Read a single integer from the keyboard. Assume this integer represents the numb
ID: 3807011 • Letter: R
Question
Read a single integer from the keyboard. Assume this integer represents the number of times you want to flip a coin (with two sides: “H” and “T” for “heads” and “tails” respectively). Show all possible outcomes of “H” and “T” for flipping the coin this many times. You must use recursion for this problem. You may not use any loops (or goto) to solve this. Example 1 (user input is underlined): Coin flips? 1 T H Example 2 (user input is underlined): Coin flips? 2 TT TH HT HH Example 3 (user input is underlined): Coin flips? 3 TTT TTH THT THH HTT HTH HHT HHH
Explanation / Answer
import sys,math
list_comb=[]
def print_coin_flips(flip_comb,length,list_comb=list_comb):
if(flip_comb<0):
return
bin_comb=bin(flip_comb)[2:]
length_bin_output=len(bin_comb)
len_dif=length-length_bin_output
if(len_dif!=0):
while(len_dif!=0):
bin_comb='0'+bin_comb
len_dif=len_dif-1
list_comb.append(bin_comb)
print_coin_flips(flip_comb-1, length,list_comb)
p=raw_input('Coin flips?')
p=int(p)
print_coin_flips(int(math.pow(2,p))-1,p,list_comb)
for i in list_comb:
i=i.replace('1','T')
i=i.replace('0','F')
print i
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.