Reputation: 21
while testcount < 100:
num1=randint(0,10)
num2=randint(0,10)
num3=randint(0,10)
num4=randint(0,10)
num5=randint(0,10)
numo=[num1,num2,num3,num4,num5]
if #there are two 7s# in numo:
testcount=testcount+1
num_of_successes=num_of_successes+1
else:
testcount=testcount+1
print(num_of_successes,"out of 100 there were two 7s")
How do i detect if there are two 7s in 'numo'? even if it doesn't use much of this code.
Upvotes: 2
Views: 90
Reputation: 33984
You can avoid searching the item in the list by counting on the fly without any list at all:
from random import randint
num_of_successes = 0
for testcount in xrange(100):
if sum(int(randint(0, 10) == 7) for i in xrange(5)) == 2:
num_of_successes += 1
print(num_of_successes, "out of 100 there were two 7s")
Upvotes: 1
Reputation: 1143
As I see it:
from random import randint
testcount = 0
num_of_successes = 0
while testcount < 100:
num1 = randint(0, 10)
num2 = randint(0, 10)
num3 = randint(0, 10)
num4 = randint(0, 10)
num5 = randint(0, 10)
numo = [num1, num2, num3, num4, num5]
if numo.count(7) == 2:
num_of_successes += 1
testcount += 1
print num_of_successes, "out of 100 there were two 7s"
Upvotes: 0
Reputation: 33984
for testcount in range(100):
num1=randint(0,10)
num2=randint(0,10)
num3=randint(0,10)
num4=randint(0,10)
num5=randint(0,10)
numo=[num1,num2,num3,num4,num5]
if numo.count(7) == 2:
num_of_successes=num_of_successes+1
print(num_of_successes, " out of 100 there were two 7s")
Upvotes: 0
Reputation: 4849
You can use the list.count()
method to check the occurances.
while testcount < 100:
num1=randint(0,10)
num2=randint(0,10)
num3=randint(0,10)
num4=randint(0,10)
num5=randint(0,10)
numo=[num1,num2,num3,num4,num5]
num_of_successes=numo.count(7)
if num_of_successe == 2 :
print(num_of_successes,"out of 100 there were two 7s")
Upvotes: 0
Reputation: 90889
For a list, you can use the count()
function to find out how many elements of the parameter
passed in to count function exist in the list.
Example -
>>> l = [1,2,3,4,5,6,4]
>>> l.count(4)
2
Upvotes: 5