如何在python中编写递归函数

时间:2016-11-27 13:05:07

标签: python algorithm loops recursion

我一直坚持这个问题的解决方案很长一段时间我写了一段按要求工作的代码,但我似乎在编译结束时遇到错误

  

您需要设计一个迭代和一个名为的递归函数   replicate_iter和replicate_recur将分别收到两个   参数:重复的次数和数据的次数   是要重复的数字或字符串。

     

该函数应该返回一个包含重复数据的数组   论点。例如,replicate_recur(3,5)或replicate_iter(3,5)   应该返回[5,5,5]。如果times参数为负或零,   返回一个空数组。如果参数无效,则引发ValueError。

我的代码如下:

def replicate_iter(times,data):

    emptyArray = []
    if not isinstance(data, int) and not isinstance(data, str):
        raise ValueError
    if times <= 0:
        print emptyArray
    if not isinstance(times,int):
        raise ValueError
    else:
        while times > 0:
            emptyArray.append(data)
            times -= 1
        return emptyArray

array = []

def replicate_recur(times,data):

    if not isinstance(data,int) and not isinstance(data,str):
        raise ValueError
    if not isinstance(times,int):
        raise ValueError
    if times <= 0 and len(array) != 0:
        return array
    elif times <= 0 and len(array) <=0:
        return []
    else:
        array.append(data)
        replicate_recur(times - 1,data)

请帮助提出建议

错误讯息: enter image description here

5 个答案:

答案 0 :(得分:1)

首先,想一想:

def f(times,data):
  return [] if times == 0 else f(times - 1,data) + [data]

print(f(3,5)) # [5,5,5]

现在,关于递归解决方案,(1)为了访问arrayreplicate_recur需要在一开始就声明,&#34; global array,&# 34;因为变量array是在函数范围之外声明的; (2)修改递归调用,&#34; replicate_recur(times - 1,data),&#34;到&#34; return replicate_recur(times - 1,data),&#34;为了使函数在times大于零时实际返回一个值。 (也就是说,正如我所理解的那样,它通常被认为是具有递归函数的全局累加器的不良形式。)

答案 1 :(得分:0)

根据您提供的示例,这可能是您想要的:

array = []
def replicate_recur(times, val):
    if(isinstance(times, int) and times > 0):
        array.append(val)
        return replicate_recur(times-1, val)
    return array
print(replicate_recur(3, 5)) # [5,5,5]



array = []
def replicate_iter(times, val):
    if(isinstance(times, int) and times > 0):
        for i in range(times):
            array.append(val)
        return array
    raise ValueError
print(replicate_iter(3, 5)) #[5,5,5]

答案 2 :(得分:0)

您不得使用全局变量。第二次调用您的函数会导致错误的结果。改为使用内部函数或可选参数。

python parser.py eztest.txt Start -t

答案 3 :(得分:0)

也许你应该分解逻辑,总是变得更具可读性,因此它变得更容易实现。你应该避免全局变量,尤其是全局变量,它们会给你带来很大的痛苦。

def rep_rec(times, data, pack=[]):
    pack += [data]
    return pack if times < 2 else rep_rec(times-1, data, pack)


def replicate_recur(times, data):
    if not times or not data:
        return []
    if isinstance(times, int) and (isinstance(data, int) or isinstance(data, str)):
        return rep_rec(times, data) if times > 0 else []
    raise ValueError

答案 4 :(得分:0)



"""
A.  In recursions, in general, some input is minimized until some minimum condition.
    "eg: in f(x-2), x is the input" 



B.  In the following recursion, multiples of x "eg: x TIMES f(x-2)" are
    computed as x gets smaller and smaller by 2 "eg: f(x MINUS 2)", 
    until x finally reaches 1 "eg: if x==ONE return 1", the minimum CONDITION value.



C.  The recursion multiplies by many values generated by calls of function "f",
    until mininum is reached.
    "eg: x TIMES value-AT-f-CALL_a(x-2) TIMES value-AT-f-CALL_b(x-2)....



D.  When mininum CONDITION is reached, or in other words, when x reaches 1, the recursion 
    multiplies by 1, instead of another value generated by function "f" call.
    "eg: x TIMES value-AT-f-CALL_a(x-2) TIMES value-AT-f-CALL_b(x-2) TIMES 1"

    NOTE: This is why the recursion ends, as it no longer multiplies by value at f-call.



E.  In "TIMES 1" in D above, because 1 is the minimum RETURN value
    "eg: if x==1: return ONE", this means the minimum CONDITION is reached.

    NOTE: if we had x PLUS f(x-2), then the mininum value would be 
    ADDED TO (instead of multiplied by) the SUM (instead of the product).
"""

def f(x):
    """This is a recursive function f to generate product of x, as x decreases by 2"""
    if x == 1:
        return 1
    else:
        return (x * f(x-2))