Python probability of a pair - python

I am trying to make a poker game where it would check if it is a pair or three of a kind or four of a kind.
I am trying to figure out where to insert a while loop. if I should put it in front of the for card in set(cards): statement or the for i in range(5):
I want to keep printing 5 cards until it shows either a pair, 3 of a kind, or 4 of a kind.
Then what I want to do is to print the probability of printing one of those options
import random
def poker():
cards = []
count = 0
for i in range(5):
cards.append(random.choice([1,2,3,4,5,6,7,8,9,10,11,12,13]))
print(cards)
for card in set(cards):
number = cards.count(card) # Returns how many of this card is in your hand
print(f"{number} x {card}")
if(number == 2):
print("One Pair")
break
if(number == 3):
print("Three of a kind")
break
if(number == 4):
print("Four of a kind")
break

You should put the while above cards but bring count outside of that loop so you can maintain it. You do this because you need to repeat the entire card creation/selection process each time until you meet the condition you are looking for.
import random
def poker():
count = 0
while True:
cards = []
for i in range(5):
cards.append(random.choice([1,2,3,4,5,6,7,8,9,10,11,12,13]))
print(cards)
stop = False
for card in cards:
number = cards.count(card) # Returns how many of this card is in your hand
print(f"{number} x {card}")
if(number == 4):
print("Four of a kind")
stop = True
break
elif(number == 3):
print("Three of a kind")
stop = True
break
elif(number == 2):
print("One Pair")
stop = True
break
if stop:
break
else:
count += 1
print(f'Count is {count}')

Related

how to stop it without using "brake;"? its a guessing play

import math
import random
a = math.floor((random.random())*100)
if a%10 != 00:
c = math.floor(a/10)
a = a - c*10
#to make sure the number isnt over 10
attempts = int(input("enter num of attempts"))
att = attempts
for i in range(0,attempts+1,1):
tr = int(input("try"))
att = att -1
if tr == a:
print("good")
break;
else:
print("no,try again", "you got",att,"more attempts")
if att == 0:
print("game over,the num was", (a))
the game has random num between 0-10 and you need to insert num of attempst, and then guess what number is it, and you got the amount of attempst you have insert to try guessing the num.
You can replace the for loop by a while loop.
This way you have more control, you can use a found boolean and loop while it is False.
Note also that you have to increment i by yourself.
I printed the messages (win/lost) outside of the loop.
It makes the loop code more readable.
I also used randint() to choose the random number to guess.
It does all the work without further computation and is also part of the random module.
from random import randint
a = randint(1, 10)
attempts = int(input("enter num of attempts"))
att = attempts
found = False
i = 0
while i < attempts and not found:
i += 1
att -= 1
tr = int(input("try"))
if tr == a:
found = True
elif att > 0:
print("no,try again", "you got", att, "more attempts")
if found:
print("good")
else:
print("game over,the num was", (a))

Games such a flip a coin, rolling dice, and choosing cards

