我想要一些等价于下面代码的东西。下面的代码生成扑克可能的手牌模式。
from itertools import combinations
m = 13
n = 4
x = range(m) * n
y = 5
pattern = set()
for i in combinations(x, y):
pattern.add(tuple(sorted(i)))
我尝试使用itertools.combinations_with_replacement
。毫无疑问,会有像(0,0,0,0,0)或(1,1,1,1,1)这样的组合。但是一张牌中没有5张皇后和5张国王。所以我不想取5个相同的东西。如何实现受限组合迭代器
from itertools import combinations_with_replacement
m = 13
n = 4
x = range(m)
y = 5
pattern = []
for i in combinations_with_replacement(x, y):
pattern.append(i)
我希望像下面的代码。
伪代码:
m = 13
n = 4
x = range(m)
y = 5
pattern = []
for i in combinations_with_replacement_restricted(x, y, max=n):
pattern.append(i)
注:因为我是英语学习者,请修改我的语法错误。
看完文档:https://docs.python.org/2/library/itertools.html?highlight=combinations#itertools.combinations_with_replacement
我发现针对目标的内置解决方案不存在。
所以如果你想做到这一点,我认为两个解决方案可能是合适的:
[1]。让你所有的牌都不同:
from itertools import combinations
m = 13
n = 4
x = range(m * n)
y = 5
pattern = set()
# combinations from range(0, 52)
for i in combinations(x, y):
# so p/n maps to range(0, 13)
pattern.add((p / n for p in sorted(i)))
[2]。排除所有无效结果:
from itertools import combinations
m = 13
n = 4
x = range(m) * n
y = 5
pattern = set()
for i in combinations(x, y):
if min(i) == max(i):
continue
pattern.add(tuple(sorted(i)))
你可以这样做:
import itertools
# each card is a pair (value, color)
cards = [ (value, color) for value in xrange(13) for color in xrange(4) ]
# all 5 cards combinations within 52 cards
for hand in itertools.combinations( cards, 5 ) :
print hand