【问题标题】:How to write a recursive function in python如何在python中编写递归函数
【发布时间】:2016-11-27 13:05:06
【问题描述】:

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

您需要设计一个迭代和递归函数,称为 replicate_iter 和 replicate_recur 分别接收两个 参数: times 是重复的次数和 data which 是要重复的数字或字符串。

函数应该返回一个包含重复数据的数组 争论。例如,replicate_recur(3, 5) 或 replicate_iter(3,5) 应该返回 [5,5,5]。如果时间参数是负数或零, 返回一个空数组。如果参数无效,则引发 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)

请多多指教

错误信息:

【问题讨论】:

  • 把你的错误回溯作为代码而不是图像。
  • 谢谢。会做。新手
  • 没有汗水。只需edit您的问题将错误消息包含为文本而不是图像,以便可以通过搜索找到。

标签: python algorithm loops recursion


【解决方案1】:

首先,考虑一下:

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

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

现在,关于您的递归解决方案,(1) 为了访问 array,replicate_recur 需要在其开头声明“global array”,因为变量 array 已声明超出函数范围; (2) 将递归调用“replicate_recur(times - 1,data)”修改为“return replicate_recur(times - 1,data)”,以便函数在times 大于零时实际返回一个值。 (也就是说,据我了解,为递归函数使用全局累加器通常被认为是不受欢迎的形式。)

【讨论】:

  • 感谢您的解释。这对我有用。您能否解释一下这条线是如何工作的: return replicate_recur(times - 1,data) +[data] 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
  • @MrTerfa 关于单线,想想如果times 是1 会返回什么f(times - 1,data)。现在想想返回值+ [data] 会变成什么?然后想一想,如果我们连续三个这样的电话呢?
  • @MrTerfa 关于修改你原来的递归,当你第一次调用times大于0的函数时,函数不会返回任何东西。它确实对修改外部array 的同一函数进行了另一次调用,但只返回任何内容。当我们最终到达return array 行时,由于没有请求,因此不会向原始调用发出该返回。在递归调用前加上 return 前缀意味着我们期望从递归调用返回值,当我们到达 return array 时,它会通过之前的调用传播。
  • 我现在明白了。谢谢。
【解决方案2】:

根据您提供的示例,也许这就是您想要的:

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]

【讨论】:

    【解决方案3】:

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

    def replicate_recur(times,data, array=None):
        if array is None:
            array = []
        if times <= 0:
            return array
        array.append(data)
        return replicate_recur(times - 1, data, array)
    

    【讨论】:

      【解决方案4】:

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

      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
      

      【讨论】:

        【解决方案5】:
        
        
        """
        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))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-08-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多