Gary
Gary

Reputation: 55

display how many times an element has been randomly selected from a list in Python

I would like to write a program that randomly selects an element from a list for 1000 trials after which it determines the number of times each element was selected as output.

For instance, here's some code:

import random
foo = ['rock', 'paper', 'scissors', 'lizard', 'spock']
print(random.choice(foo))

This will return a single element from 'foo' at random. I'd like to run the random selection over an iteration of, say, 1000 times, and then print out how many times each element was selected. Any help would be appreciated.

Upvotes: 2

Views: 569

Answers (2)

MikeVaughan
MikeVaughan

Reputation: 1501

import random

foo = ['rock', 'paper', 'scissors', 'lizard', 'spock']

rock = 0
paper = 0
scissors = 0
lizard = 0
spock = 0
count = 0

while count < 1000:
    choice = random.choice(foo)

    if choice == 'rock':
        rock += 1

    elif choice == 'paper':
        paper += 1

    elif choice == 'scissors':
        scissors += 1

    elif choice == 'lizard':
        lizard += 1

    elif choice == 'spock':
        spock += 1

    count +=1


print rock
print paper
print scissors
print lizard
print spock

Upvotes: 0

Lukas Graf
Lukas Graf

Reputation: 32610

Use an instance of collections.Counter to keep track of your picks:

from collections import Counter
import random

options = ['rock', 'paper', 'scissors', 'lizard', 'spock']
picks = Counter()

for i in range(1000):
    pick = random.choice(options)
    picks[pick] += 1

print picks

Example output:

Counter({'scissors': 224, 'lizard': 209, 'spock': 192, 'paper': 188, 'rock': 187})

The collections.Counter is very similar to a regular dictionary, but it assumes a default value of 0 if a key is not yet present, so you can directly create a new key and increase it with the += operation - ideal for counting.

Since it implements the dict interface, you would do

picks['rock']

to just retrieve the counts for the 'rock' choice and use it in your code.

Upvotes: 4

Related Questions