How can I get a list with m tails? Python

340 views Asked by At

So I need to create a list with m tails. The elements of the list will be a random choice between tail and head. I did like :

Def S(m):
    list=[]
    counter=0
    signs=["head","tail"]
    while counter<(m):
        list.append(random.choice(signs))
        for k in list:
            if k=="tail":
               counter+=1
    print(list)

So this one gives me a list but not with m tails. I think the while is wrong here but I am not sure how to write the code. Can you help me to change it?

2

There are 2 answers

0
hiro protagonist On BEST ANSWER

this will work:

from random import choice

def S(m):
    lst = []
    counter = 0
    signs = ["head", "tail"]
    while counter < m:
        toss = choice(signs)
        lst.append(toss)
        if toss == 'tail':
            counter += 1
    return lst

lst = S(10)
print(lst)                # ['head', 'tail', 'head', 'head', 'tail', ...]
print(lst.count('tail'))  # 10
0
Seraph Wedd On

If you want you own code to work, you can just add:

counter = 0

After the while condition. The mistake in you code is the increment of count. What it does is for one loop, it counts all tails on your list and adds that to counter, then, like a snowball effect, the SAME tails were counted and added AGAIN for every succeeding loops.

This correction is a bit inefficient though as you will always clear the value of count, then count again from the start. If your list reaches large index values, it may slow down your code.

Good luck!