简体   繁体   English

Powerset递归,列表理解python3

[英]Powerset recursive, list comprehension python3

I'm new to Python3 and are trying to do a recursive powerset function. 我是Python3的新手,正在尝试做一个递归powerset函数。 It should use list comprehension. 它应该使用列表理解。

I wrote: 我写:

def powerset(seq):
    if not seq:
       return [[]]
    return powerset(seq[1:]) + [[seq[0]] + n for n in powerset(seq[1:])]

This function works but I got feedback and was told it was unnecessary to call the function two times. 该函数有效,但是我得到了反馈,并被告知没有必要两次调用该函数。 It did to much computing. 它对很多计算都起到了作用。 It should easily be able to compute up to 20 powersets. 它应该能够轻松地计算多达20个功率集。 So how should I do? 那我该怎么办? I can't get it to work without calling the function twice. 如果不两次调用该函数,就无法使其正常工作。 Thanks. 谢谢。

Just calculate powerset(seq[1:]) once, store it in a variable, and use it twice: 只需计算powerset(seq[1:]) ,将其存储在变量中,然后使用两次:

def powerset(seq):
    if not seq:
        return [[]]
    ps = powerset(seq[1:])
    return ps + [[seq[0]] + n for n in ps]

The difference to yours is that this way, you use ps twice, but you compute it just once. 与您的不同之处在于,这种方式您使用 ps两次,但是只计算一次。


Alternatively, you could use a double list-comprehension (if you like that sort of thing...) 另外,您可以使用双重列表理解(如果您喜欢这种东西...)

def powerset(seq):
    return [x for ps in powerset(seq[1:]) for x in ([seq[0]] + ps, ps)] if seq else [[]]

Here, the same temporary variable ps is defined inside the list comprehension. 在此,列表理解定义了相同的临时变量ps Note, however, that the results will be in a slightly different order this way. 但是请注意,这种方式的结果顺序会稍有不同。


I feel very unclear. 我感到非常不清楚。 I actually don't understand how just assigning it to a variable can change that? 我实际上不明白,仅将其分配给变量怎么会改变呢? It means the same thing? 这意味着同一件事吗?

You seem to think too much in terms of pure math here. 您似乎在这里对纯数学的想法太多了。 In programming, y = f(x) does not mean "y is the same as/synonymous for f(x)", but "assign the result of f(x) to y". 在编程中, y = f(x)并不意味着“ y与f(x)相同/同义词”,而是“将f(x)的结果分配给y”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM