循环和Collat​​z猜想 [英] Loops and Collatz Conjecture

查看:44
本文介绍了循环和Collat​​z猜想的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a problem with loops and declaring variables. currently I am making a program about Collatz Conjecture, the program should check what is the biggest steps to reach one from certain amount of Collatz Sequence. here's my code :

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 变量,但是我无法在不知道该怎么办的地方使它工作.谢谢

this biggest_steps variable always return the last 2 steps. I know what causing this problem is that biggest_step variable located inside the loop but I can't get it working anywhere don't know what to do. Thanks

推荐答案

在您亲自尝试之前,请不要阅读我的代码.

Don't read my code until you have tried it yourself.

尝试创建一个列表,将每个更改附加到列表中,然后获取末尾的移动数量,只需获取列表的长度即可.

Try to make a list that appends every change to a list, then to get the number of moves at the end, just get the length of the list.

.

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)

这篇关于循环和Collat​​z猜想的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