【问题标题】:Calculating the Nth Sequence of Length M in Python在 Python 中计算长度为 M 的第 N 个序列
【发布时间】:2012-04-19 13:15:33
【问题描述】:

我正在编写一个用于验证的库/实用程序。我将有一组元素和一个以某种顺序使用它们的被测系统。该集合代表所有可能的输入,系统将接收这些元素的有限序列。

由于有限序列的集合将是无限的,我不打算计算一个集合的所有序列,而是设想使用 python 生成器来完成以下操作:

def seq(s): # s is a set
  length = 0
  nth = 0
  # r = calculate nth sequence of length
  # if there are no more sequences of length, length += 1
  # else n += 1, yield r

我最终会将其扩展到单射和双射序列,但目前该集合的元素可以出现任意次数。

生成器是解决此问题的最佳方法吗?使用这样的生成器会消除递归带来的任何简单性吗?谁能指出任何可能对我有帮助的 itertools(或其他模块)捷径?

【问题讨论】:

    标签: python recursion set generator sequence


    【解决方案1】:

    听起来您正在寻找itertools.product。我相信这会满足您的要求:

    def seq(s):
        length = 1
        while True:
            for p in itertools.product(s, repeat=length):
                yield p
            length += 1
    

    现在你可以这样做了:

    >>> zip(range(10), seq(set((1, 2, 3))))
    [(0, (1,)), (1, (2,)), (2, (3,)), (3, (1, 1)), (4, (1, 2)), 
     (5, (1, 3)), (6, (2, 1)), (7, (2, 2)), (8, (2, 3)), (9, (3, 1))]
    

    或者这个:

    >>> test_seq = itertools.izip(itertools.count(), seq(set((1, 2, 3))))
    >>> for i in range(10):
    ...     next(test_seq)
    ... 
    (0, (1,))
    (1, (2,))
    (2, (3,))
    (3, (1, 1))
    (4, (1, 2))
    (5, (1, 3))
    (6, (2, 1))
    (7, (2, 2))
    (8, (2, 3))
    (9, (3, 1))
    

    这也可以进一步压缩,使用其他itertools:

    >>> from itertools import chain, product, count
    >>> s = set((1, 2, 3))
    >>> test_seq = chain.from_iterable(product(s, repeat=n) for n in count(1))
    >>> zip(range(10), test_seq)
    [(0, (1,)), (1, (2,)), (2, (3,)), (3, (1, 1)), (4, (1, 2)), (5, (1, 3)), 
     (6, (2, 1)), (7, (2, 2)), (8, (2, 3)), (9, (3, 1))]
    

    【讨论】:

    • 这看起来不错,我想我会使用combinations_with_replacement(,) 来允许序列中的重复?
    • @JohnCarter,好吧,上面的确实允许在序列中重复。不同之处在于,对于上面使用的 n 维笛卡尔积,顺序很重要; (1, 1, 2)(1, 2, 1) 都已生成。如果您不希望这样,那么combinations_with_replacement 是您的最佳选择。
    • 对。感谢您的澄清。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 2012-01-30
    相关资源
    最近更新 更多