How can I simplify this code - python

I'm a beginner, and I wanted to know if there was a simpler way of write this out in Python. I'm assuming some type of dictionary, but I do not understand how to write it out.
I was on a cruise a couple of days ago, and I play craps. I wanted to know if the odds are somewhat correct. So, I wrote this, but I know there is a simpler way.
import random
dice2 = 0
dice3 = 0
dice4 = 0
dice5 = 0
dice6 = 0
dice7 = 0
dice8 = 0
dice9 = 0
dice10 = 0
dice11 = 0
dice12 = 0
for i in range(100000):
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
number = dice1 + dice2
#print(dice1)
if number == 2:
dice2 +=1
elif number == 3:
dice3 += 1
elif number == 4:
dice4 += 1
elif number == 5:
dice5 += 1
elif number == 6:
dice6 += 1
elif number == 7:
dice7 += 1
elif number == 8:
dice8 += 1
elif number == 9:
dice9 += 1
elif number == 10:
dice10 += 1
elif number == 11:
dice11 += 1
elif number == 12:
dice12 += 1
total = dice2+dice3+dice4+dice5+dice6+dice7+dice8+dice9+dice10+dice11+dice12
At the end of this, it just prints out the percentage of hits on numbers from 2-12.

I'd use Counter, as that's what it was made for:
from random import randint
from collections import Counter
counts = Counter(randint(1, 6) + randint(1, 6) for i in range(100000))
total = sum(counts.values())
number_of_tens = counts[10]

from random import randint
dice = [0]*11
for i in range(100000):
dice[randint(1,6)+randint(1,6)-2] += 1
total = sum(dice) #it is 100000, of course
for i, v in enumerate(dice, 2):
print('{0}: {1}%'.format(i, v*100.0/total))

import random
def roll(n=6):
return random.randint(1, n)
dice = dict.fromkeys(range(2, 13), 0)
for i in range(100000):
number = roll() + roll()
dice[number] += 1
total = float(sum(dice.values()))
for k,v in dice.items():
print "{}, {:.2%}".format(k, v/total)

Related

Producing probability of wins in Python craps game

I have the logic down for this game of craps. My only problem right now is that I can't seem to get any output for finding the probability of wins for the game. Here is the code:
from random import seed, randint
def simulate():
die1 = randint(1, 6)
die2 = randint(1, 6)
roll = die1 + die2
first_roll = roll
if first_roll == 7 or first_roll == 11:
return True
elif first_roll == 2 or first_roll == 3 or first_roll == 12:
return False
else:
second_roll = randint(1, 6) + randint(1, 6)
while second_roll != first_roll and second_roll != 7:
if second_roll == first_roll:
return True
elif second_roll == 7:
return False
## Main
def probability(n):
simulate()
wins = 0
for i in range(n):
if simulate() == 1:
wins += 1
return
print(probability(10000))
I want to find the probability of wins for 10000 trials. However, I don't get any output when running this code. Nothing shows up. Where am I going wrong on this? I have tried for a couple hours but nothing seems to be working for me. Please include code and what I was doing wrong. I know for a fact that it should be 49% but I can't seem to arrive at that answer.
I am sorry for my latest answer, I didn't read that its craps game.
from random import seed, randint
def simulate():
die1 = randint(1, 6)
die2 = randint(1, 6)
roll = die1 + die2
first_roll = roll
if first_roll == 7 or first_roll == 11:
return True
elif first_roll == 2 or first_roll == 3 or first_roll == 12:
return False
else:
while True:
second_roll = randint(1, 6) + randint(1, 6)
if second_roll == first_roll:
return True
elif second_roll == 7:
return False
# Main
def probability(n):
wins = 0
for i in range(n):
if simulate() == 1:
wins += 1
return wins
print(probability(100000))
I think its the answer, I changed the second part of simulate()
where its returning True, when second_roll == first_roll, returning False when second_roll==7, and repeats that while loop by continue, if second_roll is equal to other number.

I want to tell the user that they are very lucky if they get heard or tail 6 times in a row

