Define a function named q1() that accepts one integer (n) as a parameter and use
ID: 3828083 • Letter: D
Question
Define a function named q1() that accepts one integer (n) as a parameter and uses List comprehension to create and return a List containing a sequence of n randomly selected characters. You may use any variable names you need, but the q1() function should return the List - nothing should be printed. The characters should be either 'A', 'B' or 'C' based on the following parameters: bullet An 'A' is three (3) times more likely to be added to the List than a 'B' bullet A 'B' is twice (2 times) as likely to occur than a 'C' This means that there may not be numerically 3 times more 'A' characters than 'B's, but the algorithm is 3 times more likely to add an 'A' than a 'B' and twice as likely to add a 'B' than a 'C'. Example output of the function q1() at the interactive Python prompt: >>> q1(6) ['B', 'A', 'B', 'A', 'A', 'C'] >>> q1(10) ['B', 'C', 'A', 'A', 'B', 'A', 'A', 'A', 'B', 'A']Explanation / Answer
from random import randint
def q1(n):
randchar = ['A']*6
randchar.append('B')
randchar.append('B')
randchar.append('C')
result = [randchar[randint(0, 8)] for i in range(0, n)]
return result
print(q1(6))
print(q1(10))
# code link: https://paste.ee/p/nzLYE
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.