I'm a Beginner; I'm trying to make a program in python 3.5 that flips a coin 100 times, then counts the amount of heads and tails from those 100 flips and displays it at the bottom. I got the 100 flips to work, and I also tried to make a counter to count the amount of h/t that landed, but it's inconsistent and wonky, and the counters doesn't count the correct amount. I would love it if some one could help me.
import random
hcounter = 0
tcounter = 0
while True:
flip = ['heads','tails']
decision = input("Flip a coin 100 times? (y/n): ")
if decision == 'y':
#for some reason, the range doubles the number; I dont know why, so since I want 100 flips, I put 50 for the range.
for x in range(0, 50):
for y in flip:
print(random.choice(flip))
if random.choice(flip) == flip[0]:
hcounter += 1
elif random.choice(flip) == flip[1]:
tcounter += 1
print("--------------------------------")
print("Heads: ",hcounter,"\nTails: ",tcounter)
elif decision == 'n':
print("\nOk")
break
yeah
This is a really good start to coding! A few things to fix, let's go through 'em.
if random.choice(flip) == flip[0]:
hcounter += 1
elif random.choice(flip) == flip[1]:
tcounter += 1
This isn't correct. If it isn't a head, it is a tail, but you call random.choice(flip) again, asking Python if it is now a tail. If it goes tails then heads, we don't add anything.
for x in range(0, 50):
for y in flip:
The first line will make the program run 50 times. But then in each of those 50 loops, the for y will make it run 2 times, once with y as heads and once for y as tails. We don't need this at all.
Apart from that, good job!
import random
hcounter = 0
tcounter = 0
while True:
flip = ['heads','tails']
decision = input("Flip a coin 100 times? (y/n): ")
if decision == 'y':
for x in range(0, 50):
if random.choice(flip) == flip[0]:
print("Heads!")
hcounter += 1
else:
print("Heads!")
tcounter += 1
print("--------------------------------")
print("Heads: ",hcounter,"\nTails: ",tcounter)
elif decision == 'n':
print("\nOk")
break
The doubling comes from this:
for x in range(0, 50): # 50 loops
for y in flip: # each with two more operations
An easier way to do this would be something like
flip = ['heads', 'tails']
results = [ random.choice(flip) for i in range(100)]
head_counter = results.count(flip[0])
tail_counter = results.count(flip[1])
If you want to practice incremental counting:
flip = ['heads', 'tails']
results = []
heads, tails = 0, 0
for _ in range(100):
results.append(random.choice(flip))
if results[-1] == flip[0]:
heads += 1
else:
tails += 1
enter code here
You can also do that without a for-loop:
k = 100 # times
hcounter = sum(random.choices([0,1],k=k)) # or tails if you want :)
print("Heads: ", hcounter,"\nTails: ", k - hcounter )
Your code is great... except for one part. There is a unnecessary line of code in there. You mentioned doubling correct? Well that's were it comes from. I suggest take of the line of code:
for y in flip:
You see what this is doing is incrementing through you heads and tails list and size the len of that list is two it doubles. If it was three it would triple. So if you take it off it should only do it once. You code would look like this. Tell me if it works:
import random
hcounter = 0
tcounter = 0
while True:
flip = ['heads','tails']
decision = input("Flip a coin 100 times? (y/n): ")
if decision == 'y':
#for some reason, the range doubles the number; I dont know why, so since I want 100 flips, I put 50 for the range.
for x in range(0, 50):
print(random.choice(flip))
if random.choice(flip) == flip[0]:
hcounter += 1
elif random.choice(flip) == flip[1]:
tcounter += 1
print("--------------------------------")
print("Heads: ",hcounter,"\nTails: ",tcounter)
elif decision == 'n':
print("\nOk")
break
Related
So I'm a trying to create a function which first flips an unbiased coin but if the result is heads it flips a biased coin with 0.75 probability of heads. If it shows tails then the next flip is unbiased. I've tried the following code but I can only run this flow once i.e., if it's a head, then only the next one flip is biased and then the flow is returning to the top of the 'for' loop. Is there any recursion that I can do which can keep it inside the loop?
def prob1():
choices = []
for _ in range (1,501):
x = random.choice(Toss_list)
if x == 0:
y = random.choices(Toss_list, weights=(0.75,0.25))
else:
y = random.choices(Toss_list, weights=(1,1))
choices.append(x)
choices.append(y)
heads = choices.count([0])+choices.count(0)
tails = choices.count([1])+choices.count(1)
return print(f'Count of heads = {heads} and count of tails = {tails}' )
From what I understand, the biasing only depend on the previous choice.
I would simplify the code with this:
import random
tossList = ['H', 'T']
choice = 'T' # first choice will be unbiased
heads,tails = 0,0
for _ in range(500):
weights = (0.5, 0.5) if choice == 'T' else (0.75, 0.25)
choice = random.choices( tossList, weights)
if choice == ['H']:
heads += 1
else:
tails += 1
print( f'Count of heads = {heads} and count of tails = {tails}' )
You can put it in a infinite loop such as
While True:
#Do code here
Or
#Exsample:
tosses = 1
while tosses <= 10:
print(tosses )
tosses += 1
You can try this:
import random
def prob1():
choices = []
biased_flag = 0
for _ in range (1,501):
x = random.choices(Toss_list, weights=(0.75,0.25)) if biased_flag else random.choice(Toss_list)
if x == 0 and biased_flag == 0:
biased_flag = 1
# implement other rules that decide the coin to use for the next toss
choices.append(x)
heads = choices.count([0])+choices.count(0)
tails = choices.count([1])+choices.count(1)
return print(f'Count of heads = {heads} and count of tails = {tails}' )
I'm trying to write a program in Python that flips a coin and returns the longest series of heads and tails. It asks the user how many times to flip the coin. For some reason my program isn't running and I cant figure out why. I don't know why it isn't asking the user for the "number of flips" and "as a character string" for example.
import random
def flip():
flipValue = random.randint(1,2)
if flipValue == 1:
side = "Heads"
else:
side = "Tails"
return side
def nStreak():
number = int(input("Number of flips: "))
chars = int(input("As a character string: "))
series = 0
heads = 0
tails = 0
longest_h = 0
longest_t = 0
while series != number:
side = flip()
series += 1
if side == "Heads":
heads += 1
tails = 0
if heads == chars:
longest_h += 1
heads = 0
if side == "Tails":
tails += 1
heads = 0
if tails == chars:
longest_t += 1
tails = 0
print("Number of heads streaks: ", longest_h)
print("Number of tails streaks: ", longest_t)
When I run it I get nothing.
You need to call the function at the last line.
nStreak()
Or else it won't execute the code.
At the bottom of your script add nStreak() with no identation.
I want to write a coin flip or "Heads or Tails" program, but when I run it, it only gets either heads or tails everytime. I can't see why, it's a logical error so I find it hard to spot.
import random
flips = 1
coin = random.randint(1,2)
heads = 0
tails= 0
while flips <= 100:
if coin == 1:
print("Heads")
heads += 1
flips +=1
elif coin == 2:
print("tails")
tails += 1
flips +=1
print("You got", heads, "heads and", tails,"tails!")
input("Exit")
Python removes a lot of code writing that you have to do in other languages. This program is only three lines. Using the random() method, you're able to do this in a very simple matter.
Here is my code.
import random
coin_flip = ['heads','tails']
print random.choice(coin_flip)
import random
flips = 0
heads = 0
tails = 0
while flips < 100:
if random.randint(1,2) == 1:
print("heads")
heads += 1
else:
print("tails")
tails += 1
flips += 1
print("you got ", heads," heads, and ", tails," tails!")
input ("exit")
Changes made: starts from 0 and is only raising count when a flip has been made (also, flip is made every iteration as the cases are contained enough)
also, im not casting the toss to a seperate variable but comparing it immediately.
my output was:
you got 54 heads, and 46 tails!
exit
without listing the seperate flips
Note; this was the first time I ever wrote python. If there's room for optimalisation, let me know!
Try this:
import random
flips = 1
heads = 0
tails= 0
while flips <= 100:
coin = random.randint(1,2)
flips +=1
if coin == 1:
print("Heads")
heads += 1
elif coin == 2:
print("tails")
tails += 1
print("You got " + str(heads) + " heads and " + str(tails) + " tails!")
raw_input("Exit")
Edits i made:
put coins variable in loop so that a new random value is assigned on every call.
I'm new to python and I'm trying to create a coinflip loop which will keep flipping and counting the number of flips until the number of heads = the number of tails, where it will stop and print the total number of flips it took to reach that. I'm trying to get the results in order to work on my maths coursework, but I cannot seem to figure out how to get it to stop or print the results, and when I do it prints 0. Here is the code I have so far:
import random
heads = 1
tails = sum(random.choice(['head', 'tail']) == 'tail'
count = 0
while True:
coinresult = random.randint(1, 2) if heads == tails:
break
print("The number of flips was {count}".format(count = heads + tails))
not sure what is going on with your indentation but try this:
import random
heads = 0 #initialize the count variables
tails = 0
while True:
coinresult = random.randint(1, 2) #flip coin
if coinresult == 1: #if result = 1 then increment heads counter
heads += 1
elif coinresult == 2: #if result = 2 then increment tails counter
tails += 1
if heads == tails: #check if counts are equal and break loop if they are
break
print("The number of flips was {count}".format(count = heads + tails))
import itertools as it
import random
def flips():
while True:
yield (random.getrandbits(1)<<1) - 1
def cumsum(seq):
s = 0
for i in seq:
s += i
yield s
def length(seq):
n = 0
for _ in seq:
n += 1
return n
print("The number of flips was {}".format(length(it.takewhile((0L).__cmp__, cumsum(flips())))))
I think this will be a nice implementation
import random
s = 0
iteration = 0
while True:
coin = random.sample([-1,1], 1)[0]
s = s + coin
iteration = iteration + 1
if s == 0:
break
print(iteration)
I've been writing a program in python that simulates 100 coin tosses and gives the total number of tosses. The problem is that I also want to print the total number of heads and tails.
Here's my code:
import random
tries = 0
while tries < 100:
tries += 1
coin = random.randint(1, 2)
if coin == 1:
print('Heads')
if coin == 2:
print ('Tails')
total = tries
print(total)
I've been racking my brain for a solution and so far I have nothing. Is there any way to get the number of heads and tails printed in addition to the total number of tosses?
import random
samples = [ random.randint(1, 2) for i in range(100) ]
heads = samples.count(1)
tails = samples.count(2)
for s in samples:
msg = 'Heads' if s==1 else 'Tails'
print msg
print "Heads count=%d, Tails count=%d" % (heads, tails)
import random
total_heads = 0
total_tails = 0
count = 0
while count < 100:
coin = random.randint(1, 2)
if coin == 1:
print("Heads!\n")
total_heads += 1
count += 1
elif coin == 2:
print("Tails!\n")
total_tails += 1
count += 1
print("\nOkay, you flipped heads", total_heads, "times ")
print("\nand you flipped tails", total_tails, "times ")
You have a variable for the number of tries, which allows you to print that at the end, so just use the same approach for the number of heads and tails. Create a heads and tails variable outside the loop, increment inside the relevant if coin == X block, then print the results at the end.
Keep a running track of the number of heads:
import random
tries = 0
heads = 0
while tries < 100:
tries += 1
coin = random.randint(1, 2)
if coin == 1:
heads += 1
print('Heads')
if coin == 2:
print ('Tails')
total = tries
print('Total heads '.format(heads))
print('Total tails '.format(tries - heads))
print(total)
import random
tries = 0
heads=0
tails=0
while tries < 100:
tries += 1
coin = random.randint(1, 2)
if coin == 1:
print('Heads')
heads+=1
if coin == 2:
print ('Tails')
tails+=1
total = tries
print(total)
print tails
print heads
tosses = 100
heads = sum(random.randint(0, 1) for toss in range(tosses))
tails = tosses - heads
You could use random.getrandbits() to generate all 100 random bits at once:
import random
N = 100
# get N random bits; convert them to binary string; pad with zeros if necessary
bits = "{1:>0{0}}".format(N, bin(random.getrandbits(N))[2:])
# print results
print('{total} {heads} {tails}'.format(
total=len(bits), heads=bits.count('0'), tails=bits.count('1')))
Output
100 45 55
# Please make sure to import random.
import random
# Create a list to store the results of the for loop; number of tosses are limited by range() and the returned values are limited by random.choice().
tossed = [random.choice(["heads", "tails"]) for toss in range(100)]
# Use .count() and .format() to calculate and substitutes the values in your output string.
print("There are {} heads and {} tails.".format(tossed.count("heads"), tossed.count("tails")))
I ended up with this.
import random
flips = 0
heads = 0
tails = 0
while flips < 100:
flips += 1
coin = random.randint(1, 2)
if coin == 1:
print("Heads")
heads += 1
else:
print("Tails")
tails += 1
total = flips
print(total, "total flips.")
print("With a total of,", heads, "heads and", tails, "tails.")
Here is my code. Hope it will help.
import random
coin = random.randint (1, 2)
tries = 0
heads = 0
tails = 0
while tries != 100:
if coin == 1:
print ("Heads ")
heads += 1
tries += 1
coin = random.randint(1, 2)
elif coin == 2:
print ("Tails ")
tails += 1
tries += 1
coin = random.randint(1, 2)
else:
print ("WTF")
print ("Heads = ", heads)
print ("Tails = ", tails)
import random
print("coin flip begins for 100 times")
tails = 0
heads = 0
count = 0
while count < 100: #to flip not more than 100 times
count += 1
result = random.randint(1,2) #result can only be 1 or 2.
if result == 1: # result 1 is for heads
print("heads")
elif result == 2: # result 2 is for tails
print("tails")
if result == 1:
heads +=1 #this is the heads counter.
if result == 2:
tails +=1 #this is the tails counter.
# with all 3 being the count, heads and tails counters,
# i can instruct the coin flip not to exceed 100 times, of the 100 flips
# with heads and tails counter,
# I now have data to display how of the flips are heads or tails out of 100.
print("completed 100 flips") #just to say 100 flips done.
print("total tails is", tails) #displayed from if result == 2..... tails +=1
print("total heads is", heads)