gpt4 book ai didi

python - 循环和 Collat​​z 猜想

转载 作者:太空宇宙 更新时间:2023-11-04 02:48:53 25 4
gpt4 key购买 nike

我在循环和声明变量方面遇到了问题。目前我正在制作一个关于 Collat​​z 猜想的程序,该程序应该检查从一定数量的 Collat​​z 序列中达到一个的最大步骤是什么。这是我的代码:

start_num = int(input("insert a starting Number > "))
how_many = int(input("how many times you want to check? >"))


def even_or_odd(number):
if number % 2 == 0:
return 'isEven'
else:
return 'notEven'


def collatz(n):
z = n
counter = 0
while True:
if n != 1:
if even_or_odd(n) == 'isEven':
n = n/2
counter += 1
continue
if even_or_odd(n) == 'notEven':
n = (n*3)+1
counter += 1
continue
else:
print('number ' + str(z) + ' reached 1 with : ' + str(counter) + ' steps')
return counter
break


def check_biggest_steps(steps_before, steps_after):
if steps_before > steps_after:
return steps_before
if steps_after > steps_before:
return steps_after
if steps_after == steps_before:
return steps_after


def compute_collatz(n_times, collatz_number):
for _ in range(n_times):
before = collatz(collatz_number)
collatz_number += 1
after = collatz(collatz_number)
collatz_number += 1
biggest_steps = check_biggest_steps(before, after)

print('Biggest Steps is :' + str(biggest_steps))


compute_collatz(how_many, start_num)

biggest_steps 变量始终返回最后 2 步。我知道导致此问题的原因是 biggest_step 变量位于循环内,但我无法让它在任何地方工作,我不知道该怎么做。谢谢

最佳答案

在您自己尝试之前不要阅读我的代码。

尝试制作一个列表,将每个更改附加到列表中,然后获取最后的移动次数,只需获取列表的长度即可。

.

def collatz(x):
while x != 1:
if x % 2 > 0:
x =((3 * x) + 1)
list_.append(x)
else:
x = (x / 2)
list_.append(x)
return list_


print('Please enter a number: ', end='')
while True:
try:
x = int(input())
list_ = [x]
break
except ValueError:
print('Invaid selection, try again: ', end='')


l = collatz(x)

print('\nList:', l, sep=' ')
print('Number of steps required:', len(l) - 1)

关于python - 循环和 Collat​​z 猜想,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44431763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com