Python code for the coin toss issues - python

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)

Related

Python - while loop count

I need to know the score of "heads" and "tails" in 5 times tossing the coin.
For example, the result should be:
- Heads was 3 times
- Tails was 2 times
import random
print("Heads or tails. Let's toss a coin five times.\n")
toss = 1
while toss <= 5:
coin = ["HEADS", "TAILS"]
y = random.choice(coin)
print("Toss number:", toss, "is showing:", y)
toss = toss + 1
I have made changes to your code to count the frequency of each coin side (Heads or Tails),
import random
print("Heads or tails. Let's toss a coin five times.\n")
toss = 1
counts = {"HEADS": 0, "TAILS": 0}
while toss <= 5:
coin = ["HEADS", "TAILS"]
y = random.choice(coin)
counts[y] += 1
print("Toss number:", toss, "is showing:", y)
toss = toss + 1
print("Heads was " + str(counts["HEADS"]) + " times - Tails was " + str(counts["TAILS"]) + " times")
You should have two variables, head and tail:
import random
print("Heads or tails. Let's toss a coin five times.\n")
head = tail = 0
for i in range(5):
coin = ["HEADS", "TAILS"]
y = random.choice(coin)
print("Toss number:", i, "is showing:", y)
if y == "HEADS":
head += 1
elif y == "TAILS":
tail += 1
Or, a better solution would be having a dictionary with keys representing heads and tails, with the value representing the count.
One simple solution would be to let toss be a list of coin toss results. Starting with an empty list, you could loop until the list contained 5 results and on each toss push a new member into the list. That way you end up with a single data structure that contains all the information you need about the tosses.
Create two variables, initialize them to 0, check the result of the coin toss in a if block and add accordingly.
heads, tails = 0, 0
if y == "HEADS":
heads += 1
else:
tails += 1
return (heads, tails)

Consecutive Coin Flip Counting in Python

I'm new to programming and have encountered an error that I can't seem to debug, no matter what alterations I make. I'm attempting to write a function that allows the user to specify the number of flips and the length of a consecutive streak of coin flips. The program is supposed to count the number of times that the streak (heads or tails) occurs. When I run my current program, I return a value of 1 for both heads and tails:
import random
def flip():
flipValue = random.randint(1,2)
if flipValue == 1:
side = "Heads"
else:
side = "Tails"
return side
def nStreak():
numFlips = int(input("Number of flips:"))
lengthStreak = int(input("Length of streak:"))
numRuns = 0
heads = 0
tails = 0
numStreakHeads = 0
numStreakTails = 0
while numRuns != numFlips:
side = flip()
numRuns += 1
if side == "Heads":
heads += 1
if heads == lengthStreak:
numStreakHeads += 1
if side == "Tails":
tails += 1
if tails == lengthStreak:
numStreakTails += 1
print("Number of heads streaks:", numStreakHeads)
print("Number of tails streaks:", numStreakTails)
For one thing, you're not resetting your counter after you reach lendthStreak. So once, say, heads is equal to lendthStreak it will be greater than lendthStreak every time afterwards, thus you'll always get a result of 1. You want to reset that value after you've encountered a streak. You'll also want to reset your counter once you get a flip of the opposite side (once you flip heads, set tails=0).
import random
def flip():
flipValue = random.randint(1,2)
if flipValue == 1:
side = "Heads"
else:
side = "Tails"
return side
def nStreak():
numFlips = int(input("Number of flips:"))
lengthStreak = int(input("Length of streak:"))
numRuns = 0
heads = 0
tails = 0
numStreakHeads = 0
numStreakTails = 0
while numRuns != numFlips:
side = flip()
numRuns += 1
if side == "Heads":
heads += 1
tails = 0
if heads == lengthStreak:
numStreakHeads += 1
heads = 0
if side == "Tails":
tails += 1
heads = 0
if tails == lengthStreak:
numStreakTails += 1
tails = 0
print("Number of heads streaks:", numStreakHeads)
print("Number of tails streaks:", numStreakTails)

Heads or Tails / Coin-flip program

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.

100 random numbers with an odd and even counter