I am trying to create a Coin Flip Game this is what I have came up with so far:
import random
def headsOrTails(number_of_flips):
number_of_flips = int(input("How many times do you want to flip the coin: "))
heards_count = 0
tails_count = 0
for i in range(number_of_flips):
rand = random.randint(1, 2)
if rand == 1:
heards_count += 1
print(f"It is Heads.\n Heads {heards_count}")
elif rand == 2:
tails_count += 1
print(f"It is Tails.\n Tails {tails_count}")
print(heards_count)
print(tails_count)
headsOrTails(1)
I want to tell the user that they are very lucky if they get heard or tail 6 times in a role. And I was wondering if anyone can help me do that.
An if statement like this should work:
if heards_count == 6:
print('You are very lucky!')
heards_count can only equal 6 if you pass in six to the function headsOrTails(). Get rid of the line
if rand == 1 and rand == 1 and rand == 1 and rand == 1:
rand will be reset on each iteration of the loop so it does not check if rand has been equal to 1 four times. Hope this helps!
Here is what I would do. I would use the heads_count and the tails_count as a heads/tails in a row count. If you get a heads, reset the tails count. If you get a tails, reset the heads count.
import random
def headsOrTails():
number_of_flips = int(input("How many times do you want to flip the coin: "))
heads_count = 0
tails_count = 0
for i in range(number_of_flips):
rand = random.randint(1, 2)
if rand == 1:
tails_count = 0
heads_count += 1
print(f"It is Heads.\n Heads in a row {heads_count}")
elif rand == 2:
heads_count = 0
tails_count += 1
print(f"It is Tails.\n Tails in a row {tails_count}")
if heads_count == 6 or tails_count == 6:
print("You are very lucky")
headsOrTails()
import random
def headsOrTails(n):
heads_count = 0
tails_count = 0
heads_inarow = 0
tails_inarow = 0
for i in range(n):
rand = random.randint(1, 2)
if rand == 1:
tails_inarow = 0
heads_inarow += 1
heads_count += 1
print(f"It is Heads.\n Heads in a row {heads_inarow}")
elif rand == 2:
heads_inarow = 0
tails_inarow += 1
tails_count += 1
print(f"It is Tails.\n Tails in a row {tails_inarow}")
if heads_inarow == 6 or tails_inarow == 6:
print("You are very lucky")
print(heards_count)
print(tails_count)
number_of_flips = int(input("How many times do you want to flip the coin: "))
headsOrTails(number_of_flips)

Python craps game: Wrong output

