Python recursive function doesn't return

前端 未结 3 866
情书的邮戳
情书的邮戳 2021-01-23 04:58

I\'m trying to sharpen my noob Python skills by trying a problem my son has in his college CS class. The goal is to create a function that uses recursion to process a list. The

3条回答
  •  Happy的楠姐
    2021-01-23 05:32

    You need to actually return your RecursiveProcess. Look below at your modified code.

    You aren't exactly doing anything recursively if all you do is call the function and store the value in ListIn2. You will keep overwriting your previous data. By returning, you will end up getting your recursive behaviour:

    def RecursiveProcess(ListIn2, target): #Recursive function that adds to target value the value to its right
        if target > -1:  #stop function if index is below 0
            ListIn2[target] = ListIn2[target] + ListIn2[target+1]  #Add value to the right of target to the target value
            return RecursiveProcess(ListIn2, target-1) #Call the function again with lower taget value to process the next value
        else:
            return ListIn2  #return the changed list
    
    l = [5, 10, 11, 6, 7, 1, 2, 4, 6, 7]
    d = RecursiveProcess(l, len(l)-2)
    print(d) # [59, 54, 44, 33, 27, 20, 19, 17, 13, 7]
    

提交回复
热议问题