Dependent probability in Python - python

I'm trying to make something in Python, just for myself, which will determine the likelihood of, in my case, drawing a certain card in a deck. The deck's size is determine by a raw_input, as is the number of cards of which you are trying to calculate probability of drawing. Right now, I have:
from __future__ import division
t = True
while True:
if t == True:
numCards = int(raw_input("How many cards in your deck? Type here: "))
print "There are " + str(numCards) + " cards in your deck."
whatCards = raw_input("What card are you testing for how likely it is to draw them? Type here: ")
whatCards = whatCards.capitalize()
print whatCards + " is a great card!"
if whatCards.endswith("s"):
numCards2 = int(raw_input("How many " + whatCards + " are in it? "))
whatCards = whatCards + "s"
elif whatCards.endswith("y"):
numCards2 = int(raw_input("How many " + whatCards[:-1] + "ies are in it? "))
else:
numCards2 = int(raw_input("How many " + whatCards + "s are in it?"))
if numCards2 > 1:
print "Ok! There are " + str(numCards2) + " " + whatCards + "s" + "!"
else:
print "Alright. There is " + str(1) + " " + whatCards + "!"
'''probability = (numCards2 / numCards) + (numCards2 / (numCards-1)) + (numCards2 / (numCards-2)) + \
(numCards2 / (numCards-3)) + (numCards2 / (numCards-4)) + (numCards2 / (numCards-5))\
+ (numCards2 / (numCards-6))'''
probability = numCards2 / numCards
print "Results are approximate"
print "Decimal: " + str(probability)
if len(str(probability)) <= 3:
print "Percentage: " + str(probability)[2] + str(0) + "%"
else:
print "Percentage: " + str(probability)[2] + str(probability)[3] + "%"
print "Fraction: " + str(numCards2) + "/" + str(numCards)
t = False
if t == False:
numCards = int(raw_input("How many cards in your deck? Type here: "))
print "There are " + str(numCards) + " cards in your deck."
whatCards = raw_input("What card are you testing for how likely it is to draw them? Type here: ")
whatCards = whatCards.capitalize()
print whatCards + " is a great card!"
if whatCards.endswith("s"):
numCards2 = int(raw_input("How many " + whatCards + " are in it? "))
whatCards = whatCards + "s"
elif whatCards.endswith("y"):
numCards2 = int(raw_input("How many " + whatCards[:-1] + "ies are in it? "))
else:
numCards2 = int(raw_input("How many " + whatCards + "s are in it?"))
if numCards2 > 1:
print "Ok! There are " + str(numCards2) + " " + whatCards + "s" + "!"
else:
print "Alright. There is " + str(1) + " " + whatCards + "!"
'''probability = (numCards2 / numCards) + (numCards2 / (numCards-1)) + (numCards2 / (numCards-2)) + \
(numCards2 / (numCards-3)) + (numCards2 / (numCards-4)) + (numCards2 / (numCards-5))\
+ (numCards2 / (numCards-6))'''
probability = numCards2 / numCards
print "Results are approximate"
print "Decimal: " + str(probability)
if len(str(probability)) <= 3:
print "Percentage: " + str(probability)[2] + str(0) + "%"
else:
print "Percentage: " + str(probability)[2] + str(probability)[3] + "%"
print "Fraction: " + str(numCards2) + "/" + str(numCards)
t = True
As you can see, what it's currently solving is likelihood of only one draw. However, my goal is to make it so that the user can input their own number of card draws, so, say, they have a 60 card deck, with 15 Swamp cards in it, and 7 draws. The problem is that if I wanted to draw a hand's worth of cards (7), I couldn't just make it calculate the probability of drawing out of 60, then 59, then 58, down to 53. That's because if they were to draw the Swamp, the probability goes down, which going down from 60 to 53 wouldn't do. What would I have to make so that it randomly selected x cards out of y (deck size), with z amount of draws as well as decremented the number of x when it was "drawn", and changed y for each "draw". And it would have to work any number of times, depending on what the user wanted. Thanks! (hope this makes sense...)

Let's say you have n cards and you are drawing m of them. The possible combinations are n!/(n-m)! If you are looking for the probability to draw y cards ( y<=m ) of a kind which makes up x of the total n cards. You have to consider 2 quantities:
1. The possible ways to pick y cards out of x cards which is x!/(x-y)! And then the possible ways to lay this ordered sets into m slots, or else where to put the other m-y cards into the set of m cards which is m!/(m-y)!
The product of these 2 quantities gives you the favorable events, while the first number gives you the total event. So your probability is
P = x!m!(n-m)!/(n!(x-y)!(m-y)!)
I hope I did not miss anything :)

Related

I'm getting the wrong output in my if statment

