【问题标题】:Python - all lottery combinations - no duplicates, in orderPython - 所有彩票组合 - 没有重复,按顺序
【发布时间】:2013-07-28 06:43:28
【问题描述】:

我编写了一个脚本来打印彩票组合。我的目标是:彩票中有 6 个数字,介于 1-49 之间,这意味着有 13,983,816 种组合。我想按顺序打印出所有组合,同时确保没有重复。

到目前为止,这是我的代码:

import random
numbers = []
for i in range(2):
    for j in range(6):
        numbers.append(random.randint(1,49))
        for k in range(j):
            while numbers[j]==numbers[k]:
                numbers[j]=random.randint(1,49)
    print sorted(numbers)
    numbers = []
f = open('combinations.txt', 'w')
f.write(str(sorted(numbers)))

问题是:

终端中的输出是:

[18, 20, 27, 32, 44, 48]
[5, 7, 10, 13, 33, 45]

我想从[1,2,3,4,5,6] 开始,到[44,45,46,47,48,49] 结束。所以我需要订购结果。

另外,我尝试将列表转换为字符串,以便将结果放入一个大文本文件中,但我现在只是将[] 打印到文本文件中。

【问题讨论】:

    标签: python


    【解决方案1】:

    使用itertools.combinations:

    >>> from itertools import combinations
    >>> for comb in combinations(range(1,50), 6):
    ...     print comb      #Hit Enter at your own risk
    

    将组合打印到文本文件:

    with open('combinations.txt', 'w') as f:
       for comb in combination:
           f.write(str(comb) + '\n')
    

    【讨论】:

    • 哇,这真的很简单。谢谢阿什维尼。不知道有这样的模块。
    • 是否需要使用 for 循环将所有结果打印到 txt 文件?
    • 我希望文本文件中的每个组合都在换行符上(\n)
    • 迭代结果并写入文件不会比解包迭代器更好吗?考虑到元素的数量是巨大的!
    • Hit Enter at your own risk: 在我的机器上打印 49choose6 个组合需要 55865.068640177684 秒。那是 15 个半小时!
    【解决方案2】:

    您正在清除列表然后写入文件。

    from itertools import combinations
    f = open('combinations.txt', 'w')
    for comb in combinations(range(1,50), 6):
        f.write(str(comb))
        f.write('\n')
    f.close()
    

    但是请确保您至少有 350 MB 的可用磁盘空间!还有一些空闲时间。

    (我检查了 348168480 字节:

    >>> s = 0
    >>> for comb in combinations(range(1,50), 6):
    ...    s += len(repr(comb))+2
    ... 
    >>> s
    348168480
    

    )。

    【讨论】:

      【解决方案3】:
      **import itertools
      f= open('combinations.txt','w')
      numb = [1,2,3,4,5,6,7]
      it = itertools.combinations(numb,3)
      for x in it:
          f.write(str(x))
          f.write('\n')
      f.close()**
      

      你去,只需添加尽可能多的数字 numb 并将 it 变量更改为 r 的对应项

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-25
        • 1970-01-01
        • 2018-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多