Programming Praxis - Happy Numbers

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:

[python] 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/(10s) for i,e in enumerate(r): pass temp -= e * 10(len(r)-i) r.append(temp) return r [/python]

Method 2:

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

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:

[python] 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 [/python]

The source can also be found on Bitbucket.

Jeroen Pelgrims

Software Developer developer in Antwerp working at Unbrace
Follow me on Twitter: @jeroenpelgrims