Python 3: Getting IndexError: list index out of range on shuffle method

2024/7/5 11:57:37

I'm building a blackjack command line game and I've run into a snag. The shuffle feature on my deck class object keeps coming up with IndexError: list index out of range on line 29. It is a sporadic bug, id say about 50% of the time it comes up. Here is the code:

import random#class constructor for cards
class card:def __init__(self, suit, card_name, card_value):self.suit = suitself.card_name = card_nameself.card_value = card_value#class constructor for the deck
class deck:def __init__(self):self.current_deck = []self.suits = ['hearts', 'diamonds','spades','clubs']self.cards = ['ace','2','3','4','5','6','7','8','9','10','jack','queen','king']def initialize(self):for i in range(len(self.suits)):for j in range(len(self.cards)):if (self.cards[j]=='2' or self.cards[j]=='3' or self.cards[j]=='4' or self.cards[j]=='5' or self.cards[j]=='6' or self.cards[j]=='7' or self.cards[j]=='8' or self.cards[j]=='9'):self.current_deck.append(card(self.suits[i], self.cards[j], int(self.cards[j])))elif (self.cards[j]=='10' or self.cards[j]=='jack' or self.cards[j]=='queen' or self.cards[j]=='king'):   self.current_deck.append(card(self.suits[i], self.cards[j], 10))else:self.current_deck.append(card(self.suits[i], self.cards[j], 11))def shuffle(self):for card in self.current_deck:j = random.randint(0, len(playing_deck.current_deck))temp = cardcard = self.current_deck[j]self.current_deck[j] = tempclass dealer:def __init__(self):self.money = 10000self.hand = []def hit(self, deck_):self.hand.append(deck_.pop())def deal(self, deck_, player_):self.hand.append(deck_.pop())class player: def __init__(self, name):self.name = nameself.money = 200self.hand = []def hit(self, deck_):self.hand.append(deck_.pop())josh = player('josh')playing_deck = deck()playing_deck.initialize()
playing_deck.shuffle()josh.hit(playing_deck.current_deck)for i in range(len(playing_deck.current_deck)):print(vars(playing_deck.current_deck[i]))
Answer

You're calling randint:

Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

If it's not obvious why this is a problem, let's use a much smaller example:

>>> a = ['x', 'y']
>>> len(a)
2
>>> a[0]
'x'
>>> a[1]
'y'
>>> a[2]
IndexError: list index out of range
>>> randint(0, 2)
1
>>> randint(0, 2)
2 # oops

This is why Python usually uses half-open ranges, where a <= N < b, instead of a <= N <= b. And why you normally want to use randrange instead of randint.


Or, even more often, when you find yourself reaching for randint or randrange, there's a good chance you wanted shuffle (which will randomly reorder the whole list in one go), or choice (which will pick a value out of a list, without needing to first pick an index), etc., so skim through the docs to see if what you want is already written.

https://en.xdnf.cn/q/120707.html

Related Q&A

How to encrypt a file

Just trimmed this down big timeI have an overall assignment that must read a file, encrypt it and then write the encrypted data to a new file.what ive tried is this:filename=input("Enter file name…

Any Idea on how Should I analyze this Algorithm? [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

Syntax error ; multiple statements found while

Why is there this syntax error Multiple statements found while compiling a single statement given when I run this code? Answer and help will be super appreciated for this python newbie here

No module named PyPDF2._codecs, even after already installed

I have installed PyPDF2==2.3.0, but I still get the error below when I import PyPDF2. The error message is:ModuleNotFoundError: No module named PyPDF2._codecs

rearding regex (python) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 10 years ago.Improv…

While Loop Guessing Number Game - Python

Im trying to make a guess the number between 1-10 game but the while loops seems to keep running. I want to program to let the user guess a number then display if its too high or low etc then start aga…

Calculating distance between word/document vectors from a nested dictionary

I have a nested dictionary as such:myDict = {a: {1:2, 2:163, 3:12, 4:67, 5:84}, about: {1:27, 2:45, 3:21, 4:10, 5:15}, apple: {1:0, 2: 5, 3:0, 4:10, 5:0}, anticipate: {1:1, 2:5, 3:0, 4:8, 5:7}, an: {1:…

Is there anything wrong with the Python code itself? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Python Iterate Over String

So Ive got a string e.g "AABBCCCASSDSFGDFGHDGHRTFBFIDHFDUFGHSIFUGEGFGNODN".I want to be able to loop over 16 characters starting and print it. Then move up 1 letter, loop over 16 characters a…

what does with open do in this situation [duplicate]

This question already has answers here:What is the Python "with" statement used for?(3 answers)Closed 7 years ago.sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN D…