lunedì 23 maggio 2011

Happy numbers in python

I'll show you a method in python to check if a number is happy.
When a number is happy? Well, you have to follow this algorithm:

1. Take a number n.
n = 23
2. Dissect it into digits.
2 and 3
3. Square them all and add them up
2^ 2 + 3 ^ 2 = 4 + 9 = 13
4. You get a new number m.
m = 13
5. If m = 1, n is happy; otherwise set n = m and repeat at 1.
1^2 + 3^2 = 1 + 9 = 10
n = 10
1 ^ 2 + 0 ^ 2 = 1
23 is happy!
6. If you run into a loop, n is not a happy number (is sad).

I've used recursion because it is fun (talking about happy numbers).

def happy(n, past = set()):
m = sum(int(i)**2 for i in str(n))
if m == 1:
return True
if m in past:
return False

[1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97]