Python homework not working - receving an error - python

I am trying to write this code but I Receve the following error and I am not sure exactly why it is not printing out.
The assigment is to make sure that whenever we pull out for example Ace of Spades, Ace of Hearts, Ace of Diamonds and Ace of Clubs they are not to be in the [my_cards] section.
I tried the following code:
import random
standard_cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"]
my_cards = {"Hearts": standard_cards, "Diamonds": standard_cards, "Clubs": standard_cards, "Spades": standard_cards}
new_cards = list(my_cards)
picked_cards = []
for card in range(3):
random.shuffle(my_cards)
chosen_card_color = random.choice(my_cards)
chosen_card = random.choice(chosen_card_color)
my_cards.remove(chosen_card)
picked_cards.append(chosen_card_color + " " + chosen_card)
print("User took these 3 cards:\r\n", picked_cards)
Here is the error I receive:
"C:\Python lectures\TestovProekt\venv\Scripts\python.exe" "C:/Python lectures/TestovProekt/Domashno.py"
Traceback (most recent call last):
File "C:\Python lectures\TestovProekt\Domashno.py", line 19, in <module>
random.shuffle(my_cards)
File "C:\Users\BOP\AppData\Local\Programs\Python\Python39\lib\random.py", line 362, in shuffle
x[i], x[j] = x[j], x[i]
KeyError: 0
Process finished with exit code 1
Any help would be really appreciated!

As noted in The_spider's answer, there are a number of issues with your original code. Their answer addresses those issues, so I will propose a different solution using a list of card tuples:
import random
import itertools
ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"]
suits = ["Spades", "Hearts", "Clubs", "Diamonds"]
cards = list(itertools.product(ranks, suits))
deck = cards.copy()
random.shuffle(deck)
user_hand = [deck.pop() for _ in range(3)]
Output:
[(3, 'Diamonds'), ('J', 'Spades'), (10, 'Clubs')]
From here, it'd be pretty straight-forward to use a dictionary to store "players", and deal new hands to all the players in the correct order (instead of 3 cards at once for each player which is not how poker hands are dealt).

mycards is a dictionary, which you can't shuffle. As you want to choose a card color here, I think you intended to chose from new_cards, which does contain the 4 card colors. This also requires that you've to get the card itself with a dictionary key. Also, first shuffling and then choosing random appears me a bit useless, you can't concatenate strings and int and, as Random Davis said, you should copy your standard_list. Otherwise, the cards will be removed from every color, and not only from the one you just chosen, meaning that you'll never get 2 the same card of a different type.
The entire code should look something like this:
import random
standard_cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"]
my_cards = {"Hearts": standard_cards.copy(), "Diamonds": standard_cards.copy(), "Clubs": standard_cards.copy(), "Spades": standard_cards}
#you can leave one of them uncopied, as it won't affect the other ones anymore now.
new_cards = list(my_cards)
picked_cards = []
for card in range(3):
chosen_card_color = random.choice(new_cards)
chosen_card = random.choice(my_cards[chosen_card_color])
my_cards[chosen_card_color].remove(chosen_card)
picked_cards.append(chosen_card_color + " " + str(chosen_card))
print("User took these 3 cards:\r\n", picked_cards)

Related

calling function multiple times with new results

