简体   繁体   English

如何实现受限组合迭代器?

[英]How do I implement restricted combinations iterator?

I want something equivalent to the following code. 我想要等同于以下代码的东西。 The following code generate poker possible hand patterns. 以下代码生成扑克可能的手形。

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)))

I tried to use itertools.combinations_with_replacement . 我试图使用itertools.combinations_with_replacement Not surprisingly there are combinations like (0, 0, 0, 0, 0) or (1, 1, 1, 1, 1). 毫不奇怪,有类似(0,0,0,0,0)或(1,1,1,1,1)的组合。 But there are no 5 Queens and 5 Kings in a cards. 但是一张牌中没有5个皇后和5个国王。 So I don't want to take 5 same things. 所以我不想做5件同样的事情。 How do I implement restricted combinations iterator. 如何实现受限组合迭代器。

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)

I want like the following code. 我想要下面的代码。

Pseudo code: 伪代码:

m = 13
n = 4
x = range(m)
y = 5
pattern = []
for i in combinations_with_replacement_restricted(x, y, max=n):
    pattern.append(i)

PS Because I'm English learner, please modify my grammar mistakes. 附注:由于我是英语学习者,请修改我的语法错误。

After reading the docs: https://docs.python.org/2/library/itertools.html?highlight=combinations#itertools.combinations_with_replacement 阅读文档后: https : //docs.python.org/2/library/itertools.html? highlight = combinations# itertools.combinations_with_replacement

I found that a built-in solution for your target don't exists. 我发现您的目标没有内置的解决方案。

So if you want to make this, I think the two solution may be suitable: 因此,如果您要这样做,我认为两种解决方案可能是合适的:

[1]. [1]。 Make all your cards distinct: 让您所有的卡片都与众不同:

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]. [2]。 Exclude all invalid results: 排除所有无效结果:

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)))

You could do this : 您可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM