Programming Praxis – Happy Numbers

July 23rd, 2010 by Jeroen Leave a reply »

Today’s problem had to do with Happy Numbers.

I split the problem up in two parts,  splitting up a number up in to digits and checking whether or not the number is a Happy Number.

The first part I implemented in two different ways.

Method 1:

def chop(x):
	r = []
	length = int(ceil(log(x, 10)))
	if ceil(log(x, 10)) == int(ceil(log(x, 10))):
		length += 1
	#a(dd), s(ubstract)
	for a,s in zip(range(0, length), range(length-1, -1, -1)):
		temp = x/(10**s)
		for i,e in enumerate(r):
			pass
			temp -= e * 10**(len(r)-i)
		r.append(temp)
	return r

Method 2:

def chop2(x):
	return [int(x) for x in str(x)]

Method 2 is shorter and faster, but I really wanted to try solving it by just using numbers.
String conversions feel a bit “dirty”.

Then finally, checking whether a number is a happy number or not:

def isHappyNumber(x):
	if x <= 0:
		return False
	numbers = [x]
	while x != 1:
		x = sum([a**2 for a in chop(x)])
		if x in numbers:
			return False
		numbers.append(x)
	return True

The source can also be found on Bitbucket.

Advertisement

Leave a Reply