I'm new to python and am trying to fix this and By defualt its running the else statment I don't understand and need help. I'm new so please dumb your answers down to my -5 iq
menu = "Baguette , Crossiant , Coffee , Tea , Cappuccino "
print(menu)
if "" > menu:
order = input("What Would you like? \n ")
amount = input("How many " + order + " would you like?")
print( name + " Your " + amount + " " + order + " will be ready soon!\n\n\n")
price = int(4)
#converts number into intenger to do math correctly (int)
total = price * int(amount)
#turns total into string intead of intenger to prevent error in terminal
print("Thank you, your total is: $" + str(total))
print("Your " + amount + " of " + order + " is ready!")
print("Please enjoy you " + order + "!")
print("Please come again!")
else:
#If not on menu stops running
print("Sorry Thats not on the menu")
quit()
I changed the if "" to on_menu and list the options but it didn't work, and I asked people on discord.
menu = ["Baguette" , "Crossiant" , "Coffee" , "Tea" , "Cappuccino "]
count = 0
for item in menu:
print(str(count) +" -> "+str(item))
count += 1
order = int(input("\n What Would you like? \n "))
if order > len(menu) or order < 0 or order == "" or not menu[order]:
print("Sorry Thats not on the menu")
quit()
orderCount = int(input("How many " + menu[order] + " would you like?"))
print("Your " + str(orderCount) + " " + menu[order] + " will be ready soon!\n\n\n")
amount = int(4) * int(orderCount)
print("Thank you, your total is: $" + str(amount))
print("Your " + str(amount) + " of " + str(menu[order]) + " is ready!")
print("Please enjoy you " + str(menu[order]) + "!")
print("Please come again!")
Currently you are not checking the user input, you are just checking for a False statement based on what you defined. You need to check if the user input is on the menu, else quit the program.
menu = "Baguette , Crossiant , Coffee , Tea , Cappuccino "
print(menu)
name = input("What your name? \n ")
order = input("What Would you like? \n ")
if not order.lower() in menu.lower(): # checking if user input is in the menu
#If not on menu stops running
print("Sorry Thats not on the menu")
quit()
amount = input("How many " + order + " would you like?")
print( name + " Your " + amount + " " + order + " will be ready soon!\n\n\n")
price = int(4)
#converts number into intenger to do math correctly (int)
total = price * int(amount)
#turns total into string intead of intenger to prevent error in terminal
print("Thank you, your total is: $" + str(total))
print("Your " + amount + " of " + order + " is ready!")
print("Please enjoy you " + order + "!")
print("Please come again!")
#input name
name = input("What is your name?\n")
#create menu
menu = "Baguette, Crossiant, Coffee, Tea and Cappuccino"
#display menu
print(menu)
#input order
order = input("What would you like?\n")
#if the order item is in the menu
if order in menu:
#input quantity
amount = input("How many " + order + "s would you like? ")
#display message
print( name + " Your " + amount + " " + order + " will be ready soon!\n\n\n")
#setting price of all items to 4
price = 4
#calculating total
total = price * int(amount)
#turns total into string intead of intenger to prevent error in terminal
print("Thank you, your total is: $" + str(total))
print("Your " + amount + " of " + order + " is ready!")
print("Please enjoy you " + order + "!")
print("Please come again!")
#if the item is not in menu
else:
#display message
print("Sorry Thats not on the menu")
Hope this helps! I have added the explanation as comments.

I don't know how to make a while loop last until a list doesn't have any values left

I am trying to recreate the card game "War" in python and cant figure out how to loop the code under the comment until every value in the list is gone. So basically the code generates a shuffled deck of cards and pops the cards from the list. I want to have the code repeat until all the cards have been popped from the deck and I have no idea how to do that.
import random
def shuffled_deck():
deck = list(range(2, 15)) *4
random.shuffle(deck)
return deck
userdeck = shuffled_deck()
print("welcome to War!")
user1 = input("Player-1 name: ")
user2 = input("Player-2 name: ")
u1points = 0
u2points = 0
drawturns = 0
# - I want to loop the segment of code under this comment
usercard = userdeck.pop()
u1card = usercard
print(user1 + ": " + str(u1card))
usercard = userdeck.pop()
u2card = usercard
print(user2 + ": " + str(u2card))
if u1card > u2card:
print(str(u1card) + " is greater than " + str(u2card) + ".")
print(user1 + " won this round.")
u1points +=1
elif u2card > u1card:
print(str(u2card) + " is greater than " + str(u1card) + ".")
print(user2 + " won this round.")
u2points +=1
else:
print("It's a draw, try again.")
while u1card == u2card:
drawturns +=1
usercard = userdeck.pop()
u1card = usercard
print(user1 + ": " + str(u1card))
usercard = userdeck.pop()
u2card = usercard
print(user2 + ": " + str(u2card))
if u1card > u2card:
print(str(u1card) + " is greater than " + str(u2card) + ".")
print(user1 + " won this round.")
u1points +=1
u1points + drawturns
elif u2card > u1card:
print(str(u2card) + " is greater than " + str(u1card) + ".")
print(user2 + " won this round.")
u2points +=1
u1points + drawturns
else:
print("It's a draw, try again.")
if u1card == u2card == False:
drawturns = 0
break
You can do:
while len(userdeck)>0:
or, you can write smartly as:
while userdeck:
This is because an empty list is considered as False, whereas a non empty list is considered as True. So, when userdeck is empty, while loop will assume it to be False case, so the loop will stop. This same concept can also be applied for if statements.

