简体   繁体   English

Python 递归幂集 function 用于元组

[英]Python recursive powerset function for tuples

I am trying to create a function that returns a powerset (all subsets of a given tuple of numbers) in the form of a tuple of tuples.我正在尝试创建一个 function 以元组元组的形式返回一个幂集(给定数字元组的所有子集)。

I have followed code that I have found previously, but this returns the output as a list of lists rather than a tuple of tuples.我遵循了我之前找到的代码,但这会将 output 作为列表列表而不是元组的元组返回。

def subs(S):
    if S == []:
        return [[]]

    x = subs(S[1:])

    return x + [[S[0]] + y for y in x]

This correctly returns: [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] for an input of subs([1,2,3])这正确返回: [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]的输入subs([1,2,3])

However I am looking for the function to input a tuple and return a tuple of tuples, such that the output would be:但是我正在寻找 function 来输入一个元组并返回一个元组的元组,这样 output 将是:

>>> print (subs((1,2,3))
((), (3), (2), (2, 3), (1), (1, 3), (1, 2), (1, 2, 3))

Any help would be appreciated, thanks.任何帮助将不胜感激,谢谢。

Here you go:这里是 go:

pip install more-itertools

from more_itertools import powerset
print(tuple([x for x in powerset( (1, 2, 3) )]))

Output: Output:

((), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3))

mashing tuples together or making new tuples from old ones is a bit tricky because they are immutable.将元组混合在一起或从旧元组制作新元组有点棘手,因为它们是不可变的。 Here is a hint that may put you in the right direction, along with the tip about indexing in the other solution.这是一个提示,可能会让您朝着正确的方向前进,以及有关在其他解决方案中建立索引的提示。 You can use the "scatter" operator to unpack an existing tuple into pieces when making a new one as such:在创建新元组时,您可以使用“scatter”运算符将现有元组解压缩成碎片:

In [12]: c = ((2,3),(4,),(99,0,8))                                              

In [13]: d = (*c, (7,6,5))                                                      

In [14]: d                                                                      
Out[14]: ((2, 3), (4,), (99, 0, 8), (7, 6, 5))

The function for lists can be converted to use tuples instead.列表的 function 可以转换为使用元组。 There is no direct equivalent of a list comprehension because the object needs to be mutable during the loop, but the result can be converted using tuple() .没有直接等效的列表推导,因为 object 在循环期间需要是可变的,但可以使用tuple()转换结果。 Care is needed with the syntax for 1-element tuples, so some extra commas have to be inserted in a couple of places.需要注意 1 元素元组的语法,因此必须在几个地方插入一些额外的逗号。

def subs(S):
    if S == ():
        return ((),)

    x = subs(S[1:])

    return x + tuple([(S[0],) + y for y in x])

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

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