我不确定如何使用此代码获取collatz序列中的步骤总数:
number = int(input('Enter a number, please:'))
while number > 1:
if number % 2 == 0:
number = number / 2
print(number)
else:
number = number * 3 + 1
print(number)
# print('Steps required:',NEED TO FILL , end='')
答案 0 :(得分:0)
您似乎只想计算while
循环内所采取的步骤。添加count
变量并打印结果如下所示:
number = int(input('Enter a number, please:'))
#initiate step count
steps = 0
while number > 1:
if number % 2 == 0:
number = number / 2
print(number)
else:
number = number * 3 + 1
print(number)
# add a step for each loop
steps += 1
print('Steps required: {}'.format(steps))
在shell中运行它会产生:
$ python3 -i collatz.py
Enter a number, please:14
7.0
22.0
11.0
34.0
17.0
52.0
26.0
13.0
40.0
20.0
10.0
5.0
16.0
8.0
4.0
2.0
1.0
Steps required: 17
答案 1 :(得分:0)
试试这个:
def collatz(number): if(number%2==0): n=number//2 print(n,"\t",end="") return n else: ev=3*number+1 print(ev,"\t",end="") return ev num1=input("Enter a number: \n") step=0 try: num=int(num1) if(num==1): print("Enter an integer greater than 1") elif(num>1): a=collatz(num) while(True): if(a==1): step=step+1 break else: a=collatz(a) step+=1 print("\nNumber of steps needed:",step) else: print("Please, Enter a positive integer to begin the Collatz sequence") except: print("please, Enter an integer")