from datetime import datetime def is_happy(num, the_results=None, cache=None): if num in cache: return False the_total = 0 for x in [int(y) for y in str(num)]: the_total += x ** 2 if the_results is None: the_results = set() if the_total == 1: return True # Infinite loop detected elif the_total in the_results: cache.add(num) return False else: the_results.add(the_total) return is_happy(the_total, the_results, cache) def run(the_number): the_ints = as_integer_array(the_number) pattern = [] result = square_and_sum(the_ints) while result != 1 and result != the_number and result not in pattern: pattern.append(result) result = square_and_sum(as_integer_array(result)) return result def as_integer_array(the_number): return [int(x) for x in str(the_number)] def square_and_sum(int_array): squared = [x * x for x in int_array] return sum(squared) if __name__ == '__main__': count = 0 cache = set() start_time = datetime.now() for x in range(0, 100000): if 1 == run(x): count += 1 print('there are {} happy numbers'.format(count)) print(datetime.now() - start_time)