簡體   English   中英

如何實現受限組合迭代器?

[英]How do I implement restricted combinations iterator?

我想要等同於以下代碼的東西。 以下代碼生成撲克可能的手形。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM