a863: 3. Happy Numbers
http://zerojudge.tw/ShowProblem?problemid=a863
- def is_happy(n):
- if n==1:
- return True
- if count>100:
- return False
- global count
- count+=1
- N=0
- for i in str(n):
- N+=int(i)**2
- return True if is_happy(N) else False
-
- while True:
- try:
- n=int(input())
- count=0
- if is_happy(n):
- print(str(n)+’ is a happy number’)
- else:
- print(str(n)+’ is an unhappy number’)
- except:
- break
看不懂就算了的版本:
- def hh(n):
- global w,t
- t+=[n]
- if n==1:
- w=n
- return
- if len(t)>100:
- w=n
- return
- n=str(n)
- k=0
- for x in range(len(n)):
- k+=int(n[x])**2
- try:
- tt=t.index(k)
- t+=[k]
- w=k
- return
- except:
- hh(k)
-
- while True:
- try:
- a=int(input())
- w=0
- t=[]
- hh(a)
- if int(w)==1:
- print(a,’is a happy number’)
- else:
- print(a,’is an unhappy number’)
- except:
- break