im trying to make a game board and i have taken some notes from my class and im just struggling to do this assignment. We never have done anything like this in class before. I need to do a coin flip, roll two dice a 6 sided one and a 20 sided one and i need to pick a card.
import random
def flip_coin():
# TODO: implement this function
# get a random int between 0 and 1
# if the number is 0, return "Coin flip: Tails"
# if the number is 1, return "Coin flip: Heads"
# delete this next line:
return 0
def roll_d6():
# TODO: implement this function
# get a random int between 1 and 6
# return "D6 roll: [that number]"
# delete this next line:
return 0
def roll_d20():
# TODO: implement this function
# get a random int between 1 and 20
# return "D20 roll: [that number]"
# delete this next line:
return 0
def pick_card():
# TODO: implement this function
# get a random number between 0 and 3
# [card suit]: 0=spades, 1=hearts, 2=diamonds, 3=clubs
# then get a random number between 1 and 13
# [card value]: 1=Ace, 11=Jack, 12=Queen, 13=King, 2-10 are normal (no translation)
# return "Your card: [card value] of [card suit]"
# delete this next line:
return 0
# TODO: put the following lines into a loop, to allow the user to repeat until they quit
print('Welcome to the game center!\nHere are your options:')
print('\t1) Flip a coin\n\t2) Pick a random playing card')
print('\t3) Roll a 6-sided dice\n\t4) Roll a 20-sided dice')
choice = input('What would you like to do? ')
# TODO: based on what the user selects, call the appropriate function above (print the result)
There are faster solutions to this: but these are the most simple solutions.
import random
def coin_flip():
generated_num = random.randint(0, 1) # generate a random number from 0 to 1
if generated_num == 0:
return "Coin flip: Tails"
else:
return "Coin flip: Heads"
def roll_d6():
generated_num = random.randint(1, 6)
return f"D6 roll: {generated_num}"
def roll_d20():
generated_num = random.randint(1, 20)
return f"D20 roll: {generated_num}"
def pick_card():
suit = random.randint(0, 3)
if suit == 0: suit = "Spades"
if suit == 1: suit = "Hearts"
if suit == 2: suit = "Diamonds"
if suit == 3: suit = "Clubs"
value = random.randint(1, 13)
if value == 1: value = "Ace"
if value == 11: value = "Jack"
if value == 12: value = "Queen"
if value == 13: value = "King"
return f"Your card: {value} of {suit}"
NOTE
Here is a better way to pick the suit:
def pick_card():
suit = random.choice(['Spades','Hearts','Diamonds','Clubs'])
...

Luhn's algorithm works for all credit cards except for AMEX cards (Python3) (cs50/pset6/credit)

I'm trying to create a program that checks whether the credit card number the user inputed is either invalid, or from AMEX, MASTERCARD, or VISA. I'm using Luhn's formula. Here is a site that contains the explanation to the formula I'm using: https://www.geeksforgeeks.org/luhn-algorithm/
It works with all credit card numbers, except credit cards from AMEX. Could someone help me?
Here is my code:
number = input("Number: ")
valid = False
sumOfOdd = 0
sumOfEven = 0
def validation(credit_num):
global sumOfOdd
global sumOfEven
position = 0
for i in credit_num:
if position % 2 != 0:
sumOfOdd += int(i)
else:
product_greater = str(int(i) * 2)
if len(product_greater) > 1:
sumOfEven += (int(product_greater[0]) + int(product_greater[1]))
else:
sumOfEven += int(product_greater)
position += 1
def main():
if (sumOfOdd + sumOfEven) % 10 == 0:
if number[0] == "3":
print("AMEX")
elif number[0] == "5":
print("MASTERCARD")
else:
print("VISA")
else:
print("INVALID")
print(f"{sumOfOdd + sumOfEven}")
validation(number)
main()
Here are some credit card numbers:
VISA: 4111111111111111
MASTERCARD: 5555555555554444
AMEX: 371449635398431
I've found many different ways to calculate this formula, but I'm not sure if mine is correct.

I'm stuck in the creating of a Board game in python

