This is my code buy no matter how many times I run it all I get is you lost. What's wrong with the code?
import random
# Creates a number to count the amount of plays
count = 1;
# Creates a variable to store the amount of starting money
money = 10;
# Creates a variable telling you how much money you start with
startingCash = "You start with $" + str(money) + "!";
while (count < 101):
# Variables for the lottery numbers
lottery1 = random.randint(1,9);
lottery2 = random.randint(1,9);
lottery3 = random.randint(1,9);
lottery4 = random.randint(1,9);
# Lottery variables in one single variable
lotteryTotal = (lottery1, lottery2, lottery3, lottery4);
# Variables for the drawn ticket
drawn1 = random.randint(1,9);
drawn2 = random.randint(1,9);
drawn3 = random.randint(1,9);
drawn4 = random.randint(1,9);
# Variable for the drawn ticket in one single variable
drawnTotal = (drawn1, drawn2, drawn3, drawn4);
# Variable that changes the money variable so the player has 2 less dollars
money = money - 2;
it seems like the == sign gets ignored or acts differently. I wanted it to do the if if they are equal to each other.
if( drawnTotal == lotteryTotal):
count = count + 1;
money = money + 5;
print ("Lottery Numbers: " + str(lotteryTotal));
print ("Your Numbers: " + str(drawnTotal));
print ("You Won $5!");
input("Press Enter to continue")
else:
print ("Lottery Numbers: " + str(lotteryTotal));
print ("Your Numbers: " + str(drawnTotal));
print ("You Lost!");
input("Press Enter to continue");
Your code is working... the results are just not what you expected.
The problem is that, to win, you need to generate the same random sequence of digits twice in a row. What is the probability of that?
The probability of repeating a toss of a single 1-9 digit is 1 out of 9. If you have two such digits, you have two 1/9 probabilities and their compound probability is 1/9 * 1/9, or 1/81. If you have four as in your case, you'll win once every 1/9 * 1/9 * 1/9 * 1/9 = 1/6561 games.
You tried "many times", but... did you try enough times? Even after one thousand games, the probability of winning at least once is less than 15%. Even after 6561 games, the probability of winning at least once is nowhere near 100% - actually it's closer to two thirds.
I modified it to only tell me the number of wins, and to only do so when indeed you do win (MarkyPython's suggestion). After some time, it tells me,
100 won in 686114 games; win rate is 95% of expected.
(The first win, by the way, was after 29172 games).
Great explanation lserni.
Khodexian, in case if you are willing to increase the number of chances of winning you can simply take the numbers into account and disregard the sequence in which they were generated.
For example,
import random
# Creates a number to count the amount of plays
count = 0;
# Creates a variable to store the amount of starting money
money = 10;
# Creates a variable telling you how much money you start with
startingCash = "You start with $" + str(money) + "!";
win, lost = 0, 0
while (win < 100):
count = count + 1;
# Variables for the lottery numbers
lotteryTotal = [random.randint(1,9), random.randint(1,9), random.randint(1,9), random.randint(1,9)]
# Variable for the drawn ticket in one single variable
drawnTotal = [random.randint(1,9), random.randint(1,9), random.randint(1,9), random.randint(1,9)]
# Variable that changes the money variable so the player has 2 less dollars
money = money - 2;
if( sorted(lotteryTotal) == sorted(drawnTotal) ):
money = money + 5;
print ("Lottery Numbers: " + str(lotteryTotal));
print ("Your Numbers: " + str(drawnTotal));
print ("You Won $5!");
win += 1
else:
print ("Lottery Numbers: " + str(lotteryTotal));
print ("Your Numbers: " + str(drawnTotal));
print ("You Lost!");
lost += 1
print ('played {}, won {} and lost {}'.format(count, win, lost))
And I get a statistics like this,
played 40170, won 100 and lost 40070
Related
I wrote this from pseudo-code provided during class, and I've got most of it figured out. Only issue I'm running into is it's returning duplicate numbers for the first 5 'balls' and I can't at all figure out why. One of the lines in the pseudo-code I wasn't sure about was: "if that number is not in the main number sequence". I coded it like this:
if number != mainNumbers:
which could be the issue, but I'm not sure how else to code that.
from random import *
def drawing():
balls=0
mainNumbers=[]
while balls < 5:
number=randint(1,69)
if number != mainNumbers:
mainNumbers.append(number)
balls = balls + 1
mainNumbers.sort()
pBall=randint(1,26)
return mainNumbers, pBall
def main():
print("This program simulates a user defined number of Powerball drawings\n")
runs = int(input("What's the total number of drawings? "))
print()
count = 1
while count <= runs:
balls, pBall = drawing()
print("Drawing: {0} - The numbers are: {1} and the Powerball is: {2}".format(count, balls, pBall))
count = count + 1
main()
I'm doing a dice roll assignment. The rules are:
The points rolled on each player’s dice are added to their score.
If the total is an even number, an additional 10 points are added to their score.
If the total is an odd number, 5 points are subtracted from their score.
If they roll a double, they get to roll one extra die and get the number of points rolled added to their score.
The score of a player cannot go below 0 at any point.
The person with the highest score at the end of the 5 rounds wins.
Basically, what I've done is created variables of what 2 separate players roll in 2 rounds of the game, now I'm trying to add these variables together so that the player can have their total for round 1 and 2 combined. My teacher had mentioned something about a while function but that was all he was allowed to say, that plus I'm not sure how to do that.
I feel like what I've done is overly complicated, plus the fact it doesn't even work.
if (round2scoreP1 % 2) == 0 + (round1scoreP1 % 2) == 0:
addedscoreround2P1even=(totalround1scoreP1even)+(totalround2scoreP1even)
print(username1,"'s total for round 1 and 2 is",addedscoreround2P1even,".")
elif (round1scoreP1 % 2) != 0 + (round2scoreP1 % 2) != 0:
addedscoreround2P1odd=(totalround1scoreodd)+(totalround2scoreodd)
print(username1,"'s total for round 1 and 2 is",addedscoreround2P1odd,".")
elif (round1scoreP1 % 2) == 0 + (round2scoreP1 % 2) != 0:
addedscoreround2P1evenodd=(totalround1scoreP1even)+(totalround1scoreP1odd)
print(username1,"'s total for round 1 and 2 is",addedscoreround2P1evenodd,".")
elif (round1scoreP1 % 2) != 0 + (round2scoreP1 % 2) == 0:
addedscoreround2P1oddeven=(totalround1scoreP1odd)+(totalround1scoreP1even)
print(username1," obtained",addedscoreround2P1oddeven,".")
I'm not going to write you the whole assignment, but you could consider using a Player-class to store the rolls and total scores in:
class Player():
def __init__(self):
self.rolls = []
self.total_score = 0
def roll_dice():
self.rolls.append(random.randint(1, 6))
I am in a beginner programming course. We must do an exercise where we make a change maker program. The input has to be between 0-99 and must be represented in quarters, dimes, nickles, and pennies when the input is divided down between the four. I wrote a code that involved loops and whiles, but he wants something more easy and a smaller code. He gave me this as a way of helping me along:
c=int(input('Please enter an amount between 0-99:'))
print(c//25)
print(c%25)
He told us that this was basically all we needed and just needed to add in the dimes, nickles, and pennies. I try it multiple ways with the dimes, nickles, and pennies, but I cannot get the output right. Whenever I enter '99', I get 3 for quarters, 2 for dimes, 1 for nickles, and 0 for pennies. If anyone would be able to help me, that would be wonderful!
I'm now sure about what you want to achieve. Using the modulo operator you could easily find out how many quarters, dimes, nickles and pennies.
Let's just say you input 99.
c=int(input('Please enter an amount between 0-99:'))
print(c//25, "quarters")
c = c%25
print(c//10, "dimes")
c = c%10
print(c//5, "nickles")
c = c%5
print(c//1, "pennies")
this would print out:
3 quarters
2 dimes
0 nickles
4 pennies
n = int(input("Enter a number between 0-99"))
q = n // 25
n %= 25
d = n // 10
n %= 10
ni = n // 5
n %= 5
c = n % 5
print(str(q) +" " + str(d) +" " + str(ni) + " " + str(c))
I hope this helps? Something like this but don't just copy it. Everytime you divide by 25 10 5 you must lose that part because it's already counted.At the end print what ever you want :).
The actual trick is knowing that because each coin is worth at least twice of the next smaller denomination, you can use a greedy algorithm. The rest is just implementation detail.
Here's a slightly DRY'er (but possibly, uh, more confusing) implementation. All I'm really doing differently is using a list to store my results, and taking advantage of tuple unpacking and divmod. Also, this is a little easier to extend in the future: All I need to do to support $1 bills is to change coins to [100, 25, 10, 5, 1]. And so on.
coins = [25,10,5,1] #values of possible coins, in descending order
results = [0]*len(coins) #doing this and not appends to make tuple unpacking work
initial_change = int(input('Change to make: ')) #use raw_input for python2
remaining_change = initial_change
for index, coin in enumerate(coins):
results[index], remaining_change = divmod(remaining_change, coin)
print("In order to make change for %d cents:" % initial_change)
for amount, coin in zip(results, coins):
print(" %d %d cent piece(s)" % (amount, coin))
Gives you:
Change to make: 99
In order to make change for 99 cents:
3 25 cent piece(s)
2 10 cent piece(s)
0 5 cent piece(s)
4 1 cent piece(s)
"""
Change Machine - Made by A.S Gallery
This program shows the use of modulus and integral division to find the quarters, nickels, dimes, pennies of the user change !!
Have Fun Exploring !!!
"""
#def variables
user_amount = float(input("Enter the amount paid : "))
user_price = float(input("Enter the price : "))
# What is the change ?? (change calculation)
user_owe = user_amount - user_price
u = float(user_owe)
print "Change owed : " + str(u)
"""
Calculation Program (the real change machine !!)
"""
# Variables for Calculating Each Coin !!
calculate_quarters = u//.25
# Using the built-in round function in Python !!
round(calculate_quarters)
print "Quarters : " + str(calculate_quarters)
u = u%0.25
calculate_dime = u//.10
round(calculate_dime)
print "Dime : " + str(calculate_dime)
u = u%0.10
calculate_nickels = u//.05
round(calculate_nickels)
print "Nickels : " + str(calculate_nickels)
u = u%0.5
calculate_pennies = u//.01
round(calculate_pennies)
print "Pennies : " + str(calculate_pennies
Code for the change machine works 100%, its for CodeHs Python
This is probably one of the easier ways to approach this, however, it can also
be done with less repetition with a while loop
cents = int(input("Input how much money (in cents) you have, and I will tell
you how much that is is quarters, dimes, nickels, and pennies. "))
quarters = cents//25
quarters_2 = quarters*25
dime = (cents-quarters_2)//10
dime_2 = dime*10
nickels = (cents-dime_2-quarters_2)//5
nickels_2 = nickels*5
pennies = (cents-dime_2-quarters_2-nickels_2)
I have created a number guessing game, where a user chooses a range of numbers to guess from, and when the user inputs a number, the program will respond if they are too high or too low, until the user guesses correctly. The program currently takes the number of attempts, and the time taken into account. There are also different difficulties (the higher the difficulty the more numbers to guess from). I have tried to create a scoring system but I need a little more help with the math side. Right now I have this code that generates a score:
def scorer(tries, total_time, difficulty):
# Tells the user how much time and how many attempts were made
print "\nCorrect! It took you " + str(round(total_time, 2)) + \
" seconds and " + str(tries) + " tries to guess.\n"
# Calculates score, making lower times and fewer
# tries yield a higher score
# Difmod takes into account the difficulty
# Multiply by 1000 to make number more readable
score = 1 / (1 + (tries * round(total_time, 2))) * 1000 * dif_mod(difficulty)[1]
# Prints the score, rounded to 1 decimal place
print "Score: " + str(round(score, 2))
tries and total_time are self-explanatory, and dif_mod is a value I made to try to make the score 'fairer' to higher difficulties. The value of dif_mod is higher, the higher difficulty there is. As shown here:
def dif_mod(difficulty):
if difficulty == 1:
return [10, 1]
elif difficulty == 2:
return [50, 1.5]
elif difficulty == 3:
return [100, 2]
elif difficulty == 4:
return [1000, 10]
elif difficulty == 5:
return [10000, 20]
elif difficulty == 0:
return [1, 1]
The first value in the list is the highest possible number to guess from, the second item in the list is dif_mod. These are all placeholder values and I want to figure out what I should use for them.
My main aim is to make a score higher based on fewer attempts and less time taken, but to also reward a user with a higher score if they are on a higher difficulty.
I am trying to come up with a simulation for the Pig dice game. I want it to simulate for the number of games the user wants(each game to 100 points) and report the average points and percent wins for each player. My program is running but it is only running for one game. I think there is something wrong with my loop but i cannot tell. Thank you for your help and time here is my program:
from random import randrange # Use "randrange(1, 7)" to get a random
# number between 1 and 6.
# Takes one turn in the game of pig. Keeps rolling until either
# the holdAmount is reached or a pig (1) is rolled. Returns the
# score accumulated during the turn.
def takeTurn(holdAmount):
totalScore = 0
while totalScore < holdAmount:
rollValue = randrange(1,7)
if rollValue == 1:
totalScore = 0
break
else:
totalScore = totalScore + rollValue
return totalScore
# Start with turn score equal to 0. Repeatedly roll die, adding
# roll value to score each time, until score reaches holdAmount.
# If at any time a pig (1) is rolled, set score to 0 and end the
# turn early.
# Tests the takeTurn function.
def main():
first = eval(input("How many points should the first player try for in each turn?"))
second = eval(input("How many points should the second player try for in each turn?"))
games = eval(input("How many games should be simulated?"))
firstScore = 0
secondScore = 0
turnCount = 0
score = 0
score1 = 0
won = 0
won1 = 0
for i in range(games):
while firstScore < 100 and secondScore < 100:
firstScore = takeTurn(first) + firstScore
secondScore = takeTurn(second) + secondScore
turnCount = turnCount + 1
if firstScore >= 100:
won = won + 1
elif secondScore >= 100:
won1 = won1 + 1
score = score + firstScore
score1 = score1 + secondScore
percent = won / games
percent1 = won1 / games
points = score / games
points2 = score1 / games
print("The average points for player one is",points)
print("The percent of games won for player one is",percent)
print("The average points for player two is",points2)
print("The percent of games won for player two is",percent1)
if __name__ == "__main__":
main()
I was confused for a while when I first looked at this. The reason is that each game ends with the same score since you do not reset the firstScore, etc. values each time. If you set each of those to 0 at the beginning of your for loop, you won't have any problems.
To be more specific, if you move firstScore, secondScore, and turnCount inside your for loop at the very top of it, the code runs properly.
The traditional way to gain a better understanding of what your program is doing is to add some print statements at looping and branching points.
A more advanced technique is to trace through the program using pdb.
You need firstScore and secondScore inside your for-loop.