The obvious pythonic way:
from happy import find_happy_numbers if __name__ == "__main__": for number in find_happy_numbers(100): print(number)
Jokes aside, here's a Python implementation using simple memoization:
def memoize(fn): cache = {} def memoized_fn(*args): if args in cache.keys(): return cache[args] cache[args] = apply(fn, args) return cache[args] return memoized_fn @memoize def is_happy(n): next = sum([int(i)**2 for i in str(n)]) if next == 1: return True elif next > 9: return is_happy(next) else: return False def find_happy_numbers(n): for i in range(n): if is_happy(i): yield i
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
The obvious pythonic way:
Jokes aside, here's a Python implementation using simple memoization: