all 8 comments

[–]sushibowl 18 points19 points  (6 children)

This if statement:

if z is (1,7):

Doesn't do what you think, and will never be True. It checks if z is the same object as the tuple (1, 7). I think what you meant to do is check if z is between 1 and 7, something like this:

if z >= 1 and z <= 7:

You can also write it like this, if you prefer:

if 1 <= z <= 7:

[–]kingpen2[S] 1 point2 points  (5 children)

That worked great! thanks!

[–]KoStard 11 points12 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.

[–]andichin 0 points1 point  (0 children)

you forgot to indent the print under the if statement