I wanted to create a poker simulation that creates a certain number of 5-card poker hands, to see how many times hands I need to play till I get the royal flush...
I wrote a function that generates 5 cards but when i run the function multiple times it won't work --> i get 5*x cards instead of multiple hands with each 5 cards
import random
d = []
h = []
def cards():
l1 = ["Herz", "Karo", "Pik", "Kreuz"]
l2 = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
for i in range(10):
d.append([])
for k in range(10):
d[k].append(l1[random.randint(0, (len(l1) - 1))])
d[k].append(l2[random.randint(0, (len(l2) - 1))])
for a in d:
if a not in h:
h.append(a)
if len(h) == 5:
break
else:
continue
return h
for i in range(2):
print(cards())
When I run the code, I get the following:
[['Karo', 8], ['Herz', 5], ['Pik', 13], ['Herz', 12], ['Karo', 3]]
[['Karo', 8, 'Karo', 5], ['Herz', 5, 'Karo', 6], ['Pik', 13, 'Herz',
4], ['Herz', 12, 'Herz', 5], ['Karo', 3, 'Pik', 3], ['Karo', 8,
'Kreuz', 3], ['Karo', 9, 'Kreuz', 3], ['Pik', 13, 'Herz', 10], ['Pik',
6, 'Karo', 11], ['Karo', 2, 'Pik', 13], []]
Your code currently has global lists that it keeps appending to. This is almost certainly not what you want.
I would suggest creating a deck of cards, and sampling them without replacement to get a hand of five. You can get up to 10 such hands from a deck of 52 cards. A better way might be to create the deck and shuffle it, picking off 5 cards at a time until it contains fewer than 5 cards.
In either case, you could then pass each hand through a function that tests if it is a flush or whatever else you want.
All the tools you will need for this (until you use numpy), are in the itertools and random modules.
First create a global deck. There is no need to do this multiple times because it will slow you down to no purpose. The deck of cards won't change, only their order will:
rank = [str(x) for x in range(2, 11)] + list('JQKA')
suit = list('♠♥♦♣')
deck = list(''.join(card) for card in itertools.product(rank, suit))
Now you can use this deck to generate from 1 to 10 hands at a time with no repeating cards between them. The key is that shuffling the deck is done in place. You don't have to regenerate the deck every time:
def make_hands(cards=5, hands=None):
if hands is None:
hands = len(deck) // cards
if cards * hands > len(deck):
raise ValueError('you ask for too much')
if cards < 1 or hands < 1:
raise ValueError('you ask for too little')
random.shuffle(deck)
result = [deck[cards * i:cards * i + cards] for i in range(hands)]
You can change the desired number of cards per hand and hands per deck with this function. Let's say that you also have a function to check if a hand is a flush or not called isflush. You could apply it like this:
def how_many():
shuffles = 0
hands = 0
while True:
shuffles += 1
cards = make_hands()
for hand in cards:
hands += 1
if isflush(hand):
return shuttles, hands
shuffles, hands = how_many()
print(f'It took {hands} hands with {shuffles} reshuffles to find a flush')

How do you print values in lists with their index number in Python 2.7?

I am trying to make a Blackjack game in python. I ran into a problem because I am trying to use the random module with my game. I used the random module to get a number that coordinates with the index number in my list. The list I made consisted of card face values. I don't know how to print these values using the random index number, though. Here is my code:
# this is a blackjack game made in python
import random
import time
# make a list full of the card values
cards = (["A", "K", "Q", "J", 2, 3, 4, 5, 6, 7, 8, 9, 10])
indexNum1 = random.randint(0,12)
indexNum2 = random.randint(0,12)
indexNum3 = random.randint(0,12)
indexNum4 = random.randint(0,12)
indexNum5 = random.randint(0,12)
for card in cards:
print card(indexNum1)
print card(indexNum2)
print card(indexNum3)
print card(indexNum4)
print card(indexNum5)
I hope someone can help me solve this problem. Thanks!
You can index cards directly, e.g.:
print(cards[indexNum1])
But if you want in a loop you should iterate over the indexes:
for cardidx in (indexNum1, indexNum2, indexNum3, indexNum4, indexNum5):
print(cards[cardidx])
But you are making this much harder than you need to, because currently your code could return 5 Aces - which I assume you don't want:
cards = ["A", "K", "Q", "J", 2, 3, 4, 5, 6, 7, 8, 9, 10]
hand = random.sample(cards, k=5)
for card in hand:
print(card)
If you want to properly simulate a deck of cards, you'll have to do this:
import random
def clean_deck():
return list("AJQK234567890") * 4
def draw_cards(deck, n):
return [deck.pop() for _ in range(n)]
deck = clean_deck()
random.shuffle(deck)
for card in draw_cards(deck, 5):
print(card)
This keeps track of the deck of cards, literally shuffles them, which is conveniently a random function, and then "draws" from the deck (pops). You have to keep track of the deck so you could, for example, draw 4 aces but then there wouldn't be any more left. This approach is also persistent across card-drawings - when you draw cards from the deck, they are actually removed, so you also can't draw more than 4 aces in an entire game. It will crash if you try to draw from an empty deck, although you could put an if statement in draw_cards to refill the deck if needed, but you should be aware that this would happen if the deck ran out - it could lead to weird things like 5 aces in a game.
I've changed all your digits to strings, as there's no use for them as integers if some cards aren't integers. (An alternative is to keep them all as integers, which you can do with the range function - at a guess range(13), or if you want to go from 2, range(2, 15)). I've also changed 10 to 0 as 0 was unused and that made it a lot more concise. It should be easy enough to change back should you wish.
The difference between this and the other approaches is that the other approaches never remove cards (pop). They just randomly pick cards and then put them back, although they've been drawn.
If you want to randomly choose k cards without repetition and keep the indices, this may helps:
import random
cards = (["A", "K", "Q", "J", 2, 3, 4, 5, 6, 7, 8, 9, 10])
indices = random.sample(range(len(cards)), k=5)
print 'Indices are:', indices, '\nCards chosen are:',[cards[index] for index in indices]

