【问题标题】:Appending to one list in recursive function在递归函数中附加到一个列表
【发布时间】:2019-12-08 17:42:55
【问题描述】:

在我的代码中,我的返回值被附加到列表中。将所有项目附加到单个列表的方法是什么?现在,每个堆栈都会创建一个列表并返回该列表。

def palindrome_partition(string):
  if len(string) <=2:
    rev = string[::-1]
    if string == rev:
        return string
    else:
        return

  pal = []
  b = string[1:-1]
  if len(b) <=1:
    return
  a = b[::-1]
  res = palindrome_partition(b)
  if res is not None:
    pal.append(res)
  if a == b:
    pal.append(b)
  return pal

结果是[[[],]] 想要的结果[ , , ]

【问题讨论】:

  • 想要的结果是什么?
  • 想要的结果:[ , , ]

标签: python recursion palindrome


【解决方案1】:

IIUC,替换

pal.append(res)

pal += res

【讨论】:

  • 当您附加 res 时,您每次都将一个列表附加到一个列表中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-26
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
相关资源
最近更新 更多