I have the following assignment:
In this chapter you saw an example of how to write an algorithm that determines whether
a number is even or odd. Write a program that generates 100 random numbers, and keeps
a count of how many of those random numbers are even and how many are odd.
This is how far I've been able to get, I can get the 100 numbers, but I can't figure out how to total up the odd and evens. This is supposed to include a value returning boolean function as well.
All we're allowed to use is loops, if-elif-else, functions, and other basic things.
import random
NUMBER_LIST = [random.randint(0,1000)]
def main():
for numbers in range(100):
number = print(NUMBER_LIST)
number
is_even(number)
print('The total amount of even numbers is', even_count)
print('The total amount of odd numbers is', 100 - even_count)
def is_even(number):
even_count = 0
for number in NUMBERS_LIST:
if (number % 2):
even_count += 1
return even_count
main()
EDIT:
I'm not supposed to use a List, so if theres a way to do it without, let me know!
import random
def main():
numberList = [] # create an empty list, to add 100 random ints to
for i in range(100):
numberList.append(random.randint(1,1000)) # add a random int
# now, numberList has 100 random numbers in it
# keep track of how many odd numbers
oddCount = 0
# loop through numberList
for number in numberList:
if number%2 == 1: # number is odd
oddCount += 1
evenCount = 100 - oddCount # if a number is not odd, it is not even
print("There are", oddCount, "odd numbers, and", evenCount, "even numbers")
Okay, now that we have that hard-coded version, let's try a more flexible way that allows you to specify as many things as possible:
def main(numNumbers, smallestNumber, biggestNumber):
numberList = []
for i in range(numNumbers):
numberList.append(random.randint(smallestNumber, biggestNumber))
oddCount = 0
for number in numberList:
if number%2: # oh look, I didn't have to do the `== 1` part
oddCount += 1
evenCount = numNumbers - oddCount
print("There are", oddCount, "odd numbers, and", evenCount, "even numbers")
import random
NUMBER_LIST = [random.randint(0,1000)]
even = 0;
odd = 0;
for numbers in range(100):
if (numbers%2 == 1):
odd = odd+1
if (numbers%2 == 0):
even = even+1
print('number of evens is: ',even)
print('number of odds is: ',odd)
So you can just do this sort of thing.
from random import randrange
even = 0
for i in range(100):
num = randrange(1000)
if num % 2 == 0:
even += 1
print('There were {0} even numbers and {1} odd numbers.'.format(even, 100-even))
You can do this without a list, but let's do that since your problem may require so.
First of all, note that your code just creates a list with one random number inside it. If you want to populate the list with 100 random numbers, you must do something similar to this:
NUMBER_LIST = []
i = 0
while i < 100:
number = random.randint(0, 1000)
NUMBER_LIST.append(number)
i += 1
Then, you check if the number is even, with number % 2 == 0 (That is, the remainder of the division of number by 2 is 0. this will return either true or false) and increment the respective counter:
NUMBER_LIST = []
# initialize both counters
evens = 0
odds = 0
i = 0
while i < 100:
number = random.randint(0, 1000)
NUMBER_LIST.append(number)
if number % 2 == 0:
evens += 1
else:
odds += 1
i += 1
Then, you just need to print the counts:
print("The number of even numbers is: " + evens)
print("The number of odd numbers is: " + odds)
The full code would then be:
import random
NUMBER_LIST = []
evens = 0
odds = 0
i = 0
while i < 100:
number = random.randint(0, 1000)
NUMBER_LIST.append(number)
if number % 2 == 0:
evens += 1
else:
odds += 1
i += 1
print("The numbers were: " + str(NUMBER_LIST))
print("The number of even numbers is: " + evens)
print("The number of odd numbers is: " + odds)
And without the list:
import random
evens = 0
odds = 0
i = 0
while i < 100:
number = random.randint(0, 1000)
if number % 2 == 0:
evens += 1
else:
odds += 1
i += 1
print("The number of even numbers is: " + evens)
print("The number of odd numbers is: " + odds)
#!/usr/bin/env python3
import random
def main(n=100):
NUMBER_LIST = [random.randint(0,1000) for x in range(0,n)]
odds = len(list(filter(lambda x: x % 2, NUMBER_LIST)))
print("Odd Numbers: {}\nEven Numbers: {}".format(odds, n-odds))
if __name__ == "__main__":
main()
I am in the same class! This code worked for me.
import random
def main ():
counter = 1
even_numbers = 0
odd_numbers = 0
while counter < 101:
a = random.randint(1,100)
if a % 2 == 0:
even_numbers += 1
else:
odd_numbers += 1
counter += 1
if counter == 101 :
reveal_total(even_numbers, odd_numbers)
def reveal_total(even_numbers, odd_numbers):
print("This many evens : ", even_numbers)
print("This many odds : ", odd_numbers)
main()

python - infinite coin flip that stops when number of heads = number of tails

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)

Categories