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
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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With