2

我正在尝试从预定的顺子手牌中生成一个潜在的牌“出牌”列表(在这个游戏中,顺子被定义为 3 张以上的牌 - 例如[3,4,5])。困难在于找到一种方法来获取已识别顺子列表(可能包括多个未连接的顺子 - )并将它们及其包含在其中的子顺子['2D','3D','4D','5D','6D','8D','9D','10D']附加到播放列表中(对于给定的手,理想情况下输出是)[['2D','3D','4D'],['3D','4D','5D'],['4D','5D','6D'],['2D','3D','4D','5D'],['3D','4D','5D','6D'],['8D','9D','10D']]

以下是当前的尝试;

seq = ['1D','2D','3D','4D', '6D', '7D','8D', '10D', '11D', '12D']
plays = []
for card in seq:
    ind = seq.index(card)+1
    try:
        if int(seq[ind][0:len(seq[ind])-1]) - int(card[0:len(card)-1]) == 2:
            for num in xrange(len(seq[0:ind])):
                if len(seq[0:(ind-num)]) > 3:
                    plays.append(seq[0:(ind-num)])
                    plays.append(seq[num+1:ind])
                elif len(seq[0:(ind-num)]) == 3:
                    plays.append(seq[0:(ind-num)])
            print plays #debug
except IndexError:
    print 'error'
    #append from the last appended chunk up until last element?
    #arises from final element

[['1D', '2D', '3D', '4D'], ['2D', '3D', '4D'], ['1D', '2D', '3D']]

[['1D', '2D', '3D', '4D'], ['2D', '3D', '4D'], ['1D', '2D', '3D'], ['1D' ', '2D', '3D', '4D', '6D', '7D', '8D'] , ['2D', '3D', '4D', '6D', '7D', '8D' '] , ['1D', '2D', '3D', '4D', '6D', '7D'] , ['3D', '4D', '6D', '7D', '8D'] , ['1D', '2D', '3D', '4D', '6D'], ['4D', '6D', '7D', '8D']** , ['1D', '2D', '3D', '4D '], ['6D', '7D', '8D' ], ['1D', '2D', '3D'] ]

错误

粗体输出表示不需要的元素(重复或单独直线的结合)。感谢您的输入!

编辑 1:添加第 10-12 行

编辑2:添加@Steve Tjoa 提供的解决方案

(假设卡片是一系列整数)卡片 = [1, 2, 3, 4, 6, 7, 8, 10, 11, 12]

def f(cards):
    for i in range(len(cards)):
        for j in range(i+3, len(cards)+1):
            if cards[i:j] == range(cards[i], cards[i]+j-i):
                plays.append(cards[i:j])
            print plays
4

2 回答 2

2

这有帮助吗?

In [34]: def f(cards):
   ....:     return [cards[i:j]
   ....:             for i in range(len(cards))
   ....:             for j in range(i+3, len(cards)+1)
   ....:             if cards[i:j] == range(cards[i], cards[i]+j-i)]
   ....: 

In [35]: f([1, 2, 3, 4, 6, 7, 8, 10, 11, 12])
Out[35]: [[1, 2, 3], [1, 2, 3, 4], [2, 3, 4], [6, 7, 8], [10, 11, 12]]

In [36]: f([2, 3, 4, 5, 6, 8, 9, 10])
Out[36]: 
[[2, 3, 4],
 [2, 3, 4, 5],
 [2, 3, 4, 5, 6],
 [3, 4, 5],
 [3, 4, 5, 6],
 [4, 5, 6],
 [8, 9, 10]]

推理:cards[i]是顺子的第一张牌;cards[j-1]是最后一张牌。range返回连续整数。j-i是直线的长度。

于 2012-05-24T02:45:22.637 回答
0

如果您想同时显示排名和套件,这是获取播放列表的另一种方法。

plays = []
hand = ['AD','2D','3D','4D', '6D', '7D','8D', 'TD', 'JD', 'QD']
ranks = sorted([('-A23456789TJQK'.index(r), r+s) for r, s in hand], reverse = True)
for j in range(3, len(hand)):
    for i,r in enumerate(ranks):
        rnk = [x[0] for x in ranks[i:i+j]]
        if (max(rnk)-min(rnk) == j-1) and len(set(rnk)) == j:
            plays.append([x[1] for x in ranks[i:i+j]])

print plays
于 2012-05-24T03:51:39.900 回答