The game over line isn't working. Why isn't it correctly displaying the games won and lost?

This is my code for a game of 21 or Blackjack. On the final line it won't display the number of games won and number of games lost but I can't figure out how to fix it. Can someone help me correct this? I did this on python 3.6.1
P.S. If there is anything else that can be improved here, feedback would be much appreciated.
import random
from random import choice
import time
import colorama
from colorama import Fore, Back, Style
name = str(input("Welcome to " + Fore.YELLOW + "21" + Style.RESET_ALL + "! I'll be your dealer. \nWhat's your name?"))
instructions=""
while instructions!="N" and instructions!="Y":
instructions=str(input("Would you like to see the Instructions? Y/N"))
if instructions!="N" and instructions!="Y":
print("That is not a valid answer.")
else:
time.sleep(1)
if instructions=="Y":
print(Fore.GREEN + "Instructions:" + Style.RESET_ALL + "\nYour objective is to get as close as you can to " + Fore.YELLOW + "21" + Style.RESET_ALL + ".\n>Each round, you will be dealt two standard cards. You must add these and the person with the closest total wins. \n>You will choose whether to 'hit' or 'miss' every round. If you hit, you get dealt another card. However, be careful as going over " + Fore.YELLOW + "21 " + Style.RESET_ALL + "causes you to bust and lose! \n>Picture cards are worth 10 points each.\n>Aces are 1 or 11, randomly.")
time.sleep(1)
else:
print("")
rounds=int(input("How many rounds do you want to play " + name + "?"))
gamesLost=0
gamesWon=0
def twentyone():
roun=0
for i in range(0,rounds):
gamesLost=0
gamesWon=0
roun+=1
print("Round " + str(roun))
cards=['Ace','Ace','Ace','Ace','2','2','2','2','3','3','3','3','4','4','4','4','5','5','5','5','6','6','6','6','7','7','7','7','8','8','8','8','9','9','9','9','10','10','10','10','Jack','Jack','Jack','Jack','Queen','Queen','Queen','Queen','King','King','King','King']
cardVal = {'Ace':random.randint(1,11),'King':10,'Queen':10,'Jack':10,'10':10,'9':9,'8':8,'7':7,'6':6,'5':5,'4':4,'3':3,'2':2}
card1=random.choice(cards)
cards.remove(card1)
card2=random.choice(cards)
cards.remove(card2)
hands=(str(card1) + ", " + str(card2))
playerHand = cardVal[card1]+cardVal[card2]
print("Your hand is " + hands + ". Your hand is worth " + str(playerHand) + ".")
hit=""
while hit!="H" and hit!="S" and hit!="h" and hit!="s":
hit=str(input("Do you want to hit (H) or stay (S)?"))
if hit!="H" and hit!="S" and hit!="h" and hit!="s":
print("That is not a valid answer.")
else:
time.sleep(0.01)
while hit=="H" or hit=="h":
card=random.choice(cards)
cards.remove(card)
playerHand+=cardVal[card]
hands=(hands + ", " + str(card))
print("Your hand is " + hands + ". Your hand is worth " + str(playerHand) + ".")
if playerHand>21:
break
else:
time.sleep(0.01)
hit=str(input("Do you want to hit (H) or stay (S)?"))
if playerHand>21:
print("Sorry, you bust!")
gamesLost+=1
i+=1
else:
time.sleep(0.01)
cpuCard1=random.choice(cards)
cards.remove(cpuCard1)
cpuCard2=random.choice(cards)
cards.remove(cpuCard2)
handsCPU=(str(cpuCard1) + ", " + str(cpuCard2))
computerHand=cardVal[cpuCard1]+cardVal[cpuCard2]
while computerHand<17:
if computerHand<17:
cpuCard=random.choice(cards)
cards.remove(cpuCard)
computerHand+=cardVal[cpuCard]
handsCPU=(handsCPU + ", " + str(cpuCard))
else:
time.sleep(0.01)
if computerHand>21:
print("I'm bust! You win.")
gamesWon+=1
i+=1
elif computerHand>playerHand:
print("My hand is " + str(handsCPU) + ". It is worth " + str(computerHand) + ". You lose.")
gamesLost+=1
i+=1
else:
print("My hand is " + str(handsCPU) + ". It is worth " + str(computerHand) + ". You win.")
gamesLost+=1
i+=1
twentyone()
print("\nGame Over!")
print("You won " + str(gamesWon) + " and lost " + str(gamesLost) + ".")
again=str(input("Do you want to go again? Y/N"))
if again=="Y":
rounds=int(input("How many rounds do you want to play " + name + "?"))
twentyone()
elif again=="N":
print("Have a nice day.")
else:
print("Have a nice day.")
Unfortunately I can't test it myself since I don't have all modules. But I assume your issue is that the line print says you won and lost 0 games every time.
It looks like you're resetting your game-counters with every new game:
for i in range(0,rounds):
gamesLost=0
gamesWon=0
You play one game, record games won and lost and then reset both to 0 for the next game when the loop starts over. Since you're also initialising both counters just before the loop - but also outside the def - it should work if you remove both lines. Or you can move the lines before the loop and maybe remove the other copy if it is redundant. Defining the counters inside your function is the better approach, though.

