Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting random numbers

Tags:

python

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
like image 539
John Avatar asked Nov 30 '22 01:11

John


2 Answers

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.
like image 151
elyase Avatar answered Dec 10 '22 16:12

elyase


A few things:

  • If you want your loop to continue until you stop it, use a while loop instead of a for loop.
  • You should use != 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.

like image 40
Blender Avatar answered Dec 10 '22 15:12

Blender