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.
-- 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()
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?
As @poke stated, list.remove(x)
only removes the first appearance of x
in list
. I would simply use a new my_list
list in every iteration and get rid of the entire if
inside the loop.
while my_list.count(1) != 25: # check if there is more or less 1 (heads) in the list
print "Throwing heads and tails:"
my_list = []
for i in range(50):
toss = random.randint(int(1),int(2)) #tried this also without int() = (1,2)
my_list.append(toss)
You don't need to check again if you have 25 heads inside the loop because you are just checking it in the loop condition while my_list.count(1) != 25
BTW:
my_list.count(1) < 25 or my_list.count(1) > 25
is the same as your while
condition but less readable.