Python List, taking one item from one to another

(newbie) I have looked for answers, however, other examples are not sufficient for what I am looking for. As the title states, I am simply trying to take one item, or in this case card , from one list to another. The two lists are called 'deck' and 'hand.'
Once you pull from one list, it goes into the other, and gets deleted from its original.
Edit made more specific:
deck = [cat, cat, cat, cat, cat, cat, cat, dog, dog, dog, dog, dog, dog, bird, bird, shark, shark, shark]
hand = []
new_deck = []
def startUpCards():
if len(deck) >= 7:
hand = random.sample(deck, 7)
new_deck = [item for item in deck if item not in hand]
deck = list(new_deck)
elif len(deck) < 7:
hand = random.sample(deck, len(deck))
new_deck = [item for item in deck if item not in hand]
deck = list(new_deck)
So above is what you start out with, and everything comes out correct as intended. However, this is where my problem comes in, although no error occurs:
def addNewCard():
if len(deck) > 0:
hand.extend(random.sample(deck, 1))
new_deck = [item for item in deck if item not in hand]
deck = list(new_deck)
else:
sleep(2)
print ("You don't have any more cards in your deck!")
startUpCards()
cardChosen = input("Which card do you want to draw?")
def rmv_hand():
hand.remove(cardChosen)
addNewCard()
`print(hand)`
The issue that I am finding is that after the first draw, hand is shortened by 1, possibly meaning it didn't draw from deck, right?
I also see that my print string ("You don't have any more cards in your deck!") is printing waaay before I expect it to! What's going on?
You're going through far too much work. Use randrange to select a card by position. Use pop to remove that element from the deck, and immediately append it to the receiving hand. Here is a simple example:
import random
deck = [1, 2, 3, 4, 5]
hand = [11, 12, 13, 14, 15, 16, 17]
# Choose a random card from the deck *by position*
draw_pos = random.randrange(len(deck))
print "Pulling card #", draw_pos, "from deck to hand"
hand.append(deck.pop(draw_pos))
print deck
print hand
Sample output:
Pulling card # 2 from deck to hand
[1, 2, 4, 5]
[11, 12, 13, 14, 15, 16, 17, 3]
Does that get you going?

list index out of range even with the correct output?

