3 ms·
abs(x) >= 1 and abs(x) <= 3 Is also unidiomatic in Python. 1 <= abs(x) <= 3 Means the same thing and tightens it up a bit, and reads better since it's indi
by Jtsummers 1y ago
abs(x) >= 1 and abs(x) <= 3
Is also unidiomatic in Python.
1 <= abs(x) <= 3
Means the same thing and tightens it up a bit, and reads better since it's indicating that you're testing if something is in a range more clearly.
EDIT: To add:
The filter, list construction, and len aren't needed either. It's just:
sum(map(predicate, diffs)) # this counts the number of elements in diffs which satisfy predicate, map is lazy so no big memory overhead
Or alternatively:
sum(predicate(diff) for diff in diffs)
The predicate is complex enough and used twice, so it warrants extraction to its own named function (or lambda assigned to a variable), but even if it were still embedded this form would be slightly clearer (along with adding the line breaks and removing the extra list generations):
sum(map(lambda line: all(1 <= abs(x) <= 3 for x in line)
and (all(x > 0 for x in line) or all(x < 0 for x in line)),
diffs))
- chrismorgan 1y agoOoh yes, thanks, I didn’t even think about that, I was too focused on the other parts. Much nicer, updated.