返回项目PowerSet的递归Python函数 [英] Recursive Python function returning PowerSet of items

查看:98
本文介绍了返回项目PowerSet的递归Python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调试程序,并且遇到了问题.有人可以指导我解决这里的问题吗?

I'm trying to debug a program and am running into issues. Can anybody direct me to the issue here?

该程序用于获取项目列表,并返回这些项目的电源集列表.

The program is meant to take a list of items, and returns the list of powersets for those items.

一个例子:

>>> getAllSubsets([1,2])
[[1,2],[1],[2],[]]

代码:

def getAllSubsets(lst):
    if not lst:
        return []
    withFirst = [ [lst[0]] + rest for rest in getAllSubsets(lst[1:]) ]
    withoutFirst = getAllSubsets(lst[1:])
    return withFirst + withoutFirst

推荐答案

有更好的食谱,是的.但是我认为您的代码存在的问题是您应该将return []替换为return [[]].空集本身就是一个子集.

There are better recipes, yes. But I think the problem with your code is that you should replace return [] with return [[]]. The empty set is itself a subset.

这篇关于返回项目PowerSet的递归Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