Reputation: 21
I'm attempting to sort a "hand" array of card objects for a texas-hold-em game in Python, where the card objects hold three values: strings for suits, strings/integers for values, and integers for their "ranking" when checking for straights.
class Card:
def __init__(self, suit, val, rank):
self.suit = suit
self.value = val
self.rank = rank
def show(self):
print("{} of {}s".format(self.value, self.suit))
I also have a class for each player, who has a "pocket" of two cards, and a seven-card hand that includes the pocket and the board.
class Player:
def __init__(self, name):
self.pocket = []
self.hand = []
self.temp = []
To check for a straight flush, I feel like I need to have my self.hand array sorted by rank so I can easily roll through the suit/rank values to see if that miraculous hand is there. Since it's such a small data set I elected for a bubble sort, which I implemented by
self.hand.append(Card("Diamond", 5, 5))
self.hand.append(Card("Spade", "Ace", 1))
self.hand.append(Card("Diamond", "Queen", 12))
self.hand.append(Card("Diamond", 10, 10))
self.hand.append(Card("Diamond", "King", 13))
self.hand.append(Card("Diamond", 9, 9))
self.hand.append(Card("Diamond", "Jack", 11))
for x in self.hand:
self.temp.append(x.rank)
n = len(self.temp)
for i in range(n - 1):
for j in range(0, n - i - 1):
if(self.temp[j] > self.temp[j + 1]):
self.hand[j], self.hand[j + 1] = self.hand[j + 1], self.hand[j]
for i in self.hand:
i.show()
This bubble sort algorithm worked with a set of integers in another program, but when I display the hand here it remains unsorted. There are no error messages. Any idea where I'm wrong?
Upvotes: 0
Views: 713
Reputation: 177
You forgot to swap the values in self.temp
. Just add this inside the inner loop:
self.temp[j], self.temp[j + 1] = self.temp[j + 1], self.temp[j]
Also, unless you're trying to implement bubble sort, you should directly use .sort()
method, which would be more optimal
Upvotes: 1