I'm a beginner and I can't figure out why I can't get the output I
want. It's a craps game. It's suppose to go like:
How many games do you want to play > 6 You rolled 5 + 2 = 7 You
win
What I got is something like: You rolled 1 + 6 = 7 You rolled 1 + 6 =
7 You rolled 1 + 6 = 7 You lose
import random
def rollDice():
roll_1 = random.randint(1,7)
roll_2 = random.randint(1,7)
return roll_1, roll_2
def determine_win_or_lose(dice1,dice2):
sum = dice1 + dice2
print("You rolled", dice1, "+", dice2, "=", sum )
if sum == '2' or '3' or '12':
return 0
elif sum == '7' or '11':
return 1
else:
print("Point is", sum)
determinePointValueResult(sum)
if determinePointValueResult(sum) == 1:
return 1
elif determinePointValueResult(sum) == 0:
return 0
def determinePointValueResult(sum):
point = sum
while sum != 7 and sum != point:
x, y = rollDice()
sum = x + y
if sum == point:
return 1
elif sum == '7':
return 0
print("You rolled", x, "+", y, "=", sum )
#==== MAIN =====
win = 0
lose = 0
game = int(input("How many games do you want to play > "))
for i in range(game):
x, y = rollDice()
determine_win_or_lose(x, y)
if determine_win_or_lose(x, y) == 1:
print("You win")
win = win + 1
elif determine_win_or_lose(x, y) == 0:
print("You lose")
lose = lose + 1
print("Game results: ", win, "wins and", lose, "losses")
Your issue come from the main, because you call the determine_win_or_lose function 3 times, the first one before the if (and i'm not sure why since you do nothing with it), a second time to check the condition of the if and a third time to check the condition of the elif.
Since it's this function that print the message, and you call the function 33 times each iteration of the for loop, it's normal to get the message printed 3 times.
(
Also since the determine_win_or_lose will always return 0 or 1 you don't really need an elif you can just do an if/else to achieve the same thing and simplify your code a bit.
)
So i'd suggest the following :
#==== MAIN =====
win = 0
lose = 0
game = int(input("How many games do you want to play > "))
for i in range(game):
x, y = rollDice()
result = determine_win_or_lose(x, y)
if result == 1:
print("You win")
win = win + 1
else:
print("You lose")
lose = lose + 1
print("Game results: ", win, "wins and", lose, "losses")
Obvious issues:
You call determine_win_or_lose too many times in your for loop. Change it to:
for i in range(game):
x, y = rollDice()
result = determine_win_or_lose(x, y)
if result == 1:
print("You win")
win = win + 1
elif result == 0:
print("You lose")
lose = lose + 1
Your check in determine_win_or_lose is incorrect. It should be something like:
def determine_win_or_lose(dice1,dice2):
sum = dice1 + dice2
print("You rolled", dice1, "+", dice2, "=", sum )
if sum == 2 or sum == 3 or sum == 12:
return 0
elif sum == 7 or sum == 11:
return 1
else:
print("Point is", sum)
determinePointValueResult(sum)
if determinePointValueResult(sum) == 1:
return 1
elif determinePointValueResult(sum) == 0:
return 0
In determinePointValueResult you shouldn't compare sum to a string, but an integer:
def determinePointValueResult(sum):
point = sum
while sum != 7 and sum != point:
x, y = rollDice()
sum = x + y
if sum == point:
return 1
elif sum == 7:
return 0
print("You rolled", x, "+", y, "=", sum )
It's possible that determine_win_or_lose and determinePointValueResult are returning None. You may need to change your elifs to elses or create a new else case.

Python Won't Run

My python program prints the first thing I wrote, and then loads forever and never prints the second task. What do I need to change with my code?
import random
def main():
money = 100
win = 0
loss = 0
draw = 0
bet = random.randint(5, 20)
print('You are starting with $100 and each round you will bet', bet, 'dollors')
while True:
x = random.randint(1, 6)
y = random.randint(1, 6)
z = x + y
if money == 0 or money == 200:
break
if z == 7 or z == 11:
money += bet
win += 1
elif z == 2 or z == 3 or z == 12:
loss += 1
money -= bet
else:
draw += 1
print('You ended up with', money, 'dollars, and you won', win, 'rounds, lost', \
loss, 'rounds, and drew', draw, 'rounds')
main()
Looks like it will never be able to satisfy all the conditions and is caught in a infinite loop
I think you have to use correct condition in the if condition and i suggest u to use a var to run the loop and to break the loop.
import random
def main():
money = 100
win = 0
loss = 0
draw = 0
bet = random.randint(5, 20)
print('You are starting with $100 and each round you will bet', bet, 'dollors')
loop = True
while loop:
x = random.randint(1, 6)
y = random.randint(1, 6)
z = x + y
if money <= 0 or money >= 200:
loop = False
if z == 7 or z == 11:
money += bet
win += 1
elif z == 2 or z == 3 or z == 12:
loss += 1
money -= bet
else:
draw += 1
print('You ended up with', money, 'dollars, and you won', win, 'rounds, lost', \
loss, 'rounds, and drew', draw, 'rounds')

Random Die Generator

Can someone tell me why my program doesn't work? Even when I set s as 10000.
When I printed out wins and plays it just shows up as 0 and 1.
def manyCraps(s):
wins = 0
plays = 0
dice1 = randint(1,6)
dice2 = randint(1,6)
total = dice1 + dice2
for i in range(s):
if total == 7 or total == 11:
wins = wins + 1
plays = plays + 1
else:
if total == 2 or total == 3 or total == 12:
plays = plays + 1
else:
plays = plays + 1
dice3 = randint(1,6)
dice4 = randint(1,6)
total = dice3 + dice4

Categories

Resources