How to check range equivalence

One of my unittests checks to see if the range is configured correctly after reading the log file, and I would just like to test var == range(0,10) . However, range(0,1) == range(0,1) evaluates to False in Python 3.

Is there an easy way to check range equivalence in Python 3?

+6
source share
4 answers

In Python3, range returns iterability of type range . Two range are equal if and only if they are the same (i.e., using the same id .) To check if its contents are equal, convert range to list :

 list(range(0,1)) == list(range(0,1)) 

This works great for short ranges. For very large ranges, Charles G Waldman's solution is better.

+10
source

The first proposed solution β€” using a β€œlist” to include ranges in lists β€” is inefficient, since it will first turn range objects into lists (potentially consuming a lot of memory if ranges are large), and then compare each item. Consider, for example, a = range (1,000,000), the β€œrange” object itself is tiny, but if you force it to a list, it becomes huge. Then you need to compare one million elements.

Answer (2) is even less effective, since assertItemsEqual is not only going to instantiate lists, but also sorts them before doing an elementary comparison.

Instead, since you know that objects are ranges, they are equal when their steps, start and end values ​​are equal. For instance.

ranges_equal = len(a)==len(b) and (len(a)==0 or a[0]==b[0] and a[-1]==b[-1])

+6
source

Try assertItemsEqual , (in docs ):

 class MyTestCase(unittest.TestCase): def test_mytest(self): a = (0,1,2,3,4) self.assertItemsEqual(a, range(0,4)) 
+1
source

Another way to do this:

ranges_equal = str(a)==str(b)

A string representation indicates the start, end, and step of the ranges.

This question makes me think that perhaps Python should provide a way to get these attributes from the range object itself!

+1
source

Source: https://habr.com/ru/post/899130/


All Articles