无法理解如何为每个步骤存储值

Can't understand how to store values for each step

我是初学者,正在尝试学习递归并解决一些问题(尝试子序列问题)。但是在我什至可以尝试使递归逻辑正确之前,我在尝试存储返回值时遇到了困难。这是我尝试过的和收到的输出。尝试放置一些打印命令只是为了理解。我以为下面会给我答案 = [[b,c],[c]],看来存储的值是“None”。希望有人能解释我做错了什么以及如何纠正这个问题,这样我就可以继续处理子序列问题。 谢谢。

阿润

def subseq(arr, answer=[""]):
    if len(arr) == 0:
        return("")
    print("arr", arr)
    answer += subseq(arr[1:],answer)
    print("answer", answer)
arr = ['a','b','c']
subseq(arr)

#--------------------------------------------------------------------

I was hoing to get ['b','c'] and ['c'] as the answer but can't get that. Output is as follows: arr ['a', 'b', 'c'] arr ['b', 'c'] arr ['c'] answer [''] #This followed by the following error: answer += subseq(arr[1:],answer) #TypeError: 'NoneType' object is not iterable

您的代码还有其他错误。

将递归视为:

  1. 你想在每个递归步骤中做什么
  2. 你的输入怎么比第1步操作后变小了
  3. 对步骤 2 中获得的一小部分输入进行递归。
  4. 想想递归需要停止的基本情况,把它放在最前面。

因此,您需要按以下方式修改您的代码。请关注我的评论。

def subseq(arr, answer):
    # Step 4: Base case
    if len(arr) == 0:
        return

    print("arr ", arr)

    # Step 1: Think about what you want to solve in each step
    subsequence = arr[1:]
    
    # collect your operation output in answer
    if len(subsequence) > 0:
        answer.append(subsequence)
    
    # Step 2: New input
    new_arr = arr[1:]  # should become smaller at each step


    # Step 3: Make more recursion
    subseq(new_arr, answer)

arr = ['a','b','c']
answer = []  # Allocate memory for storing answer before hand
subseq(arr, answer)
print("answer", answer)