简体   繁体   English

使用递归求和两个数字(python)

[英]Using recursion to sum two numbers (python)

I need to write a recursive function that can add two numbers (x, y), assuming y is not negative. 我需要编写一个递归函数,假定y不为负,可以将两个数字(x,y)相加。 I need to do it using two functions which return x-1 and x+1, and I can't use + or - anywhere in the code. 我需要使用两个返回x-1和x + 1的函数来执行此操作,并且在代码的任何位置都不能使用+或-。 I have no idea how to start, any hints? 我不知道如何开始,有什么提示吗?

重要提示:您正在描述Peano算术

Lets say that 可以这样说

succ(x)=x+1
pre(x)=x-1

Then, (in pseudocode) 然后,(使用伪代码)

add(x,y) = {
    If(y==0) Return x;
    Return add(succ(x),pre(y))
}

Observe, this only works for non-negative y. 注意,这仅适用于非负y。

pseudo-code : 伪代码:

for i = 0 to y
    x = f(x)
next

where f(x) is your function that returns x+1 其中f(x)是您的函数,返回x + 1

or, if you can't do a for loop because that requires +s : 或者,如果您不能进行for循环,因为这需要+ s:

while (y > 0) {
    x = f(x)
    y = g(y)
}

where f(x) is the function that gives x+1 and g(y) is the function that gives y-1 其中f(x)是给出x + 1的函数,而g(y)是给出y-1的函数

In a comment the OP says: OP在评论中说:

I get an error - "maximum recursion depth exceeded". 我收到一个错误-“超出了最大递归深度”。

You can try upping the recursion limit with sys.recursionlimit (after an import sys , of course), but that will only get you up to a point. 您可以尝试使用sys.recursionlimit (当然,在import sys之后)来提高递归限制,但这只会使您步入正轨 Python does not have the optimization known as "tail recursion elimination", which (wonderful language as it may be;-) does not make it the best language to use for the specific purpose of teaching about recursion (that best language, IMHO but not just in my opinion, would be Scheme or some variant of Lisp). Python没有被称为“尾递归消除”的优化,该优化(可能是奇妙的语言;-)并不是使其成为用于教授递归的特定目的的最佳语言(即最佳语言,恕我直言,但不是)我认为,应该是Scheme或Lisp的某种变体)。 So, when y is larger that the maximum recursion limit you can set on your machine (system dependent), that error will inevitably ensue. 因此,当y大于您可以在计算机上设置的最大递归限制(取决于系统)时,将不可避免地发生该错误。

Alternatively, you may have miscoded the "base-recursion guard" which is supposed to return without further recursion when y equals 0 , or you may have tried calling the function with a y < 0 (which will inevitably "recurse infinitely", ie, produce the above mentioned error when the maximum recursion limit is, inevitably, exceeded). 或者,您可能对“基本递归防护”进行了错误编码,当y等于0 ,该编码应返回而无需进一步递归,或者您可能试图用y < 0调用函数(这将不可避免地“无限递归”,即,当不可避免地超过最大递归限制时,会产生上述错误。

def sum(a,b):
    if b==0:
        return a
    return sum(a+1,b-1)

This sounds like homework. 这听起来像作业。 So this is probably cheating: 所以这可能是作弊:

a+b is the same as a.__add__(b) , and a+ba.__add__(b) ,并且

ab is the same as a.__sub__(b) . aba.__sub__(b)

So you can easily add or subtract two numbers without using +/-. 因此,您无需使用+/-即可轻松地添加或减去两个数字。 No need for any recursion. 无需任何递归。

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

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