【问题标题】:Generator of combinations [duplicate]组合生成器[重复]
【发布时间】:2018-12-16 02:22:18
【问题描述】:

我想编写一个代码,它给我所有可能的 n 个元素的组合,长度为 k>n。这段代码的问题是我很快就耗尽了内存。我想知道是否有人知道如何解决这与生成器。我不想获得列表元素的所有可能组合。我想获得一定长度的元素的所有组合。 谢谢。

def allstrings(alphabet, length):
    """Find the list of all strings of 'alphabet' of length 'length'"""

    if length == 0: return []

    c = [[a] for a in alphabet[:]]
    if length == 1: return c

    c = [[x,y] for x in alphabet for y in alphabet]
    if length == 2: return c

    for l in range(2, length):
        c = [[x]+y for x in alphabet for y in c]

    return c

if __name__ == "__main__":
    for p in allstrings(['a','b','c'],4):
        print (p)

【问题讨论】:

  • 你看过itertools吗?我假设您将其作为一个学习练习,而不是因为您实际上需要这三个字母的所有组合 - 但请注意 combinationsproduct 等都带有您的“大致等效”代码可以阅读以了解如何自己做。
  • 这是一个例子,我需要大约 10000 长度的 64 个元素的组合,但我得到了 Memoryerror。还是谢谢!
  • “我需要长度为 10000 的 64 个元素的组合” - 不,您不需要,您需要找到一种更好的方法来解决您想要使用该输出解决的任何问题。即使你避开了内存问题,你也永远无法完成所有输出。

标签: python python-3.x generator combinations code-generation


【解决方案1】:
import itertools

itertools.combinations('alphabet', length)

来自How to get all possible combinations of a list’s elements?

【讨论】:

    猜你喜欢
    • 2014-09-29
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多