modified coin toss program won't run - python

So I have to complete an assignment in which a coin toss is simulated and the number of flips, tails, and heads must be counted.
My first problem was that I could not get the number of heads or tails to display, fixed that, but then it was doubling(ex: I request 50 flips and the total amount of heads and tails would equate to 100), figured out that I had accidentally made it so it was counting up twice instead of once per flip, when I changed that the program just doesn't seem to run.
When I input the amount of times I would like the coin to flip and hit enter it just does nothing and goes to the next line on my terminal. I have removed all white space off my program in case of infinite looping other than that I cannot figure out what is causing this.
Thank you for any help.

You need to remove below line, otherwise it will keep on looping
count +=1
Because, at the same time you are incrementing head or tail as well.
Assuming, you provided input 1 then, it will check
head+tail < count # 0 < 1 , which is true
then assuming coin=1 then,
count+=1
head= head+1
For the next loop
head+tail < count # 1 < 2 , which is true

The issue is that you increment your count variable, alongside your head and tails counts. So you are in a while loop aiming for a moving target. I am not attempting to compete with Ravi for the accepted answer, but here is a simplified version of your code.
You needn't use a while loop, as you know how many iterations you will do. In this case a for loop is the appropriate tool.
from random import choice
heads = tails = 0
count = int(input('how many flips? '))
for _ in range(count):
if choice([True, False]):
heads += 1
else:
tails += 1
print('you flipped %d times' % count)
print('you flipped %d heads and %d tails' % (heads, tails))

Related

Running the Random method 'choices' for an unknown number of iterations

Consider the following code
import random
fruits = [0, 0]
for _ in range(1000):
if random.choices(['apple', 'orange'], weights=[0.5, 0.5])[0] == 'apple':
fruits[0] += 1
else:
fruits[1] += 1
Looks pretty standard, predictable "output" in the list fruits. But what if you instead let it run for an unknown period of time, face-offs on top of each other, and certain criterion must be met.
def game():
pts_apple = 0
pts_orange = 0
while True:
if random.choices(['apple', 'orange'], weights=[0.54, 0.46])[0] == 'apple':
pts_apple += 1
else:
pts_orange += 1
if pts_apple >= 5 and pts_apple - pts_orange >= 3: # change for bigger differences
pts_apple = 0
pts_orange = 0
fruits[0] += 1
break
elif pts_orange >= 5 and pts_orange - pts_apple >= 3:
pts_apple = 0
pts_orange = 0
fruits[1] += 1
break
What I've noticed is the disparity is more prominent when the criterion for minimum number of points increases, and the when the difference between them must be greater. So, what is going on? I have though about this for quite som time, but I'm stumped. Why would the probability of a winner change so radically? I can only think of one reason
There is som kind of "stacking" going on. So, you win one, but then you must win another, then yet another and so on, until you meet the criteria. Because 'apple' has greater odds, there is a greater chance for 'apple' to win.
Am I missing something?
Also, how would you go about minimizing the disparity, if you have to use certain numbers? You want to be able to find the probability before you do the computation, but you don't know the number of 'face-offs'! For example, if you stack them, two 'face-offs' has 'apple' at a two-win probability of .54 * .54, right? But what if there are 200 'face-offs' before you find a winner? Do you use a normal distribution?
Cheers!
It looks like the code you've provided simulates a simple game where players can choose to play as either an "apple" or an "orange". In each round of the game, a player wins a point if they choose the fruit that is chosen by the random.choices function. The game continues until one player has scored at least five points and has at least a three-point lead over the other player. When this happens, the winning player's score is added to the fruits list and the game resets.
The key difference between the first code snippet and the game() function is that the first code snippet simply counts how many times an "apple" or an "orange" is chosen by the random.choices function, while the game() function simulates a game where players can win and lose points. This means that the output of the game() function will be different from the output of the first code snippet.
One thing to note is that the game() function has a potential for an infinite loop, because it does not have any conditions for ending the game if it goes on for too long. This could potentially cause problems if the function is allowed to run for a very long time. It might be a good idea to add a maximum number of rounds or a timeout to the game to prevent this from happening.

How do I fix my (supposedly while-loop or if-statement) dice-simulator in Python so it prints the amount of tries its taken before landing on a 6?

So, I'm a little stuck on a coding assignment of mine – I'm supposed to write a code in Python simulating the throw of a dice, in which the program randomizes numbers between 1-6 until it "lands" on the number 6; the program is furthermore supposed to count the number of tries it has "thrown the dice" before "landing" on a 6, and print out print("It took", n, "tries to get a six.") in which n = the number of tries it has thrown the dice before landing on a 6.
This is what I've come up with thus far:
import random
dice = random.randint(1,6)
n = 0
while dice == 6:
n = n + 1
print("It took", n, "tries to get a 6.")
break
But, alas, it only prints out "It took 1 try to get a 6." in the result window and shows blank in the result window whenever the "dice" doesn't land on a 6. I guess what my question is, is: how do I get it to count all the tries before landing on a 6, and subsequently print the said amount of tries in combination with the statement print("It took", n, "amount of tries to get a 6.")?
The usual pattern for repeating an action an unknown number of times is to use a while True loop, and then break out of the loop when the exit condition is satisfied.
rolls = 0
while True:
die = random.randint(1, 6)
rolls += 1
if die == 6:
break
print("It took", rolls, "tries to get a 6.")
You need to write your break command into an if-statement.
In your current code it breaks within the first iteration.
As this is an assigment i dont want to tell you everything.
But that while loop condition won't get you there.
Try writing a blank while loop with a break-condition, think about it.

