3 ms·
Not that it really matters, but since he lamented that the second Python solution was "longer and less elegant", I'll point out that that algorithm can be writt
by shmageggy 8y ago
Not that it really matters, but since he lamented that the second Python solution was "longer and less elegant", I'll point out that that algorithm can be written in a functional style that is both short and (IMO) somewhat elegant. However with reduce being removed as a built-in since Python 3, this is arguably not Pythonic.
from functools import reduce
squares = (x * x for x in range(10))
min_and_max = lambda current, x: [min(current[0], x), max(current[1], x)]
minimum, maximum = reduce(min_and_max, squares, [next(squares)]*2)
print(minimum)
print(maximum)
- c8g 8y agosquares = [x * x for x in range(10)] print(min(squares)) print(max(squares)) this one works and looks good.
- wyldfire 8y agorange(10) doesn't properly demonstrate the material differences between generators and lists. Like posted elsewhere, tee is an appropriate solution that preserves the generator's benefits over a list. It's too bad that the example is so synthetic.
- shmageggy 8y agoOne downside of both solutions is that they both traverse the list twice, which could be expensive when we're talking about real data and not toy problems.