I found myself keep writing pretty long one-liner code(influenced by shell pipe), like this:
def parseranges(ranges, n):
"""
Translate ":2,4:6,9:" to "0 1 3 4 5 8 9...n-1"
== === == === ===== =========
"""
def torange(x, n):
if len(x)==1:
(x0, ) = x
s = 1 if x0=='' else int(x0)
e = n if x0=='' else s
elif len(x)==2:
(x0, x1) = x
s = 1 if x0=='' else int(x0)
e = n if x1=='' else int(x1)
else:
raise ValueError
return range(s-1, e)
return sorted(reduce(lambda x, y:x.union(set(y)), map(lambda x:torange(x, n), map(lambda x:x.split(':'), ranges.split(','))), set()))
I felt ok when I written it.
I thought long one-liner code is a functional-programming style.
But, several hours later, I felt bad about it.
I'm afraid I would be criticized by people who may maintain it.
Sadly, I've get used to writing these kind of one-liner.
I really want to know others' opinion.
Please give me some advice. Thanks
I would say that it is bad practice if you're sacrificing readability.
It is common wisdom that source code is written once but read many times by different people. Therefore it is wise to optimize source code for the common case: being read, trying to understand.
My advice: Act according to this principle. Ask yourself: Can anybody understand any piece of my code more easily? When the answer is not a 100% "No, I can't even think of a better way to express the problem/solution." then follow your gut feeling and reformat or recode that part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With