Calculating an average in "Rock, Paper, Scissors"

Last night I was thinking to my self about the probability of getting the same outcome in "Rock, Paper, Scissors" 10 times in a row. I worked out how to do that and completed that task but then I wanted to challenge myself a bit, so I wanted to adapt the program so it ran the initial program a number of times (10,000) and then outputted the average result, which I hoped would be close to the probability of getting the same 10 times in a row. Please note that I am not taking into account tactics, just that both players randomly pick either r, p, or s.
def rps():
num=0 # num is the number of times i want the programme to run while roll<10:
total=0 # this should be close to 3^10 * 10000, its the result of all the tries added together
while num <10001:
tries=0 # this is how many times the programme has tried to get p1=p2
roll=0 # this is the amount of times it has counted p1=p2 (it gets re-set everytime it reaches 10)
import random
while roll <10:
p1=random.randint(1,3)
p2=random.randint(1,3)
if p1==p2:
roll=roll+1
else:
tries=tries + 1
roll=0
num=num+1
if roll==10:
total=total+roll
roll=0
if num==10000:
print (num)
print (total/num)
rps()
There are quite a few problems with the program, for once, there isn't any use for the second for loop, I get that you are using the second for loop to reset the counter if the number of consecutive rolls reaches 10, but you are already doing that here
if roll==10:
total=total+roll
roll=0
by setting roll=0, you are resetting it.
also, the last if condition adds to the complexity,
if num==10000:
print (num)
print (total/num)
instead of this, you can just print the average outside the loop like this
if roll==10:
total=total+roll
roll=0
print (total/10000) #this being outside the while loop
one more thing, you are incrementing num only when roll1 != roll2, this adds to the number of times the loop has to run
This is how the program came out after the changes
import random
def rps():
num=0 #num is the number of times i want the programme to run while roll<10:
total=0 #this should be close to 3^10 * 10000, its the result of all the tries added together
roll = 0
while num <10001:
tries=0 #this is how many times the programme has tried to get p1=p2
p1=random.randint(1,3)
p2=random.randint(1,3)
if p1==p2:
roll = roll+1
else:
tries = tries + 1
roll = 0
if roll==10:
print(roll)
total += roll
roll=0
num = num + 1
print (total/10000)
print(tries)
rps()
The answer coming out was 0,I guess it was highly unlikely that you get 10 in a row.
Some self-explanatory code (so you can also learn to write clean code):
import random
def get_10_outcomes():
return [
(random.randint(1, 3), random.randint(1, 3))
]
def have_we_got_10_in_a_row():
return (
len(set(get_10_outcomes()))
== 1
)
def how_many_10_in_a_row_in_10000():
return len(list(filter(
None,
[have_we_got_10_in_a_row() for _ in range(10000)]
)))
def get_chance_of_10_in_a_row():
return how_many_10_in_a_row_in_10000() / 10000
chance = get_chance_of_10_in_a_row()
print('{:.3%}'.format(chance))

First timer on StackOverflow---Having trouble with recursion. Trying to have the computer recursively guess the user's number

I'm having a little trouble with this program. I'm a newbie to recursion by the way. Anyway I'm running this and i feel like it should work but it just becomes an infinite loop. Error message is "maximum recursion depth exceeded in comparison". I'm just taking a number, upper and lower limit from the user and having the computer guess it recursively. Any help would be greatly appreciated!
game where computer guesses user's number using recursion
import random as rand
def recursionNum(compGuess, magicNum):
#if the number that the user inputs for the computer to
#guess is to low it multiplies the number by 2 and then subtracts 1
#if the number is to high its divided(//) by 2 and then adds 1
if compGuess == magicNum:
print('You guessed right') #basecase
elif compGuess > magicNum:
print('Guess is', compGuess, '...Lower')
return recursionNum(compGuess //2+1, magicNum)
else:
print('Guess is', compGuess,'....Higher')
return recursionNum(compGuess *2-1, magicNum)
userNum =0
lowerLim = 0
upperLim = 0
while userNum not in range(lowerLim, upperLim):
lowerLim = int(input('What your lower limit: '))
upperLim = int(input('What is yor upper limit: '))
userNum = int(input('pick a number within your set limits:'))
compGuess = rand.randint in range(lowerLim, upperLim)
recursionNum(compGuess, userNum)
First of all, you will never print anything because the print statement is after the return. Return returns control back to the calling scope and so lines following a return statement are ignored. Second, there is no reason to use recursion for this. A simple for loop is much better suited for this. If you are just looking for an application to practice recursion on, may I suggest a Fibonacci number generator? It is a fairly popular example for the topic.

While count in python

user_answer = (raw_input('Can you guess the word that is missing? ')).lower()
count =0
while count <=1:
if user_answer == 'brown':
print ('Well done')
break
else:
user_answer =(raw_input('Please Guess again? '))
count+=1
else:
print ("Fail Game")
I'm working on a simple game and it allows the user to input the wrong guess three times. I have been playing around with this while loop and it works, (while count <=1) but i am a little confused as too why??? (not complaining) but can anyone explain why it works as i originally though the code should be like to one below (but these uses 5 attempts)
count = 0
while count <=3:
all rest of code is same as above.
The maximum number of inputs you can get with that code is 3. Why?
The first is outside the loop.
The second is when count is 0. After the input, count will be 1.
The third (and last) is when count is 1. After the input, count will be 2. The loop will finish in the next iteration because the condition 2 <= 1 will be False.

Categories

Resources