I have an excercise to do and I'm stuck. It's the board game Alak, not much known, that I have to code in python. I can link the execrcise with the rules so you can help me better. The code has the main part and the library with all the procedures and function.
from Library_alak import *
n = 0
while n < 1:
n = int(input('Saisir nombre de case strictement positif : '))
loop = True
player = 1
player2 = 2
removed = [-1]
board = newboard(n)
display(board, n)
while loop:
i = select(board, n, player, removed)
print(i)
board = put(board, player, i)
display(board, n)
capture(board, n, player, player2)
loop = True if again(board, n, player, removed) is True else False
if player == 1 and loop:
player, player2 = 2, 1
elif player == 2 and loop:
player, player2 = 1, 2
win(board, n)
print(win(board, n))
And here is the library:
def newboard(n):
board = ([0] * n)
return board
def display(board, n):
for i in range(n):
if board[i] == 1:
print('X', end=' ')
elif board[i] == 2:
print('O', end=' ')
else:
print(' . ', end=' ')
def capture(board, n, player, player2):
for place in range(n):
if place == player:
place_beginning = place
while board[place] != player:
place_end = place
if board[place + x] == player:
return board
else:
return board
def again(board, n, player, removed):
for p in board(0):
if p == 0:
if p not in removed:
return True
else:
return False
def possible(n, removed, player, i, board):
for p in range(n + 1):
if p == 1:
if board[p-1] == 0:
if p not in removed:
return True
else:
return False
def win(board, n):
piecesp1 = 0
piecesp2 = 0
for i in board(0):
if i == 1:
piecesp1 += 1
else:
piecesp2 += 1
if piecesp1 > piecesp2:
print('Victory : Player 1')
elif piecesp2 > piecesp1:
print('Victory : Player 2')
else:
return 'Equality'
def select(board, n, player, removed):
loop = True
while loop:
print('player', player)
i = int(input('Enter number of boxes : '))
loop = False if possible(n, removed, player, i, board)is True else True
return i
def put(board, player, i):
i -= 1
if board[i] == 0:
if player == 1:
board[i] = 1
return board
else:
board[i] = 2
return board
else:
put(board, player, i)
So my problems here are that I have few errors, the first one is that when I enter the number '1' when asked to enter a number of boxes ( which is the place to play on ) nothing happens. Then when entering any other number, either the error is : if board[place + x] == player:
NameError: name 'x' is not defined
or there seems to be a problem with the : if board[place + x] == player:
NameError: name 'x' is not defined
I would appreciate a lot if anyone could help me. I'm conscious that it might not be as detailed as it should be and that you maybe don't get it all but you can contact me for more.
Rules of the Alak game:
Black and white take turns placing stones on the line. Unlike Go, this placement is compulsory if a move is available; if no move is possible, the game is over.
No stone may be placed in a location occupied by another stone, or in a location where a stone of your own colour has just been removed. The latter condition keeps the game from entering a neverending loop of stone placement and capture, known in Go as ko.
If placing a stone causes one or two groups of enemy stones to no longer have any adjacent empty spaces--liberties, as in Go--then those stones are removed. As the above rule states, the opponent may not play in those locations on their following turn.
If placing a stone causes one or two groups of your own colour to no longer have any liberties, the stones are not suicided, but instead are safe and not removed from play.
You shouldn't use "player2" as a variable, there's an easier way, just use "player" which take the value 1 or 2 according to the player. You know, something like that : player = 1 if x%2==0 else 2
and x is just a increasing int from 0 until the end of the game.

Appending a list which refers to a list inside a function

I have the task of producing a Blackjack game in Python which allows up to 4 human players to play plus the automated House.
I have to use a function 'get_deck' (see code below).
I am struggling to figure out how to get a card from 'get_deck' and append it to the player's list.
I managed to make the program when using my own defined list for the cards but for this assignment I have to use the 'get_deck' function. The '?????' in the below code are where I referenced my first card values list.
Here is my code:
def get_deck():
deck = [value + suit for value in '23456789TJQKA' for suit in 'SHDC']
random.shuffle(deck)
return iter(deck)
while True:
get_deck()
player1 = []
player2 = []
player3 = []
player4 = []
house = []
player1.append(random.choice(?????))
player2.append(random.choice(?????))
player3.append(random.choice(?????))
player4.append(random.choice(?????))
house.append(random.choice(?????))
player1_bust = False
player2_bust = False
player3_bust = False
player4_bust = False
house_bust = False
if number_players[0] == 1:
player1_total = total(player1)
while True:
player1_total = total(player1)
print "Player 1 has these cards %s with a total value of %d." % (player1, player1_total)
if player1_total > 21:
print "Bust!"
player1_bust = True
break
elif player1_total == 21:
print "Blackjack!"
break
else:
hit_stand = raw_input("Hit or Stand? (h or s): ").lower()
if 'h' in hit_stand:
player1.append(random.choice(?????))
else:
break
I hope this makes sense! Thanks in advance.
Using Python 2.7
The get_deck function is already randomly shuffling the deck for you. You don't need to get random elements from its list, because it's already randomized. Just get the next element from the iterator that get_deck returns.
https://docs.python.org/2/library/stdtypes.html#iterator-types

Categories

Resources