序列函数错误? [英] Sequence function error?
本文介绍了序列函数错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
第3行出现错误TypeError:'int'对象不可迭代,它一直困扰着我。
示例测试:collatz_counts(4)→3#4→2→1(3个步骤)
代码我有:
def collatz_counts(x):
num = 0
for i in(x):
if i == 1:
num + = 1
return num
elif i%2 == 0:
num (i)/ 2
num + = 1
num.append(i)
else:
num =(i * 2)+ 3
num + = 1
num.append(i)
return num
解决方案 div>
使用while循环。只要修改 x
,直到你达到 1
并记录步数
def collatz_counts(x):
steps = 0
,而x!= 1:
如果x%2:
x = x * 3 + 1
else:
x = x // 2
steps + = 1
返回步骤
I'm getting an error on line 3 "TypeError: 'int' object is not iterable," and its been bothering me. Any advice/fixes appreciated.
Example test: collatz_counts(4) → 3 # 4 -> 2 -> 1 (3 steps)
Code I have:
def collatz_counts(x):
num = 0
for i in (x):
if i == 1:
num += 1
return num
elif i % 2 == 0:
num(i) / 2
num += 1
num.append(i)
else:
num = (i*2) + 3
num += 1
num.append(i)
return num
解决方案
Use a while loop. Just modify x
in place until you get to 1
and keep track of the number of steps
each time you run a cycle.
def collatz_counts(x):
steps = 0
while x != 1:
if x % 2:
x = x * 3 + 1
else:
x = x // 2
steps += 1
return steps
这篇关于序列函数错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文