Search code examples
pythonlistrandomcoin-flipping

How can I get a list with m tails? Python


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?


Solution

  • 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