![](/img/trans.png)
[英]Why is the code below return an empty list.I could not understand the reason of it so if someone can help me about that , that will make me happy
[英]Code I have written for a happy number checker is not working, could someone check it over?
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一起使用,但是我尝试过的任何其他数字都会使其无限循环。 有人可以看看我做错了什么并提出解决方案吗? 谢谢 :)
尝试这个:
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循环中
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:? Wiki:“如果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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.