Home > OS >  Function that returns a list consisting of 40 random letters from (A-F)
Function that returns a list consisting of 40 random letters from (A-F)

Time:10-19

I need to create a function called random_grades that returns a list consisting of 40 random letters from (A-F). This is the code so far.. but i dont know how to make the output letters and not numbers...

import random 
random_grades = [random.randint(5,10) for i in range (40)]

A = 10

B = 9

C = 8

D = 7

E = 6

F = 5

print(random_grades)

CodePudding user response:

random.choices does it directly:

random.seed(0)  # make it reproducible
random.choices('ABCDEF', k=40)

give:

['F', 'E', 'C', 'B', 'D', 'C', 'E', 'B', 'C', 'D', 'F', 'D', 'B', 'E', 'D', 'B', 'F', 'F', 'E', 'F', 'B', 'E', 'F', 'E', 'C', 'A', 'C', 'D', 'F', 'F', 'C', 'F', 'B', 'E', 'D', 'A', 'E', 'C', 'E', 'E']

This works because a string is an iterable of characters...

CodePudding user response:

You can use a map index -> grade aka an array, and the random variable is the index.

import random

grades = ['A','B','C','D','E','F']
 
random_grades_indexes = [random.randint(0,len(grades)-1) for i in range (40)]
random_grades = [ grades[i] for i in random_grades_indexes]

print(random_grades)

Which prints

['D', 'A', 'A', 'B', 'D', 'E', 'A', 'E', 'D', 'E', 'B', 'A', 'A', 'B', 'D', 'B', 'E', 'A', 'F', 'B', 'B', 'D', 'C', 'F', 'E', 'B', 'A', 'B', 'C', 'E', 'E', 'C', 'F', 'D', 'A', 'F', 'B', 'C', 'B', 'E']

As a proof that you will get a uniform distribution, we can create an histogram of the grades running 1000 grades.

import random

def count_elements(seq) -> dict:
    hist = {}
    for i in seq:
        hist[i] = hist.get(i, 0)   1
    return hist

grades = ['A','B','C','D','E','F']
 
random_grades_indexes = [random.randint(0,len(grades)-1) for i in range (1000)]
random_grades = [ grades[i] for i in random_grades_indexes]

dist = count_elements(random_grades)
print(dist)

Which gives

{'C': 175, 'F': 153, 'A': 153, 'E': 174, 'D': 174, 'B': 171}
  • Related