Identify python errors

Can someone assist with identifying the errors in this loop?
I am completely new to Python.
for p in players:
x = len(p)
dice = random.randint(0, x*2)
print p + " rolls a " + dice + " out of " + str(x*2)
if dice > x:
print p + " wins!"
elif dice == x:
print p + "gets a tie."
else:
print p + " loses."}
Thanks!!
Works in Python 3.x
import random
players = ["Player 1", "Player 2"]
for p in players:
x = len(p)
dice = random.randint(0, x*2)
print(str(p) + " rolls a " + str(dice) + " out of " + str(x*2))
if dice > x:
print(p + " wins!")
elif dice == x:
print(p + "gets a tie.")
else:
print(p + " loses.")
For Python 2.x
import random
players = ["Player 1", "Player 2"]
for p in players:
x = len(p)
dice = random.randint(0, x*2)
print(str(p) + " rolls a " + str(dice) + " out of " + str(x*2))
if dice > x:
print p + " wins!"
elif dice == x:
print p + "gets a tie."
else:
print p + " loses."
or add from __future__ import print_function to first example to ensure compability between Python 3 and 2.

Python 3.3 programs not working?

I've made a few programs in Python now, but I'm still pretty new. I've updated to 3.3, and most of my programs are broken. I've replaced all of the raw_inputs now with input, but this still isn't working, and I get no errors.
Could one of you fine programmers help?
a = 1
while a < 10:
StartQ = input("Would you like to Start the program, or Exit it?\n")
if StartQ == "Exit":
break
elif StartQ == "Start":
AMSoD = input("Would you like to Add, Multiply, Subtract or Divide?\nPlease enter A, M, S or D.\n")
if AMSoD == "A":
Add1 = input("Add this: ")
Add2 = input("By this: ")
AddAnswer = int(Add1) + int(Add2)
AAnswer = Add1 + " " + "+" + " " + Add2 + " " + "=",AddAnswer
print(AAnswer)
print("The answer is:"),AddAnswer
elif AMSoD == "M":
Mul1 = input("Multiply this: ")
Mul2 = input("By this: ")
MulAnswer = int(Mul1) * int(Mul2)
MAnswer = Mul1 + " " + "*" + " " + Mul2 + " " + "=",MulAnswer
print(MAnswer)
print("The answer is:"), (MulAnswer)
elif AMSoD == "S":
Sub1 = input("Subtract this: ")
Sub2 = input("From this: ")
SubAnswer = int(Sub2) - int(Sub1)
SAnswer = Sub2 + " " + "-" + " " + Sub1 + " " + "=",SubAnswer
print(SAnswer)
print("The answer is:"), (SubAnswer)
elif AMSoD == "D":
Div1 = input("Divide this: ")
Div2 = input("By this: ")
DivAnswer = int(Div1) / int(Div2)
DAnswer = Div1 + " " + "/" + " " + Div2 + " " + "=",DivAnswer
print(DAnswer)
print("The answer is:"), (DivAnswer)
DivQoR = input("Would you like to Quit or restart?\nAnswer Quit or Restart.\n")
if DivQoR == "Restart":
a = 1
elif DivQoR == "Quit":
DivQoRAyS = input("Are you sure you want to quit? Answer Yes or No.\n")
if DivQoRAyS == "Yes":
break
elif DivQoRAyS == "No":
a = 1
Put all items you want to print in the parenthesis of the print() function call:
print("The answer is:", AddAnswer)
and
print("The answer is:", MulAnswer)
etc.
Where you build your strings, it'd be easier to do so in the print() function. Instead of
AAnswer = Add1 + " " + "+" + " " + Add2 + " " + "=",AddAnswer
print(AAnswer)
(where you forgot to replace the last comma with +), do this:
print(Add1, '+', Add2, '=', AddAnswer)
and so on for the other options.

Categories

Resources