4 ms·
Forgive me if I am wrong, but I believe that section 1 contains mistakes. In the implementations of evens_only, shouldn't both of the places where modulus is us
by ff0066mote 16y ago
Forgive me if I am wrong, but I believe that section 1 contains mistakes. In the implementations of evens_only, shouldn't both of the places where modulus is used be preceded by "not"?
This isn't meant to detract from the truth that "Beautiful [code] is better than ugly," I merely thought the implementation should be correct.
- rodion_89 16y agoor better yet i % 2 == 0
- deleted 16y ago[deleted]
- l0nwlf 16y agoI would go for more pythonic "not i % 2".
- fjh 16y agoI would argue that that is not very pythonic, since it breaks the "explicit is better than implicit" guideline.
- koenigdavidmj 16y agoMost Python people are okay with relying on the behaviour of what is truthful and what is not. They would often prefer to see if foo: do_stuff() over if len(foo) > 0: do_stuff()
- highfreq 16y agoI agree. Using the truthiness of non-boolean values has always seemed questionable in any language (Javascript is possibly the worst offender). For many statically typed languages this is caught as a syntax error, which is nice for those of use prone to occasionally typos.
- baddox 16y agoThe boolean equivalents of non-boolean values are well-defined and fairly simple in Python, and I believe it's encouraged (or at least extremely common) to use them as such.
- eru 16y agoIn Haskell this is caught as a type error. But you can make your own version: class ExtendedBool t where toBool :: t -> Bool instance ExtendedBool Int where toBool = (0/=) instance ExtendedBool [a] where toBool = not . null if' v a b = if (toBool v) then a else b main = if' "String" (print "True") (print "False")
- rikthevik 16y agoYeah, I don't think you can use i % 2 as an equivalent of i % 2 == 0. Maybe it's a python 3 thing, but on my 2.6.1 the mod operator just returns the remainder, it doesn't change its output if it's a boolean context (which would be perlish and highly unpythonic). I think i % 2 is just straight up incorrect. If we're talking about style, I think i % 2 == 0 is much more clear than (not i % 2). It says explicitly that the remainder of i divided by 2 is 0.
- eru 16y ago> Yeah, I don't think you can use i % 2 as an equivalent of i % 2 == 0. Maybe it's a python 3 thing, but on my 2.6.1 the mod operator just returns the remainder, it doesn't change its output if it's a boolean context (which would be perlish and highly unpythonic). $ python3 >>> not 0 True Python doesn't have Perl-like contexts, but it does treat lots of values as True or False. I do agree that i % 2 == 0 is more explicit here.
- hellrich 16y agoIt seems to work in older Python versions (tested with 2.5). I think the new implementation is more natural: even%2 = 0, and 0 is false, while uneven%2 = 1, and 1 is true.