1

我正在尝试使用 itertools 创建三个抛硬币的所有可能组合的对,例如 ['HHH', 'TTT'], ['HHH', 'THH'] .. [TTT', 'HTH' ] , .. 等。我想将这些对作为单独的字符串访问,到目前为止我有这个;这似乎不是很理想?

from itertools import *

combs = []

combs.extend([list(x) for x in combinations(product('HT', repeat = 3), 2)])

for l in combs:
    (one, two) = l
    print ''.join(one), ''.join(two)

==编辑==

不确定是否可以编辑原始问题 - 但这里是..

删除重复项的最佳方法是什么,例如对(THT,THT)和反向对 - 反向重复,例如(HHH,TTT)和(TTT,HHH)?

谢谢你。

4

4 回答 4

4

生成所有 3 次投掷,然后从该列表中生成所有对。

import itertools

toss3 = map(''.join, itertools.product('HT', repeat=3))
toss3_pairs = list(itertools.product(toss3, repeat=2))
于 2013-02-03T18:20:39.193 回答
0
>>> combs.extend([''.join(y) for x in combinations(product('HT', repeat = 3), 2) for y in x])
>>> combs
['HHH', 'HHT', 'HHH', 'HTH', 'HHH', 'HTT', 'HHH', 'THH', 'HHH', 'THT', 'HHH', 'TTH', 'HHH', 'TTT', 'HHT', 'HTH', 'HHT', 'HTT', 'HHT', 'THH', 'HHT', 'THT', 'HHT', 'TTH', 'HHT', 'TTT', 'HTH', 'HTT', 'HTH', 'THH', 'HTH', 'THT', 'HTH', 'TTH', 'HTH', 'TTT', 'HTT', 'THH', 'HTT', 'THT', 'HTT', 'TTH', 'HTT', 'TTT', 'THH', 'THT', 'THH', 'TTH', 'THH', 'TTT', 'THT', 'TTH', 'THT', 'TTT', 'TTH', 'TTT']
于 2013-02-03T18:13:51.740 回答
0

试试这个代码:

#没有迭代工具

默认投掷(N):
    L = ['']
    对于范围内的 i(0,N):
        L=[l+'H' for l in L]+[l+'T' for l in L]
    返回 L

打印投掷(4)
于 2017-06-24T16:35:23.347 回答
-1

尝试这个:

import itertools

combs = []

combs.extend([y for y in itertools.combinations([''.join(x) for x in itertools.product('HT', repeat = 3)], 2)])

print combs

输出:

[('HHH', 'HHT'), ('HHH', 'HTH'), ('HHH', 'HTT'), ('HHH', 'THH'), ('HHH', 'THT'), ('HHH', 'TTH'), ('HHH', 'TTT'), ('HHT', 'HTH'), ('HHT', 'HTT'), ('HHT', 'THH'), ('HHT', 'THT'), ('HHT', 'TTH'), ('HHT', 'TTT'), ('HTH', 'HTT'), ('HTH', 'THH'), ('HTH', 'THT'), ('HTH', 'TTH'), ('HTH', 'TTT'), ('HTT', 'THH'), ('HTT', 'THT'), ('HTT', 'TTH'), ('HTT', 'TTT'), ('THH', 'THT'), ('THH', 'TTH'), ('THH', 'TTT'), ('THT', 'TTH'), ('THT', 'TTT'), ('TTH', 'TTT')]
>>> 
于 2013-02-03T18:13:58.550 回答