Reputation: 75
Suppose I repeatedly generate random integers from 0-9 until a given number comes out. What I need is a function that counts how many integers are generated until this happens. Please help me with this.
This is what I have tried, I put 1000 becasue it is big enough but I don't think it is correct because my number can come after 1000 iterations.
for i in range(1000):
d = randint()
if d <> 5:
cnt = cnt + 1
if d == 5:
break
Upvotes: 4
Views: 6688
Reputation: 40973
Suppose 5 is the number you are expecting:
sum(1 for _ in iter(lambda: randint(0, 9), 5))
You can add 1 if you want to include the last number.
Explanation:
iter(function, val)
returns an iterator that calls function
until
val
is returned.lambda: randint(0, 9)
is function (can be called) that returns randint(0, 9)
.sum(1 for _ in iterator)
calculates the length of an iterator.Upvotes: 10
Reputation: 304235
itertools.count
is often neater than using a while loop with an explicit counter
import random, itertools
for count in itertools.count():
if random.randint(0, 9) == 5:
break
If you want the count to include the iteration that generates 5, just start the count at 1 using itertools.count(1)
Upvotes: 2
Reputation: 11686
from random import randint
count = 0
while randint(0, 9) != 5:
count += 1
Upvotes: 1
Reputation: 298246
A few things:
while
loop instead of a for
loop.!=
as the inequality operator instead of <>
.Here's something to get you started:
import random
count = 0
while True:
n = random.randint(0, 9)
count += 1
if n == 5:
break
You could also write:
import random
count = 1
n = random.randint(0, 9)
while n != 5:
count += 1
n = random.randint(0, 9)
Converting it into a function is left as an exercise for the reader.
Upvotes: 9
Reputation:
This should work:
from random import randint
# Make sure 'cnt' is outside the loop (otherwise it will be overwritten each iteration)
cnt = 0
# Use a while loop for continuous iteration
while True:
# Python uses '!=' for "not equal", not '<>'
if randint(0, 9) != 5:
# You can use '+=' to increment a variable by an amount
# It's a lot cleaner than 'cnt = cnt + 1'
cnt += 1
else:
break
print cnt
or, in function form:
from random import randint
def func():
cnt = 0
while True:
if randint(0, 9) != 5:
cnt += 1
else:
break
return cnt
Upvotes: 0