0
下面的撲克手評估器正在生成玩家持有的不同牌的排名。它在Python 2中運行良好,但它在python 3中不起作用,因爲sort函數不能再將元組與元素進行比較。我如何使它在python 3中表現得像在Python 2中一樣?排序算法:使用排序函數將元組中的元組與元素進行比較
的排序需要決定哪些卡是最好的:
(1, (11, 8, 7, 6, 2)) # high card 11 (rank5)
(1, (12, 11, 8, 7, 2)) # high card 12 (rank4)
((3, 2), (11, 12)) # full house (triple and pair) (rank1)
((2, 1, 1, 1), (12, 11, 7, 6)) # pair of 12 (rank3)
((3, 1, 1), (12, 6, 3)) # three of 12 (rank2)
如果一個整數相比一個元組,那麼元組的第一個項目應該是相關的。 Python 2中的排序功能將正確地排序上述,但在Python 3中,我收到一個錯誤消息整數不能比較元組。
如何修改鍵功能?
def keyfunction(x):
v= x[1]
return v
def poker(hands):
scores = [(i, score(hand.split())) for i, hand in enumerate(hands)]
#print (scores)
winner = sorted(scores , key=keyfunction)[-1][0]
return hands[winner]
def score(hand):
ranks = '23456789TJQKA'
rcounts = {ranks.find(r): ''.join(hand).count(r) for r, _ in hand}.items()
#print (rcounts)
score, ranks = zip(*sorted((cnt, rank) for rank, cnt in rcounts)[::-1])
if len(score) == 5:
if ranks[0:2] == (12, 3): #adjust if 5 high straight
ranks = (3, 2, 1, 0, -1)
straight = ranks[0] - ranks[4] == 4
flush = len({suit for _, suit in hand}) == 1
'''no pair, straight, flush, or straight flush'''
score = ([1, (3,1,1,1)], [(3,1,1,2), (5,)])[flush][straight]
return score, ranks
poker(['8C TS KC 9H 4S','AC TS KC 9H 4S', 'AD AS KD KS KC', '9C AD KD AC 8C', 'AC 5H 8D AD AS'])