python - 尝试使用递归方法生成字符串的子集
问题描述
尝试在 python 中使用递归实现算法。看起来缺少一些我无法调试的东西。
我的方法是有两个递归分支并在每次递归时传递一个元素。详情如下:
## input pattern : "ab"
## output pattern : ["", "a", "b", "ab"]
对于此模式,递归树将如下所示
# "ab" [ROOT]
# |
# -a +a
# | |
# -b +b -b +b
# => "" "b" "a" "ab"
我现有的代码如下:它没有按预期工作。
def gen_subset(slist):
def helper(slist,i,temp,out):
if len(slist) == i:
out.append(temp)
return()
else:
helper(slist,i+1,temp,out)
temp.append(slist[i])
helper(slist,i+1,temp,out)
out = []
helper(slist,0,[],out)
return out
s = "ab"
print (gen_subset([c for c in s]))
此代码产生错误的结果。
输出
[['b', 'a', 'b'], ['b', 'a', 'b'], ['b', 'a', 'b'], ['b', 'a', 'b']]
我在这里错过了什么吗?
解决方案
Change temp.append(slist[i])
to temp = temp + [slist[i]]
.
This is happening because temp.append()
modifies the temp
variable in-place.
Instead we need to pass a copy of temp
to the next recursion call.
推荐阅读
- openshift - 如何设置 okd 以使用外部 nexus docker 注册表?
- python-3.x - Pandas,连接列的值。
- c# - ServiceStack api/auth/credentials 在前端迁移时返回 404
- reactjs - 如何在 Redux-Bees 中使用 websockets
- semantic-ui - 如何使我的网站在语义 UI 中固定宽度?
- javascript - 在对象数组中获取单个键和单个值的更简单方法?
- nuxt.js - Nuxt vuex 商店没有收到 axios 请求
- javascript - 从 firebase 函数返回
- javascript - 淡入淡出背景将文字向上移动
- scala - 在 Spark scala 中,如何检查数据帧中的相邻行之间