Update square root to use a generator
Opened this issue · 0 comments
chivalry commented
Apologies if you're tired of this old tune. Perhaps I'm too obsessed with iterators and generators, but this could be a one-liner calling a next on a generator expression, something like:
def square_root(number):
return next((... for ... if ...), None)
This form of next() has a second argument that is the default value to be returned if the iterator yields no values. Otherwise, it would raise an exception. It requires the generator expression to be within brackets in order to avoid the ambiguity.
As you probably can see (or will, if you haven't learned yet about next & co), this won't generate more numbers than necessary, as a list comprehension-based solution would. Just like your solution.
https://github.com/chivalry/exercism/blob/main/python/square-root/square_root.py