79.0k views
5 votes
Unique random numbers (random module)

Given integer inputs seed, how_many, and max_num, generate a list of how_many unique random integers from 0 to max_num (inclusive).
Complete function unique_random_ints(how_many, max_num):
Generate a list of how_many random integers from 0 to max_num (inclusive).
When a random number exists in the list, a new random number must be generated; use a global variable, retries, to count the number of times an existing number is generated.
Return the list.
Complete __main__:
Initialize the random module with the seed value.
Call unique_random_ints() to get a list of random integers.
Output the list of random integers and the value of retries, according to the output format shown in the example below.
Refer to the section on the standard library to learn more about the random module and pseudo-random numbers.
Ex: If the input is:
2
5
7
the output is
0 1 5 2 4 retries=1

User Ayub Malik
by
8.1k points

1 Answer

5 votes

Final answer:

To create a list of unique random integers using Python's random module, initialize a global variable 'retries' to count duplicates, generate random numbers up to 'max_num', track uniqueness, and return the list when 'how_many' unique integers are obtained.

Step-by-step explanation:

To generate a list of unique random integers from 0 to max_num (inclusive) for a given how_many, you can use Python's random module. This task also implies the need for a retry mechanism that counts the number of times a duplicate random number is generated and suggests using a global retries variable. The function unique_random_ints() should keep generating numbers until the desired quantity of unique numbers is reached.

To initialize the random seed, you use the function random.seed(seed). To generate a random integer, you use random.randint(0, max_num). You need to keep generating these numbers and check whether they are unique by comparing them to the existing list of generated numbers. Increment the retries count each time a duplicate number is generated.

Here's how you could structure the Python code for this task:

import random
global retries
retries = 0
def unique_random_ints(how_many, max_num):
unique_numbers = set()
while len(unique_numbers) < how_many:
number = random.randint(0, max_num)
if number in unique_numbers:
retries += 1
else:
unique_numbers.add(number)
return list(unique_numbers)

# __main__
if __name__ == '__main__':
seed = int(input())
random.seed(seed)
random_numbers = unique_random_ints(5, 5)
print(' '.join(map(str, random_numbers)) + ' retries=' + str(retries))
User Brad Martsberger
by
7.9k points

No related questions found