user3973383
user3973383

Reputation: 11

why comparison did not return an int

I am making simple Old Maid game. Here is my class for player's hand:

class OldMaidHand(Hand):
    def removeMatches(self):
        count=0;
        originalCards=self.cards[:];
        for card in originalCards:
            match=Card(3-card.suit,card.rank);
            if match in self.cards:
                self.cards.remove(card);
                self.cards.remove(match);
                print "Hand %s: %s matches %s "%(self.name,card,match);
                count=count+1;
            return count;`

but it's showing following error:

TypeError:comparison did not return an int.

Here is my __cmp__() method in the Card class.

    def __cmp__(self,other):
        if self.suit>other.suit:
            return 1
        if self.suit<other.suit:
            return -1
        if self.rank>other.rank:
            return 1
        if self.rank<other.rank:
            return -1

Upvotes: 0

Views: 130

Answers (1)

Two-Bit Alchemist
Two-Bit Alchemist

Reputation: 18477

From the documentation for __cmp__:

Called by comparison operations if rich comparison (see above) is not defined. Should return a negative integer if self < other, zero if self == other, a positive integer if self > other.

In other words, as your error says, it should return an integer in any case.

If none of your if conditions obtain, your __cmp__ will "fall off the end" of the function, returning None which is the default for any Python function which does not explicitly return something else. This is the source of your error (since None is not an integer).

I haven't examined your code too carefully but it seems you neglected the case where both the rank and suit are equal. Perhaps as a failsafe, you should simply return 0 at the end of the function, unless you find a case where your conditions are unmet but the cards are inequal.

Upvotes: 1

Related Questions