递归Collat​​z-猜想输出挑战

时间:2019-03-26 18:43:42

标签: python recursion

我具有用于计算collat​​z猜想的递归函数。代码产生正确的数字,它根据计数器递归调用。计数器用完后,它应该返回正确的数字-但它返回None

def collatz_con(x, revs):
    print("start")
    print(x, revs)
    if (x%2 == 0) and (revs != 0):
        print("even and revs =" + str(revs))
        holder = x//2
        print(holder)
        collatz_con(holder, revs - 1)
    elif (revs != 0):
        print("odd  and revs =" + str(revs))
        holder = ((3*x) + 1)
        print(holder)
        collatz_con(holder, revs -1)
    else:
        print("else exercised")
        return x   
print(collatz_con(1071, 14))

是否应返回x变量并打印出来?

1 个答案:

答案 0 :(得分:2)

您犯了一个常见错误,其中递归函数collatz_con()返回一个值,但是当您递归调用它时,您会忽略该返回值。我的猜测是您想要更多类似的东西:

def collatz_con(x, revs):
    print(x, revs)

    if x % 2 == 0 and revs != 0:
        print("even and revs =", revs)
        holder = x // 2
        print(holder)
        return collatz_con(holder, revs - 1)

    if revs != 0:
        print("odd and revs =", revs)
        holder = 3 * x + 1
        print(holder)
        return collatz_con(holder, revs - 1)

    print("else exercised")
    return x