 @virnuls/

Happy Numbers One of the OCR Coding Challenges

Files
• main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def squarify(n):
# sum of squared digits
result = 0
# loop through string version of number
for digit in str(n):
# add the square of the digit to the sum
result += int(digit)**2
# return the total
return result

def isHappy(number):
numbers = [number]
happy = True
while number != 1:
# replace number with sum of squares of digits
number = squarify(number)
# are the numbers repeating?
if number in numbers:
# it's not happy...
happy = False
# ... so we'll stop
number = 1
else:
# store number to check for repeats
numbers.append(number)
# return whether the number is happy
return happy

# list of happy numbers
happy = []
# number we're checking
n = 1
# number of happy numbers found
count = 0
# repeat until we've found eight happy numbers
while count < 8:
if isHappy(n):
# increase the count
count +=1
# add the number to the list
happy.append(n)
# move on to the next number
n += 1
print("The first eight happy numbers are:")
print(happy)