Sharedc19.sagewsOpen in CoCalc
3+4

7
def coin_flip():
if random() < .5:
return "H"
else:
return "T"

def coin_flips(n):
flip_results = []
for i in [1..n]:
flip_results.append(coin_flip())
return flip_results

flip_results = coin_flips(n)
for i in flip_results:
if i == "H":

def longest_run_of_heads(n):
flip_results = coin_flips(n)
print flip_results
count = 0
longest = 0
for i in [0..(n-1)]:
if flip_results[i] == "H":
count = count+1
if count > longest:
longest = count
else:
count = 0
return longest

longest_run_of_heads(10)

['H', 'T', 'H', 'H', 'T', 'H', 'T', 'T', 'T', 'T'] 2
longest_run_of_heads(10)

['T', 'T', 'T', 'T', 'H', 'T', 'T', 'T', 'H', 'H'] 2
longest_run_of_heads(10)

['H', 'H', 'H', 'T', 'T', 'T', 'T', 'H', 'T', 'H'] 3
longest_run_of_heads(10)

['T', 'H', 'H', 'T', 'T', 'H', 'H', 'T', 'T', 'T'] 2
longest_run_of_heads(10)

['H', 'H', 'T', 'H', 'T', 'H', 'H', 'T', 'H', 'H'] 2
longest_run_of_heads(10)

['T', 'T', 'T', 'H', 'H', 'T', 'T', 'H', 'T', 'H'] 2
longest_run_of_heads(10)

['H', 'H', 'T', 'T', 'H', 'T', 'H', 'H', 'H', 'H'] 4