I've tried to make a simple function, that tosses coin n times, fifty (50) times in this example, and then stores the results to the list 'my_list
'. Tosses are thrown using the for loop
.
If the result of the tosses are not 25 heads and 25 tails (i.e 24-26 ratio), it should erase the contents of the list my_list
containing the results and loop 50 tosses again until the results are exactly 25-25.
Function:
- Print the empty list.
- Start the while-loop which only ends, if my_list.count(1) is 25.
- Toss the coin using random(1,2).
- Input results to my_list.
- If my_list.count(1) is not exactly 25, then the code should erase the contents of the list and repeat the while loop.
-- coding: latin-1 --
import random
def coin_tosser():
my_list = []
# check if there is more or less 1 (heads) in the list
# if there is more or less number ones in the list, loop
# "while". If "coin tosser" throws exactly 25 heads and
# 25 tails, then "while my_list.count(1) != 25:" turns True
while my_list.count(1) != 25: # check if there is more or less 1 (heads) in the list
print "Throwing heads and tails:"
for i in range(50):
toss = random.randint(int(1),int(2)) #tried this also without int() = (1,2)
my_list.append(toss)
if my_list.count(1) < 25 or my_list.count(1) > 25:
my_list.remove(1) # remove number ones (heads) from the list
my_list.remove(2) # remove number twos (tails) from the list
# after loop is finished (25 number ones in the list), print following:
print "Heads is in the list",
print my_list.count(1), "times."
print "Tails is in the list",
print my_list.count(2), "times."
# print
print my_list
coin_tosser()
Problem
When I try to use my_list.remove(1), it doesn't remove anything from the list. If I replace my_list.remove(1) with my_list.remove('test') and add 'test' to my_list, then the program removes 'test', if conditions is not met (as it should).
Why it doesn't remove numbers? I'm not sure if these "1" and "2" are stored to list as int
or as str
. My guess is that in str
What have I done wrong?