为什么我得到RecursionError:超出了最大递归深度?

问题描述 投票:0回答:2

这是代码:

def isEven (n):    #function checks if the number is even or odd

    if (int(n)%2) == 0:
        True
    else:
        False


def Edit(b,x,y): #function loops through the number
   m = str(b)
   for i in range(1, len(m)+1):
        if isEven(m[-i]):
            continue
        elif int(m[-i+(len(m))]) > 5:
            b = b + 1
        else:
            b = b - 1
        y = y + 1
        x = x + 1
   Edit(b,x,y)

number = input()
Number = int(number)
caseNum = 0
moves = 0

Edit(Number,caseNum,moves)

print('Case #' + str(caseNum) + ' : ' + str(moves))

我想创建一个代码,检查数字中是否有奇数位,并递增或递减数字,直到数字中没有奇数位。

python recursion
2个回答
0
投票

我不太清楚你期望的输出,所以假设你想要一个数字中没有奇数位(4567 - > 4468)

你根本不能这样做:

n = [int(i) for i in input("Enter a number: ")]
caseNum = 0

for i, x in enumerate(n):
    if x % 2 != 0:
        if x > 5:
            n[i] += 1
        else:
            n[i] -= 1
        caseNum += 1

print("".join(str(x) for x in n), "CaseNum: ", caseNum)

如果你已经在主程序中使用了if-else,那么你真的不需要Even函数。

从您的代码开始,如果您使用的是Even函数,则需要返回值TrueFalse

 def isEven (n):    #function checks if the number is even or odd
    if int(n) % 2 == 0:
        return True
    else:
        return False

当你在没有任何停止条件的情况下调用相同的函数(循环它)时,你得到了RecursionError

 Edit(b,x,y)

函数中的这个语句正在创建问题,在限制之后,python停止执行并给你错误。

如果你能详细说明使用caseNum和移动,我就可以在程序中添加它们。


0
投票

即使没有无条件调用Edit(b,x,y)作为最后一步,你的代码仍然朝向“超出最大递归深度”,无论如何。

问题是你是根据它的数字递增或递减数字。考虑像3000这样的数字,其中有一个高阶奇数。在1000次递归调用中,您需要将其递增或递减近1000次。但是默认的堆栈深度只有1000帧,所以你已经沉没了。

但它变得更糟。考虑一个简单的数字,如10,你的递减和递增逻辑将它改为9,然后回到10,然后是9,然后是10,依此类推。

你最好像@DeepMehta一样递增和递减个别数字,而不是整个数字。

要正确控制对Edit()的递归调用,请使用x和/或y计数器确定在此调用期间是否进行了任何更改。如果没有变化,请返回号码。如果有变化,请递归以完成工作。

isEven()功能而言,您可以简单地做到:

def isEven(number):
    ''' function checks if the number is even or odd '''

    return int(number) % 2 == 0
© www.soinside.com 2019 - 2024. All rights reserved.