How to select a specific number of random elements from a set?

I have a set of 9 elements and I want to write a program which prompts the user for an integer n, then displays n number of elements selected randomly from my set.

This is what I tried:

import random

def main():    
    best_of = eval(input("How many maps do you want to choose? : "))

    choices = ["Arkansas", "Manchuria", "Bengal", "Baja California", "Tibet", "Indonesia", "Cascade Range", "Hudson Bay", "High Plains"]

    random_choice = random.choice(choices)

    for i in range(bes_of):    
        print(random_choice)

main()

Answer

Use the random.sample() function to pick n random elements without repetition:

sampled = random.sample(choices, best_of)
for choice in sampled:
    print(choice)

If all you need is an integer from the user, don’t use eval(); stick to using int() instead:

best_of = int(input("How many maps do you want to choose? : "))

eval() gives you more than you bargained for; it executes any valid Python expression, letting the user do anything they want with your program.

Leave a Reply

Your email address will not be published. Required fields are marked *