I am making a simple program called "go fish" for a class.
player1Hand = [2, 4, 6, 8, "J", "Q", "K"]
player2Hand = [3, 4, 5, 6, 9, 10, "A"]
player1Guesses = [2, 8, "J", 4, "Q"]
player2Guesses = [6, 9, "A", 5, 3]
basically there are 5 turns (10 total outputs). If player 1 guess is in the player 2 hand then i am supposed to output "HERE'S MY CARD" and "GO FISH" if the card is not in the hand and vice versa. I got it work, but i keep getting a out of index error.
for i in range(20):
if player1Guesses[i] in player2Hand:
print ("HERE'S MY CARD")
else:
print ("GO FISH")
if player2Guesses[i] in player1Hand:
print ("HERE'S MY CARD")
else:
print("GO FISH")
I have tried changing the range to 21 and 19 but i still get the same error and output.
GO FISH
HERE'S MY CARD
GO FISH
GO FISH
GO FISH
GO FISH
HERE'S MY CARD
GO FISH
GO FISH
GO FISH
Traceback (most recent call last):
File "C:\Users\Allen\Dropbox\Computer Science\GoFish.py", line 8, in <module>
if player1Guesses[i] in player2Hand:
IndexError: list index out of range
I am getting the correct input that i need but for some reason it still says that the index is out of range. Why am a getting this error even when the program works? I'm also a bit new to coding and if you see any thing easier or simpler I can do with my code feel free to point it out! Thanks in advance!
- avbirm
Your problem lies here:
for i in range(20):
if player1Guesses[i] in player2Hand:
You iterate over 20 items (0 to 19), but only have 5 in your list:
player1Guesses = [2, 8, "J", 4, "Q"]
Changing to range(5) will not throw the error, alternatively you can check if i is smaller than the length of player1Guesses as well as the check you are currently doing. Same goes for player2Guesses.
Check whether i is a valid index or not, value of i must be smaller than the length of list.
player1Hand = [2, 4, 6, 8, "J", "Q", "K"]
player2Hand = [3, 4, 5, 6, 9, 10, "A"]
player1Guesses = [2, 8, "J", 4, "Q"]
player2Guesses = [6, 9, "A", 5, 3]
for i in range(20):
if i < len(player1Guesses) and player1Guesses[i] in player2Hand:
print ("HERE'S MY CARD")
else:
print ("GO FISH")
if i < len(player2Guesses) and player2Guesses[i] in player1Hand:
print ("HERE'S MY CARD")
else:
print("GO FISH")
Iterate over actual length of your list:
length_of_list = len(player1Guesses)
for i in range(length_of_list):
if player1Guesses[i] in player2Hand:
print ("HERE'S MY CARD")

Moving items around in a python list?

This is the final product. IF anyone else has any tips to cut it up, please let me know! Thanks a lot for the help!
def triple_cut(deck):
''' (list of int) -> NoneType
Modify deck by finding the first joker and putting all the cards above it
to the bottom of deck, and all the cards below the second joker to the top
of deck.
>>> deck = [2, 7, 3, 27, 11, 23, 28, 1, 6, 9, 13, 4]
>>> triple_cut(deck)
>>> deck
[1, 6, 9, 13, 4, 27, 11, 23, 28, 2, 7, 3]
'''
joker1 = deck.index(JOKER1)
joker2 = deck.index(JOKER2)
first = min(joker1, joker2)
first_cards = []
for cards in range(len(deck[:first])):
cards = 0
pop = deck.pop(cards)
first_cards.append(pop)
joker1 = deck.index(JOKER1)
joker2 = deck.index(JOKER2)
second = max(joker1, joker2)
second_cards = []
for cards in deck[second + 1:]:
pop = deck.pop(deck.index(cards))
second_cards.append(pop)
second_cards.reverse()
for card in second_cards:
deck.insert(0, card)
deck.extend(first_cards)
raah I need to type more because my post is mostly code: please add more details sss ss
A hint:
p = list('abcdefghijkl')
pivot = p.index('g')
q = p[pivot:] + p[:pivot]
List slicing is your friend.
answer to the second revision
when the function is finished, it won't mutate the deck.
The problem is that you didn't give the full code. I'm guessing it looks like this:
def triple_cut(deck)
…
deck = q
And according to your docstring you call it as
deck = […]
triple_cut(deck)
and have gotten confused that the assignment deck = q doesn't propagate out of triple_cut(). You can't modify the formal parameters of a method so the assignment remains local to triple_cut and does not affect the module level variable deck
The proper way to write this is
def triple_cut(cuttable)
…
return cuttable[first:] + cuttable[:first]
deck = […]
deck = triple_cut(deck)
where I changed the name of the argument to cuttable to for purposes of explanation. You could keep the argument name as deck but I wanted to show that when you thought you were assigning to deck you were really assigning to cuttable and that assignment wouldn't carry out of triple_cut().

Categories