In: Computer Science
Exercise Define a function that generates a random code. The functions takes in
For instance, get_code('ROYGBP',4) returns a code of 4 code pegs randomly with colors chosen from 'R'ed, 'O'range, 'Y'ellow, 'G'reen, 'B'lue, and 'P'urple. One possible outcome is 'ROYY'.
Following is my python code, and I don't know how to continue, can someone help me to finished it?
And I want to know how to random the colors code length time(s) ,such as random.choice(''ROYGBP") by code length time to get particular numbers of colors, e.g.code length is 4 and 4 random colors, code length is 2 and get 2 random colors.
Thus, the hints given that''In each iteration, generate a random (integer) position in range 0 to len(colors)-1.'', I want to ask why isn't it the range from 1 to 6?
import random
def get_code(colors, code_length):
code = ''
"""
The function body will iterate code_length times.
In each iteration, generate a random (integer) position in range 0 to len(colors)-1.
From color, get the character at that random position and append the character to code
"""
colors = 'ROYGBP'
code_length = (random.randint(1,6))
return code
Do you mean the possible outcome?
Please find below code and explanation in comments and Don't forget to give a Like.
Code:
import random def get_code(colors, code_length): code = '' #we use while loop since we want to run the function body code_length times while(code_length!=0): #taking the length of color in variable length length=len(colors)-1 #generating the randome number from 0 to length of color-1 #we are taking 0 to length-1 and not 1 to length because string index starts from 0 #string is RRBYYO if we want to get 1st letter then string[0] gives R random_num=random.randint(0,length) #string slicing getting random number from above line and appending that #letter from colors to code colors[random_num] gives letter at that postition code=code+colors[random_num] #we need to decrement code_length by 1 so that while loop run will be decreased #if we don't decrement code_length then this loop will go to infinite times code_length-=1 return code #taking input from user colors=input("Enter the colors:") #taking code_length from user code_length=int(input("Enter code length:")) print(get_code(colors,code_length))#calling function and printing code
Please refer below screenshot for indentation and output: