简体   繁体   English

无法弄清楚如何在递归函数中增加变量

[英]Can't figure out how to increment a variable within a recursive function

I am trying to create a python script for the collatz conjecture (if a number's odd, times it by three and add 1, and if it's even, divide by two).我正在尝试为collat​​z猜想创建一个python脚本(如果一个数字是奇数,则乘以3并加1,如果是偶数,则除以2)。 I can't figure out how to successfully increment a variable that shows how many iterations of the function and I think it has something to do with it being recursive.我不知道如何成功地增加一个变量来显示函数的迭代次数,我认为它与递归有关。 Here's what I've got so far:这是我到目前为止所得到的:

def collatz(n):
    list_terminate = [0, 1, 2, 4]
    if n in list_terminate:
        return n
    else:
        if n % 2 == 0:
            print(n)
            iterations += 1
            return collatz(n // 2)
        if n % 2 == 1:  
            iterations += 1
            print(n)
            return collatz((n * 3) + 1)

There are a few options...有几个选项...

1) Change the function signature to include the number of iterations. 1) 更改函数签名以包含迭代次数。 This way, you can pass the information 'up the chain'这样,您就可以将信息“向上链”传递

2) Change the scope of num iterations such that the variable exists outside the function. 2) 改变 num 迭代的范围,使得变量存在于函数之外。

3) Add a recursive function inside collatz. 3)在collat​​z内部添加递归函数。

approach (1, 3)方法 (1, 3)

def collatz(n):

    def recursion(x, iterations):
        print(f"{iterations}: {x}")
        if x in [0,1,2,4]:
            return x, iterations

        if x % 2 == 0:
            return recursion(x//2, iterations + 1)
        else:
            return recursion((x*3) + 1, iterations + 1)

        return n

    n, steps = recursion(n, 0)

approach (2)方法 (2)

iterations = 0
def collatz(n):
    global iterations

    print(f"{iterations}: {n}")
    if n in [0,1,2,4]:
        return n, iterations

    iterations += 1
    if n % 2 == 0:
        return collatz(n//2)
    else:
       return collatz((n*3) + 1)

The variable does not persist between function calls.该变量不会在函数调用之间持续存在。 If you want to have multiple values passed between functions, then pass it as a parameter to your function and return both.如果您想在函数之间传递多个值,请将其作为参数传递给您的函数并返回两者。

def collatz(n, iterations):
    list_terminate = [0, 1, 2, 4]
    if n in list_terminate:
        return (n, iterations)
    else:
        if n % 2 == 0:
            print(n)
            iterations += 1
            return collatz(n // 2, iterations)
        if n % 2 == 1:  
            iterations += 1
            print(n)
            return collatz((n * 3) + 1, iterations)

If you don't like calling your function like, collatz(n, 0) , then use this is a wrapper function.如果您不喜欢像collatz(n, 0)那样调用您的函数,那么请使用这是一个包装函数。

def collatz_helper(n, iterations):
        list_terminate = [0, 1, 2, 4]
        if n in list_terminate:
            return (n, iterations)
        else:
            if n % 2 == 0:
                print(n)
                iterations += 1
                return collatz(n // 2, iterations)
            if n % 2 == 1:  
                iterations += 1
                print(n)
                return collatz((n * 3) + 1, iterations)

def collatz(n):
    return collatz_helper(n, 0)

Your problem statement is little confusing but you may try the below code, if it suits you.您的问题陈述有点令人困惑,但如果适合您,您可以尝试以下代码。

def collatz(n):
    iterations = 0
    list_terminate = [0, 1, 2, 4]
    if n in list_terminate:
        return n
    elif n % 2 == 0:
        # print(n)
        iterations += 1
        return ("No. of iterations : ", iterations, n//2)
    elif n % 2 == 1:
        iterations += 1
        # print(n)
        return ("No. of iterations : ", iterations,(n * 3) + 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM