This is a function.
def cut_dk():
a = []; b = []
random.shuffle(deck__)
slice = deck__[:2]
a.append(slice[0])
b.append(slice[1])
return a,b
c = cut_dk()
p1 = c[0]
p2 = c[1]
I have this function at the top of the program along with other functions.
It draws from a predefined list.
When calling this function dynamically in the program it returns the same variables.
It's the cutting of a card deck (two cards, highest wins the draw), when the cards are equal it needs to draw again (this is the problem, a second draw), a new selection from the list, yet it just repeats the variables it has in memory.
Calling the function again in a conditional statement just returns the same initial variables acquired on the first run, so I am unable to repeat the cut dynamically as part of the game play.
I would manage my deck as an object here with a class. This would allow us to define a deck, which is stored as an object and perform multiple functions against the deck whilst retaining the state changes from different functions.
class deck:
"""
Class designed to manage deck including iterations of changes.
Shuffling the deck will retain shuffle changes
"""
def __init__(self):
self.deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 'J', 'Q', 'K', 'A']
self.original = self.deck[:]
def shuffle(self):
"""
Shuffle deck in-place. self.deck will be modified
"""
random.shuffle(self.deck)
def cut(self):
"""
Shuffles deck and draws the two top-most cards
Returns: tuple(2) two cards from top of the deck
"""
self.shuffle()
a, b = self.deck[:2]
return a, b
def highest_draw(self):
"""
Calls self.cut() to shuffle and retrieve 2x top-most cards.
If cards match the deck is shuffled and cut again.
Returns: 2 Unique cards from top of the deck
"""
a, b = self.cut()
while a == b:
a, b = self.cut()
return a, b
def reset(self):
self.deck = self.original[:]
game = deck()
game.deck
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 'J', 'Q', 'K', 'A']
game.shuffle()
game.deck
#['A', 7, 5, 9, 8, 'J', 'K', 6, 4, 3, 1, 'Q', 2]
game.reset()
game.deck
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 'J', 'Q', 'K', 'A']
game.cut()
#('A', 'Q')
game.highest_draw()
#('J', 2)
You would still need to define how you determine the "highest" card, however this is dependant on your deck, which you have left out of the question.
It sounds as if a generator function would be useful here. You call the function once to set up your iterator and then 'draw' cards from that iterator (in this case the iterator is 'cards'). Notice you have to catch the case where you run the whole deck and it's tied throughout. I've sprinkled print statements through this to make it easier to understand how generators work.
import random
deck__ = list(range(3))*2
def draw_from_shuffled():
random.shuffle(deck__)
print(f'Deck after shuffling: {deck__}')
for c in deck__:
yield c
cards = draw_from_shuffled() #cards is now an iterator
while True:
try:
a = next(cards)
b = next(cards)
except StopIteration:
print(f'End of deck!')
cards = draw_from_shuffled()
continue
print(f'Drew {a} and {b}')
if a != b:
break
print('Hand done.')
Sample output:
Deck after shuffling: [2, 2, 1, 1, 0, 0]
Drew 2 and 2
Drew 1 and 1
Drew 0 and 0
End of deck!
Deck after shuffling: [0, 0, 2, 2, 1, 1]
Drew 0 and 0
Drew 2 and 2
Drew 1 and 1
End of deck!
Deck after shuffling: [0, 2, 1, 0, 1, 2]
Drew 0 and 2
Hand done.
More on generators: https://realpython.com/introduction-to-python-generators/
Related
I am trying to generate a blackjack game but I cannot get the values my_score and computers_score to update. They keep giving me value of 0. Can anyone advise?
Code is below. I am expecting the sums of the picked cards for my hand and computer's hand to correspond to the scores, but I am getting return values of 0.
import random
# Create the deck and two empty hands
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
my_hand = []
my_score = 0
computers_hand = []
computers_score = 0
# Choose two cards from deck randomly and place into each hand
def hand_builder(chosen_hand, chosen_score):
pick_card = random.choice(cards)
chosen_score = 0
chosen_hand.append(pick_card)
chosen_score += pick_card
for n in range(2):
hand_builder(my_hand,my_score)
hand_builder(computers_hand,computers_score)
print(my_hand)
print(my_score)
print(computers_hand)
print(computers_score)
You have to return your values:
import random
# Create the deck and two empty hands
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
my_hand = []
my_score = 0
computers_hand = []
computers_score = 0
# Choose two cards from deck randomly and place into each hand
def hand_builder(chosen_hand, chosen_score):
pick_card = random.choice(cards)
chosen_score = 0
chosen_hand.append(pick_card)
chosen_score += pick_card
return chosen_score
for n in range(2):
# save the output from the function
my_score += hand_builder(my_hand,my_score)
computers_score += hand_builder(computers_hand,computers_score)
print(my_hand)
print(my_score)
print(computers_hand)
print(computers_score)
The reason that the _hand variable is updated is because it is a list. One can update a list in a function without returning a value.
Please read for exmaple: https://www.mygreatlearning.com/blog/understanding-mutable-and-immutable-in-python/
Or use google to look into mutable and immutable variables.
I'm new to Python and coding in general and am trying to create a blackjack game in Python but I'm having trouble getting the point counter point_selection to update based on the card values in the player's hand:
deck_points = {2 : 2, 3 : 3, 4 : 4, 5 : 5, 6 : 6, 7 : 7, 8 : 8, 9 : 9, 10 : 10, 'J' : 10, 'Q'
: 10, 'K' : 10, 'A' : 11 }
dealer_hand = []
player_hand = []
dealer_points = 0
player_points = 0
def deal_initial_cards(hand, point_selection):
for i in range(2):
i = random.choice(list(deck_points))
hand.append(i)
for card in hand:
point_selection += deck_points[card]
deal_initial_cards(dealer_hand, dealer_points)
print(dealer_points)
Using the above code, the counter never updates past '0' and I'm not sure what I'm doing wrong. Any help is appreciated.
Here's a more Pythonic solution that fixes your main bug about your function deal_initial_cards() operating on a copy of its (immutable) int argument point_selection then throwing away the result, since it doesn't have a return point_selection (or store the result in a class member self.points). (Also, I made all your dict keys strings: '2','3',.... It's usually customary to represent '10' as 'T' to make all cards a single letter).
But since you're essentially declaring a Hand class, then instantiating two objects of it (dealer_hand, player_hand). deal_initial_cards() is essentially a Hand._init__() in disguise, so we have a data member cards (best not to also call it hand). See how simple and clean ph = Hand() is; no need for globals. Moreover, we could statically compute points inside the __init__() function and return it (or, better, store it in self.points inside each hand object), but that would be a bad decomposition, since if we subsequently add cards to self.cards, points wouldn't get updated. So, much more Pythonic is to make points a property of the class. We then access it
without parentheses: dh.points, not dh.points(). Last, note the use of a list comprehension (instead of a for-loop-append) to generate self.hand. And inside points(), note the use of a generator expression deck_points[card] for card in self.cards, again more Pythonic than for-loop counter. So this small example is a great showcase of Python idiom and decomposition. We can add a __str__() method to Hand. (You could also have a Card class, but really that would be overkill.)
import random
deck_points = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J' : 10, 'Q'
: 10, 'K' : 10, 'A' : 11 }
# No globals, so no need to initialize anything
class Hand:
def __init__(self):
self.cards = [random.choice(list(deck_points)) for _ in range(2)]
#property
def points(self):
return sum(deck_points[card] for card in self.cards)
def __str__(self, join_char=''):
return join_char.join(card for card in self.cards)
#deal_initial_cards(dealer_hand, dealer_points)
ph = Hand()
dh = Hand()
print('Dealer: ', end='')
print(dh.points)
print('Player: ', end='')
print(ph.points)
Python ints are immutable, this means dealer_points isn't updated. Initialy they have the same id(use id()), but when you change the variable inside the function it creates a new variable. To fix your code you need to do something like
deck_points = {2 : 2, 3 : 3, 4 : 4, 5 : 5, 6 : 6, 7 : 7, 8 : 8, 9 : 9, 10 : 10, 'J' : 10, 'Q'
: 10, 'K' : 10, 'A' : 11 }
dealer_hand = []
player_hand = []
dealer_points = 0
player_points = 0
def deal_initial_cards(hand, point_selection):
for i in range(2):
i = random.choice(list(deck_points))
hand.append(i)
for card in hand:
point_selection += deck_points[card]
return point_selection
dealer_points = deal_initial_cards(dealer_hand, dealer_points)
print(dealer_points)
whereas a list, which you probably noticed, is mutable. This means the list inside the function stays the same(keeps its id) even when its edited.
Hi I am trying to compare a list of picked numbers to a list of randomly generated numbers. I want to know how many times it took to get the same numbers in the same sequence picked. I am using the choice() function which i have imported. Please see my code below. I seem to continue to get an infinite loop and never generate the same list as "my ticket"
My code below
from random import choice
my_ticket = (9, 'z', 4, 0)
lottery_numbs = ['a', 'z', 'i', 't', 'u', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
winning_numbers = []
picked_sequences = []
increment = 0
while True:
for pick in range(4):
pick = choice(lottery_numbs)
winning_numbers.append(pick)
if winning_numbers in picked_sequences:
continue
else:
picked_sequences.append(winning_numbers)
if my_ticket in picked_sequences:
print(increment)
break
else:
winning_numbers = []
print(increment)
increment += 1
print(winning_numbers)
print(my_ticket)
print(f"It took {increment} picks to pick my lottery numbers")
Think about the types of data that you're generating. What is choice(lottery_numbs) returning? What does winning_numbers contain? What are you comparing it against? If you have similar digits in different containers, you're not going to get a "match" unless you explicitly handle the containers.
The following is my take on your code.
Firstly, I changed your my_ticket into winning_ticket and made it into a list.
Then I changed your filtering of duplicate numbers inside current_ticket into a while loop, to ensure that the ticket will always contain 4 unique characters.
Then I converted your while true loop into a while condition on if the current ticket is the same as winning ticket.
Your main issue is the my_ticket being a tuple, the other minor issues are redundant for loop to filter duplicate, no guarantee on current ticket having 4 characters, variable namings, etc.
from random import choice
winning_ticket = [9, 'z', 4, 0]
lottery_numbs = ['a', 'z', 'i', 't', 'u', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
picks = 0
current_ticket = []
while current_ticket != winning_ticket:
current_ticket = []
while len(current_ticket) < 4:
pick = choice(lottery_numbs)
if pick not in current_ticket:
current_ticket.append(pick)
picks += 1
print(f"It took {picks} picks to pick my lottery numbers")
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')
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().