Ovi
Ovi

Reputation: 573

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()

Upvotes: 0

Views: 84

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1125398

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.

Upvotes: 3

ZdaR
ZdaR

Reputation: 22974

You neeed to call the random.choice() method inside the for loop so that n random elements are printed.

import random

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

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

    for i in range(int(best_of)):    
        random_choice = random.choice(choices)
        print(random_choice)

main()

Upvotes: 1

Related Questions