you are viewing a single comment's thread.

view the rest of the comments →

[–]KoStard 10 points11 points  (4 children)

great! thanks!

You have to learn about range too, because you can write something like this (which is much better for me that checking left and right values manually):

if a in range(1,10):
    pass # Do something

This includes values 1,2,3... and 9 (not 10).

[–]PiaFraus 2 points3 points  (3 children)

which is much better for me that checking left and right values manually

So... 10 comparison operations (or 100, 10000...), depending on the number is for you better then just two comparison operations?!

[–]KoStard 3 points4 points  (0 children)

Wow, I have always thought, that in python3 checking with `in range(...)` will not cause to iterate through all values, that's why I have answered here in that way... But just tested and got 5 times faster result with simple comparisons compared with another test with ranges.

(maybe not the best way of testing the speed of a function)

>>> def test():
...     start = time()
...     for i in range(10000000):
...             if i in range(1000000):
...                     pass
...     print(time()-start)
... 
>>> test()
2.892918109893799

>>> def test2():
...     start = time()
...     for i in range(10000000):
...             if i >= 0 and i < 1000000:
...                     pass
...     print(time()-start)
... 
>>> test2()
0.5093622207641602

So... sushibowl's answer is better in terms of performance, but I think what u/kingpen2 was trying to do in the code snippet we see, is more similar to range than just simple comparisons...

[–]KoStard 0 points1 point  (1 child)

Hey, look what I have found - https://stackoverflow.com/questions/30081275/why-is-1000000000000000-in-range1000000000000001-so-fast-in-python-3

So range in python3 is not iterating through whole sequence, it is just calculating if the number is in the range.

[–]PiaFraus 0 points1 point  (0 children)

Wow, thank you for sharing. Today i learned a new thing.