I want to calculate the experimental probability of heads in coin toss by generating 0s or 1s randomly and assign 'h' for 0 and 't' for 1 to n. The number of flips is 100.
import random
array_ht = []
flip_count = 0
while flip_count != 100:
n = random.randint(0,1)
if n == 0:
n = "h"
elif n == 1:
n = "t"
flip_count += 1
array_ht.append(n)
for x in array_ht:
h_count = 0
if x == "h":
h_count += 1
print(h_count + "%")
The for loop looks through every object of array_ht and if it finds an "h", it adds 1 to the number of head flips. But the code isn't working and just prints "1% 0% 1% 0% 0% ..."
What should actually happen is for example if sequence generated was '0,1,1,0,0,0,1,1,1' then array_ht = [h,t,t,h,h,h,t,t,t] and probability to be printed is (4/9*100=) 44.444444%.
Actually we don't need to assign 'h' or 't' to n, we can just look for number of 0s but earlier I had wanted to print array_ht also.
Does this help? This calculates the probality of both h
and t
in %
percentage format.
EXPLANATION:
import random
tosses = []
# Getting A List With 100, 0s and 1s in it
for i in range(100):
tosses.append(random.randint(0, 1))
# Indexing Every 0 for a `h` and every 1 for a `t`
for i in range(len(tosses)):
if tosses[i] == 0:
tosses[i] = "h"
else:
tosses[i] = "t"
# Getting Count Of How Many Times Heads Or Tails Was In The List
freq_h = tosses.count('h')
freq_t = tosses.count('t')
# Calculating The Probablity (freq/total_outcomes) (x100 optional if want to calculate in percentage use x100)
prob_h = (freq_h/len(tosses))*100
prob_t = (freq_t/len(tosses))*100
# Adding A `%` sign to the numbers and round them up
percent_h = str(round(prob_h)) + "%"
percent_t = str(round(prob_t)) + "%"
# The Final Result
print("Probablity Heads:", percent_h)
print("Probablity Tails:", percent_t)
EDIT: A Much Shortened Version Of The Previous Solution(Quick And Dirty)
import random
tosses = []
for i in range(100):
tosses.append(random.randint(0, 1))
for i in range(len(tosses)):
if tosses[i] == 0:
tosses[i] = "h"
else:
tosses[i] = "t"
print("Probablity Heads:", str(round((tosses.count('h')/len(tosses))*100)) + "%")
print("Probablity Tails:", str(round((tosses.count('t')/len(tosses))*100)) + "%")