loading...

re: Write a script to find "Happy Numbers" VIEW POST

FULL DISCUSSION
 

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
code of conduct - report abuse