2015-09-26 48 views
2

下面的代碼是訂購撲克牌的手牌。它在Python 2.7中運行良好,但它在Python 3中不起作用。引起它給出TypeError的變化是什麼:無法定型的類型:tuple()< int()?TypeError:無法訂購的類型:Python 3中的元組()<int()3

def poker(hands): 
    scores = [(i, score(hand.split())) for i, hand in enumerate(hands)] 
    winner = sorted(scores , key=lambda x:x[1])[-1][0] 
    return hands[winner] 

def score(hand): 
    ranks = '23456789TJQKA' 
    rcounts = {ranks.find(r): ''.join(hand).count(r) for r, _ in hand}.items() 
    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', '7D 2S 5D 3S AC', '8C AD 8D AC 9C', '7C 5H 8D TD KS']) 
'8C AD 8D AC 9C' 
+0

哪一行會拋出這個? –

+0

贏家=排序(得分,鍵=拉姆達x:x [1])[ - 1] [0] – Nickpick

回答

4

它正在發生,因爲你是比較inttuple。在python2x中,默認cmp操作是針對不同的內置對象定義的,這些對象在python3中已被刪除。

Python 3 ignores the cmp() method. In addition to this, the cmp() function is gone! This typically results in your converted code raising a TypeError: unorderable types error. So you need to replace the cmp() method with rich comparison methods instead. To support sorting you only need to implement lt(), the method used for the 「less then」 operator, <.

Official documentation

所以,在python2,我們可以做這樣的事情

(2, 3) > 2 

,但它提出了在python3 TypeError。如果這段代碼在python2中工作,那麼很可能是由默認比較行爲隱式處理的錯誤。

現在,在你的例子: -

#value of scores that are being compared for sorting 
scores = [(0, (1, (11, 8, 7, 6, 2))), (1, (1, (12, 5, 3, 1, 0))), (2, ((2, 2, 1), (12, 6, 7))), (3, (1, (11, 8, 6, 5, 3)))] 

print(type(scores[1][1][0])) # <class 'int'> 
print(type(scores[2][1][0])) # <class 'tuple'> 

這正如我所解釋的python3不起作用。假設您比較tupleint的標準是什麼。

如果您確實想要比較不同類型的對象,則需要推出自己的tuple版本,並在您的scores中使用該對象。

class MyTuple(tuple): 

    def __lt__(self, other): 
     pass 

Default tuple comparison python 2

注: - 我不建議使用這種方法。這僅僅是爲了教學目的。

+0

我複製到堆棧交換的另一篇文章的代碼。我認爲如果它可以工作,它將非常優雅 – Nickpick

+0

有沒有辦法在這種情況下調用Python 2行爲? – Nickpick

+0

如果代碼不是bug,那麼'int'和'tuple'之間'cmp'的默認實現對於編寫它的程序員是有效的。在你的情況下,你需要使用自定義對象而不是像MyTuple這樣的元組,就像我在我編輯的文章中提到的那樣,並且定義了默認python比較的行爲。 – hspandher

2

解決方案: 將整數轉換爲元組: score =([(1,),(3,1,1,1)],[(3,1,1,2),(5, )])[flush] [直]

相關問題