排序算法:使用sort函数将元组中的元组与整数进行比较

时间:2015-09-27 12:43:43

标签: python sorting python-3.x tuples

下面的扑克手牌评估员正在生成玩家持有的不同牌的排名。它在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中的sort函数会正确地对上面的内容进行排序,但是在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'])

1 个答案:

答案 0 :(得分:2)

在将score分配到单元素元组时,您可以简单地转换指示高卡的整数。

...
score = ([(1, ), (3,1,1,1)], [(3,1,1,2), (5,)])[flush][straight]
...