Home > database >  Creating a list of random numbers shorter than specified 'count' between [0,1) greater tha
Creating a list of random numbers shorter than specified 'count' between [0,1) greater tha

Time:01-20

I am just starting in Python (though have coding experience in other languages) and am working on this assignment for a class in ArcGIS pro. We have been tasked with using the random module to generate a list of random numbers between 0 and 1 with a few different 'cutoffs' (shown here 0.7) and 'counts' shown here 5.

I have tried a few different ways of approaching this problem including using nested loops (shown below, different count and cutoff) but came out with a list too long. I am now trying to approach the problem using only a while loop after some guidance from my professor, yet my list remains... empty? Any help is appreciated.

(https://i.stack.imgur.com/6bNdX.png)

(https://i.stack.imgur.com/QEydA.png)

CodePudding user response:

You have the right idea, just some bugs in your code. The first one, your x is just counting from 0 to count and that's what you are appending to your list of numbers rather than the random.random() output. Also, you didn't assign any value to your random.random() output either.

The second example is much closer to what you're looking for, but you are missing a colon after the if statement and the numbers.append(x) should be indented.

import random
seed = 37
cutoff = 0.4
count = 8

random.seed(seed)

numbers = []
while len(numbers) < count:
    x = random.random()
    if x > cutoff:
        numbers.append(x)
        
print(numbers)

CodePudding user response:

Consistent with the suggestion by @Tim to use random.uniform(), here is a complete solution that builds on his guidance:

import random

count, cutoff, seed = 10, 0.4, 37

random.seed(seed)

numbers = [
    random.uniform(cutoff, 1.0)
    for _ in range(count)
]
print(numbers)

Output:

[0.8092027363527867, 0.45496156484773836, 0.7706898093168415, 0.9051519427305738, 0.9007301731456538, 0.7090106354748096, 0.778622779177406, 0.6215379004377511, 0.7168111732115348, 0.46471400998163914]
  • Related