python - 在Python中生成部分子集

标签 python python-2.7

坦白:这是为了上课。

我正在尝试生成长度为 1 - length(full set) 的所有子集,但它们必须按顺序排列。

因此,输入为 (4,2) 时,有效结果为 (4)、(4,2) 和 (2)。 不会是 (4,4) (2,2) 或 (2,4)

预计到达时间 (4,2,2) 也应该返回 (2,2)。

长度不是预先确定的。

我现在拥有的:

def gen_all_partials(outcomes, length):
    """
    Iterative function that enumerates the set of all sequences of
    outcomes of lengths up to given length.
    """

    answer_set = set([()])
    for dummy_idx in range(length):
        temp_set = set()
        for partial_sequence in answer_set:
            for item in outcomes:
                new_sequence = list(partial_sequence)
                new_sequence.append(item)
                temp_set.add(tuple(new_sequence))
        answer_set = temp_set
    return answer_set

这是通过给定函数部分获得的。我不明白 Python 如何在第二个“for”循环中迭代空集。除了“正确”答案之外,当前代码还输出 (4,4)、(2,2) 和 (2,4)。

我沉迷于嵌套循环并跟踪多个计数器并为所需的输出设置不同的长度。

我也尝试过这个:

def gen_all_partials(outcomes, length):
    """
    Iterative function that enumerates the set of all sequences of
    outcomes of lengths up to given length.
    """

    answer_set = set([()])
    for dummy_idx in range(length):
        temp_set = set()
        for partial_sequence in answer_set:
            for item in outcomes:
                new_sequence = list(partial_sequence)
                new_sequence.append(item)
                if new_sequence not in temp_set:
                    temp_outcomes = list(outcomes[:])
                    add_to_set = True
                    for val in new_sequence:
                        if val in temp_outcomes:
                            order_list = []
                            for dummy_bit in val:
                                order_list.append(val.index(dummy_bit)) 
                                if order_list == order_list.sort():
                                    temp_outcomes.remove(val)
                                else:
                                    add_to_set = False
                        else: 
                            add_to_set = False
                    if add_to_set:
                        temp_set.add(tuple(new_sequence))
        answer_set = temp_set
    return answer_set

最佳答案

来自永远有帮助的 itertools recipes :

from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

这包括空集,但您可以简单地更改范围来处理它。

关于python - 在Python中生成部分子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24618318/

相关文章:

python - 测量 200 个并发用户的数据传输速率

python - 如何定位NetworkX中巨型组件的中心节点?

python - 如何提取数字(以及比较形容词或范围)

使用L1 CPU Cache的c++算法的Python实现

python - 如果用户没有响应,则继续脚本

python - 从 for 循环值构建表

python - 如何设置flask github.authorized处理程序收到的 "next"url?

python - 将字符串作为输入,像计算器一样对其进行计算并返回整数答案的函数

一流属性访问的 Python 自定义初始化

python - 使用 psycopg2 从 Postgresql 中基于模式的表中选择数据