简体   繁体   中英

Use Random.random [30,35] to print random numbers between 30,35. Seed(70)

Probably a simple answer, not sure what I am missing. For a homework assignment I have to use random.random() to generate numbers between 30 and 35. The seed has to be set to 70 to match the pseudo-random numbers with the grader. This wasn't in my lecture so I am a little stumped as to what to do.

I have:

import random 
def problem2_4():
    print(random.random(30,35))

But this is clearly wrong.

The assignment says the output should look like (note: for the problem i use def problem2_4() just for the assignment grading system)

problem2_4()
[34.54884618961936, 31.470395203793395, 32.297169396656095, 30.681793552717807,
 34.97530360173135, 30.773219981037737, 33.36969776732032, 32.990127772708405, 
 33.57311858494461, 32.052629620057274]

The output [blah, blah, blah] indicates that it is a list of numbers rather than a series of numbers printed one-by-one.

In addition, if you want random floating point values, you'll need to transform the numbers from random.random (which are zero to one) into that range.

That means you'll probably need something like:

import random                                # Need this module.
def problem2_4():
    random.seed(70)                          # Set initial seed.
    nums = []                                # Start with empty list.
    for _ in range(10):                      # Will add ten values.
        nums += [random.random() * 5 + 30]   # Add one value in desired range.
    print(nums)                              # Print resultant list.

Of course, the Pythonic way to do this would be:

import random
random.seed(70)
print([random.random() * 5 + 30 for _ in range(10)])

Bit that might be a bit ahead of where your educator is working. Still, it's good to learn this stuff as early as possile since you'll never be a Pythonista until you do :-)

The function that you are looking for is randint , which returns an integer (whole number) between the specified minimum and maximum values.

So the solution would be

random.randint(30, 35)

Python Docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM