Question

In: Computer Science

Exercise Define a function that generates a random code. The functions takes in a string colors...

Exercise Define a function that generates a random code. The functions takes in

  • a string colors whose characters represent distinct colors to choose from, and
  • a positive integer code_length representing the length of the code.

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?

Solutions

Expert Solution

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:


Related Solutions

python 3 please Define a function voweliest that takes as input a string and returns as...
python 3 please Define a function voweliest that takes as input a string and returns as output a tuple where the string that has the most vowels in it is the first element and the second is the number of vowels in that string. Note: don't worry about ties or capital letters Hint: consider defining and using a separate function that counts the number of vowels in a given string
Write a function that counts the colors in a string using JavaScript. String "The quick brown...
Write a function that counts the colors in a string using JavaScript. String "The quick brown fox jumped the blue fence and landed on red paint." This should return the number of colors. The colors you are looking for are "blue, green, brown, gray, black, brown, red, purple".
C++ Write a function called gen_dates() that generates random dates. It takes two arrays of integers...
C++ Write a function called gen_dates() that generates random dates. It takes two arrays of integers called months and days to store the month and day of each date generated, a constant array of 12 integers called num_of_days that specify the number of days of each of the 12 months and an integer called size that specifies how many dates to generate and randomly generates size dates, storing the generated months in months array and generated days in days array....
Define a function file_to_hist() which takes a string representing a filename, opens the file, reads its...
Define a function file_to_hist() which takes a string representing a filename, opens the file, reads its contents, closes the file,* and returns a histogram based on the letter frequencies in the given file. If no such file exists, your function should return an empty histogram (i.e., an empty dictionary {}). So for example, if the file nash.txt was in the same directory as char_hist3.py and had the following contents: I have never seen a purple cow, And I never hope...
import random # define functions def rollDice(): # function returns a random number between 1 and...
import random # define functions def rollDice(): # function returns a random number between 1 and 6 def userWon(t1, t2): # function accepts player total and computer total # function returns true if player wins # function returns false if computer wins def main(): # each player rolls two Dice player = rollDice() + rollDice() computer = rollDice() + rollDice() # ask the player if they want to roll again again = int(input("Please enter 1 to roll again. Enter 2...
---------------- Exercise 2: String Permutations ---------------- Create a program that takes a string from the command...
---------------- Exercise 2: String Permutations ---------------- Create a program that takes a string from the command line and prints every permutation of that string. You may assume the string will contain all unique characters. You may print the permutations in any order, as long as you print them all. ---------------- Output: ---------------- $>./prog dog d do dog dg dgo o od odg og ogd g gd gdo go god ---------------- I need help on this exercise that requires recursion only....
---------------- Exercise 2: String Permutations ---------------- Create a program that takes a string from the command...
---------------- Exercise 2: String Permutations ---------------- Create a program that takes a string from the command line and prints every permutation of that string. You may assume the string will contain all unique characters. You may print the permutations in any order, as long as you print them all. ---------------- Output: ---------------- $>./prog dog d do dog dg dgo o od odg og ogd g gd gdo go god ---------------- I have no idea on coding this. The files I...
Write a function that takes a C string as an input parameter and reverses the string.
in c++ Write a function that takes a C string as an input parameter and reverses the string. The function should use two pointers, front and rear. The front pointer should initially reference the first character in the string, and the rear pointer should initially reference the last character in the string. Reverse the string by swapping the characters referenced by front and rear, then increment front to point to the next character and decrement rear to point to the...
Please convert this code written in Python to Java: import string import random #function to add...
Please convert this code written in Python to Java: import string import random #function to add letters def add_letters(number,phrase):    #variable to store encoded word    encode = ""       #for each letter in phrase    for s in phrase:        #adding each letter to encode        encode = encode + s        for i in range(number):            #adding specified number of random letters adding to encode            encode = encode +...
Write a Python function that takes a list of string as arguments. When the function is...
Write a Python function that takes a list of string as arguments. When the function is called it should ask the user to make a selection from the options listed in the given list. The it should get input from the user. Place " >" in front of user input. if the user doesn't input one of the given choices, then the program should repeatedly ask the user to pick from the list. Finally, the function should return the word...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT