3 ms·
I find something like this totally plausible and yet it is completely wrong. >>> def check_parity(x, expect_odd): ... odds = [ 1, 3, 5 ] ...
by bnegreve 6y ago
I find something like this totally plausible and yet it is completely wrong.
>>> def check_parity(x, expect_odd):
... odds = [ 1, 3, 5 ]
... if x in odds == expect_odd :
... print("ok")
... else:
... print("error")
...
>>> check_parity(5, True)
error
Crazy!
- skrebbel 6y agoCan you explain why it doesn't work?
- tryptophan 6y agoIt's: if (x in odds} and (odds == expect_odd). The 2nd expression is obviously false always.
- wadkar 6y agoBecause chaining the operator results in: > if x in odds == expect_odd : > if x in odds and odds == expect_odd : with the latter always evaluating to False (assuming expect_odd is a boolean flag).
- weare138 6y agoI'm not a Python expert so I don't know much about the internals of Python but my hunch is when Python evaluates 'x in odds' it's not storing that value internally as a boolean so when you use the '==' strict comparison Python is expecting both data types to be the same.
- weare138 6y agoIf I understand what you're getting at changing '==' to 'and' will make it work the way you're expecting. Both have to evaluate to 'True' in the if statement and passing 'False' to expect_odd will always print 'error'.
- bacon_waffle 6y agoThat wouldn't work for the even parity case. "(x in odds) == expect_odd" gives the intended behaviour and I think is easier to read as well.
- bnegreve 6y agoI know how to make this work, but a bug like this would be hard to spot.