Displaying certain values in Python

Asked

Viewed 53 times

2

I need help with the following:

  • I have a variable that generates random integer numbers from (0 to 400).
  • In a given number of executions, I wish(m) to be displayed(s) the value(s) and the position(s) of the value(s) less(s) than 100.
  • I have a code (see below) that I am working on, but it is not acting properly.

Where am I going wrong?

My code

from random import randint

aleatorio = randint(0,400)
maximo = 100
for i in range(1,maximo + 1):
    if aleatorio < 100:
        print (aleatorio[i])
  • All in all how many executions do you want? You weren’t clear on that

1 answer

3


The best way is to use a dictionary, in which each key can be the position of the corresponding value less than 100:

from random import randint

pos = {}
for idx, val in enumerate(range(400)):
    rand_num = randint(0, 400)
    if rand_num < 100:
        pos[idx] = rand_num

DEMONSTRATION

  • Thank you very much friend. It’s exactly what I need.

  • You’re welcome to @Danilo. You can trade if you want, instead of having the key position it can be the value. pos[val] = idx, or in the second example: {val: idx for idx, val in enumerate(rand_nums) if val < 100}

  • @Danilo, I’m sorry but I made a huge mistake here... The problem with the first method (http://ideone.com/d5o068) is that it did not generate repeated numbers, that is, 400 numbers were generated all different (0-400) in the same, and I don’t think that’s what you want. I edited for the right way

Browser other questions tagged

You are not signed in. Login or sign up in order to post.