Is my implementation of happy number OK

Jon Ribbens jon+usenet at unequivocal.co.uk
Thu Apr 30 13:04:44 EDT 2015


On 2015-04-30, Cecil Westerhof <Cecil at decebal.nl> 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:
		sequence.add(num)
		if num in happy:
		    happy |= sequence
		    break
		nextnum = 0
		while num:
		    num, digit = divmod(num, 10)
		    nextnum += digit * digit
		num = nextnum
	    else:
		unhappy |= sequence
	return happy




More information about the Python-list mailing list