這是我第一次在堆棧溢出,所以我很抱歉,如果格式不適合與網站相當正確。 我剛剛開始學習編程,接近2個星期過去了。我正在學習從http://openbookproject.net/thinkcs/python/english3e/index.html蟒蛇和一切都相當不錯,直到現在,我剛卡住了幾個小時。 我googled了很多,但無法找到一個妥善的解決方案,我的問題,所以我在這裏。Python:'列表中的對象'檢查和'__cmp__'溢出
我試圖讓CHM中解釋的OldMaidGame()運行沒有問題。 - 大部分代碼也來自上一章。
我發現我無法得到Deck.remove,Hand.remove_matches或任何其他類型的刪除功能的工作。經過一些調試後,我發現 當程序檢查卡片是否存在於甲板/手/等位置時發生問題。它永遠無法匹配。然後,在回顧一下 這一章後(在第16章),我發現'如果卡片/甲板/手/等等:移除(卡片)'等等。 cmp()確定卡片是否實際存在於甲板/手/等。這是我對cmp的版本,在給電子書給定的代碼添加'ace'之後。
def __cmp__(self, other):
""" Compares cards, returns 1 if greater, -1 if lesser, 0 if equal """
# check the suits
if self.suit > other.suit: return 1
if self.suit < other.suit: return -1
# suits are the same... check ranks
# check for aces first.
if self.rank == 1 and other.rank == 1: return 0
if self.rank == 1 and other.rank != 1: return 1
if self.rank != 1 and other.rank == 1: return -1
# check for non-aces.
if self.rank > other.rank: return 1
if self.rank < other.rank: return -1
# ranks are the same... it's a tie
return 0
的CMP本身似乎罰款據我所知,OFC我可以使用一些技巧如何使它更好的(像ACE檢查)。 所以我不知道爲什麼在卡片/手牌檢查卡總是返回false。 這是給定的刪除功能:
class Deck:
...
def remove(self, card):
if card in self.cards:
self.cards.remove(card)
return True
else:
return False
拼命試圖得到它的工作,我想出了這個:
class Deck:
...
def remove(self, card):
""" Removes the card from the deck, returns true if successful """
for lol in self.cards:
if lol.__cmp__(card) == 0:
self.cards.remove(lol)
return True
return False
似乎正常工作,直到我轉移到了其他非工作刪除功能:
class OldMaidHand(Hand):
def remove_matches(self):
count = 0
original_cards = self.cards[:]
for card in original_cards:
match = Card(3 - card.suit, card.rank)
if match in self.cards:
self.cards.remove(card)
self.cards.remove(match)
print("Hand {0}: {1} matches {2}".format(self.name, card, match))
count = count + 1
return count
我又做了一些調整:
class OldMaidHand(Hand):
def remove_matches(self):
count = 0
original_cards = self.cards[:]
for card in original_cards:
match = Card(3 - card.suit, card.rank)
for lol in self.cards:
if lol.__cmp__(match) == 0:
self.cards.remove(card)
self.cards.remove(match)
print("Hand {0}: {1} matches {2}".format(self.name, card, match))
count = count + 1
return count
該卡的移除工作正常,但它會給我一個錯誤(x不在列表),當我試圖刪除匹配。另外一個我們可能也可以做這個工作,但是因爲它已經感覺我走錯了路,因爲我無法修正原來的'卡在甲板/手/等'等,我來到這裏尋找一些答案/提示。
感謝您的閱讀,我非常感謝任何幫助,您可以給:)
--------------------- EDIT 1 *>
這是我當前的代碼: http://pastebin.com/g77Y4Tjr
--------------------- EDIT 2 *>
我試着每一個cmp在這裏建議,我仍然無法找到它與'進'卡。
>>> a = Card(0, 5)
>>> b = Card(0, 1)
>>> c = Card(3, 1)
>>> hand = Hand('Baris')
>>> hand.add(a)
>>> hand.add(b)
>>> hand.add(c)
>>> d = Card(3, 1)
>>> print(hand)
Hand Baris contains
5 of Clubs
Ace of Clubs
Ace of Spades
>>> d in hand.cards
False
>>>
我也試過card.py @DSM已成功使用,我得到的錯誤有太多,像在排序功能它說,它不能比較兩個卡對象。
所以我想知道,也許這是一個Python 3.2的問題,或者語法在某處改變了?
+1決定學習Python! – 2011-06-02 13:59:23
你確定卡組裏實際上有卡嗎? – 2011-06-02 14:04:46
@ Space_C0wb0y是的,其他一切正常。沒有發佈整個程序,因爲我不確定這個網站是否合適,因爲它可以在我鏈接的電子書上找到。唯一不合格的是'in'檢查。即使我只是手動創建一個空的甲板/手牌,添加1-2張牌,並嘗試檢查程序是否識別它們中的任何一個,它都會失敗。 – Ulquiomaru 2011-06-02 14:11:38