+ 2

# How to print the sample space of an experiment in Python??

My question is some probability related like we will specify that we have 2 elements H and T and the coin is tossed 3 times and our each array element will have length of 3 like HHH so the program will give all the possible combinations what we call sample space in probability.

1 Answer

+ 4

Can we print the sample space for one coin toss? Sure:
def space():
print "H"
print "T"
Now the sample space for 2 coins is just whatever the first coin is plus the sample space of the other coin.
The sample space for 3 coins is just whatever the first coin is plus the sample space of the other two coins.
etc..
Sounds like recursion!
def space(flips, n):
space(flips + "H", n-1)
space(flips + "T", n-1)
Where n is the number of coins.
The code above just runs forever and we are never printing anything so we need an exit case once we hit 0 coins.
def space(flips, n):
if n == 0:
print flips
return
space(flips + "H", n-1)
space(flips + "T", n-1)
And that's it, you call it like `space("", 3)`