Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 尝试使用递归方法生成字符串的子集_Python_Python 3.x_Recursion - Fatal编程技术网

Python 尝试使用递归方法生成字符串的子集

Python 尝试使用递归方法生成字符串的子集,python,python-3.x,recursion,Python,Python 3.x,Recursion,尝试在python中使用递归实现算法。看起来缺少了一些我无法调试的内容 我的方法是有两个递归分支,并在每个递归中传递一个元素。详情如下: ## input pattern : "ab" ## output pattern : ["", "a", "b", "ab"] 对于该模式,递归树如下所示 我现有的代码如下:它没有按预期工作 def gen_subset(slist): def helper(slist,i,temp,out): if len(slist) == i

尝试在python中使用递归实现算法。看起来缺少了一些我无法调试的内容

我的方法是有两个递归分支,并在每个递归中传递一个元素。详情如下:

## input pattern : "ab"
## output pattern : ["", "a", "b", "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']]
我在这里遗漏了什么吗?

temp.append(slist[I])
更改为
temp=temp+[slist[I]

发生这种情况是因为
temp.append()
在适当的位置修改
temp
变量。
相反,我们需要将
temp
的副本传递给下一个递归调用

[['b', 'a', 'b'], ['b', 'a', 'b'], ['b', 'a', 'b'], ['b', 'a', 'b']]