Skip to content Skip to sidebar Skip to footer

Printing Out A Random String (python)

I am asked to produce a random string using a previously defined value. THREE_CHOICES = 'ABC' FOUR_CHOICES = 'ABCD' FIVE_CHOICES = 'ABCDE' import random def generate_answers(n: i

Solution 1:

you could just return a list like this:

defgenerate_answers(n):
    '''Generates random answers from number inputted '''
    randoms = [random.choice(FOUR_CHOICES) for _ inrange(0,n)]
    return randoms
    #return ''.join(randoms) to get stringprint generate_answers(7)  

this would print a list like this: ['D', 'D', 'D', 'B', 'A', 'A', 'C']

you could join the list if you want a string

Solution 2:

not tested, but should work.

THREE_CHOICES = 'ABC'
FOUR_CHOICES = 'ABCD'
FIVE_CHOICES = 'ABCDE'import random

defgenerate_answers(n):
    '''Generates random answers from number inputted '''
    answerList = ""for i inrange(0,n):
        answerList += random.choice(FOUR_CHOICES)
    return answerList

Post a Comment for "Printing Out A Random String (python)"