a = int(raw_input("Enter a number to check if it is happy:"))
l = map(int, str(a))
c = 0
while 1:
for i in l:
b = i
c = c + b **2
if c == 1:
print "Happy Number!"
raw_input("Hit enter to end")
break
elif c == a:
print ("Not a Happy number")
raw_input("Hit enter to end")
break
else:
l = map(int, str(c))
这是我用 Python 编写的代码,它适用于数字 1 和 0,但是我尝试过的任何其他数字都会让它无限循环。有人可以看看我做错了什么并提出解决方案吗?谢谢:)
供参考:http://en.wikipedia.org/wiki/Happy_number
试试这个:
a = int(raw_input("Enter a number to check if it is happy: "))
visited = set()
while 1:
if a == 1:
print "Number is happy!"
break
a = sum(int(c) ** 2 for c in str(a))
if a in visited:
print "Number is sad!"
break
visited.add(a)
您应该保留在此过程中生成的所有值:
def is_happy_number(n):
seen = set()
while True:
digits = [int(c) for c in str(n)]
n = sum(digit**2 for digit in digits)
if n == 1:
return True
elif n in seen:
return False
seen.add(n)
>>> is_happy_number(1)
True
>>> is_happy_number(7)
True
>>> is_happy_number(11)
False
这是因为如果你有一个循环,这并不意味着循环将从你开始的地方开始。例如:
11 -> 2
2 -> 4
4 -> 16
16 -> 37
37 -> 58
58 -> 89
89 -> 145
145 -> 42
42 -> 20
20 -> 4
如您所见,您以"11"开头,但循环以"4"开头。
while 循环中放置一个 print 语句
while 1:
print(l)
并查看用户输入时会发生什么,比如说2
.
您需要重置c = 0
:
else:
l = map(int, str(c))
c = 0
不满意的数字的条件也需要改变。输入调试打印语句后,我想您将看到需要做什么。
有 2 个问题,您需要重置"c",它几乎永远不会自行循环。试试这个:
a = int(raw_input("Enter a number to check if it is happy:"))
l = map(int, str(a))
while 1:
c = 0
for i in l:
b = i
c = c + b **2
if c == 1:
print "Happy Number!"
raw_input("Hit enter to end")
break
elif c == 4:
print ("Not a Happy number")
raw_input("Hit enter to end")
break
else:
l = map(int, str(c))
我移动了"c = 0"命令并调整了 elif 语句
为什么如果 elif c == a: ?维基 : "如果 n 不满意,那么它的序列不会变为 1。相反,发生的事情是它最终进入了循环"
试试这个:
r=int(raw_input("Enter Number :"))
happy=[]
for _ in range(r):
number=_
l=[]
s=0
while not (s in l[:-1]) and s!=1:
s=0
for __ in str(number):
s+= int(__)**2
l.append(s)
number=s
if l[-1]==1:
happy.append(_)
print ("Happy Numbers are :")
print happy
number=int(input("enter how many happy number to print"))
count=0
print("the first {} happy numbers are:".format(number))
for i in range(1,100000):#you can change the range if you want more happy numbers
n=i
while n!=1 and count!=number:
num=n
temp=0
while num!=0:
rem=num%10
temp=temp+(rem**2)
num=num//10
n=temp
if n==4:#condition to break the loop if it is no a happy number
break
if n==1:
count=count+1
print (i)