Is my implementation of happy number OK

Jon Ribbens jon+usenet at
Thu Apr 30 19:04:44 CEST 2015

On 2015-04-30, Cecil Westerhof <Cecil at> wrote:
> Besides it need some documentation: is it a good implementation? Or
> are there things I should do differently?

Here's an alternative implementation which is a bit neater:

    def find_happy(maximum):
	"""Return set of happy numbers between 1 and `maximum`"""
	happy = {1}
	unhappy = set()
	for num in range(maximum + 1):
	    sequence = set()
	    while num not in sequence and num not in unhappy:
		if num in happy:
		    happy |= sequence
		nextnum = 0
		while num:
		    num, digit = divmod(num, 10)
		    nextnum += digit * digit
		num = nextnum
		unhappy |= sequence
	return happy

More information about the Python-list mailing list