def next_in_chain(n): """ Given a positive integer n, computes the next element of its "happy number chain", obtained by summing the squares of its digits. Does not validate its input. :param n: a positive integer. :return: the sum of the squares of the digits of n """ digits = map(int, list(str(n))) squares_of_digits = map(lambda x: x * x, digits) return sum(squares_of_digits) def chain(n): """ Given a positive integer n, yields the entries of its happy number chain. Does not validate its input. :param n: a positive integer. """ while True: yield n n = next_in_chain(n) def is_happy(n): """ A positive integer n is "happy" if its happy number chain ends in 1. Given a positive integer n, returns whether or not it is happy. Does not validate its input. :param n: a positive integer :return: True if n is happy, False otherwise. """ seen_so_far = set() for element in chain(n): if element in seen_so_far: return False if element == 1: return True seen_so_far.add(element) if __name__ == '__main__': for i in range(1001): if is_happy(i): print(i)