Given colour = [ “red”, “blue”, “green”, “yellow”, “purple”, “orange”, “white”, “black” ]
generate and print a list of 50 random colours. You will need to use the random module to get random numbers. Use range and map to generated the required amount of numbers. Then use map to translate numbers to colours. Print the result.
This is a question i’ve been given and here’s my code so far
colour = [ "red", "blue", "green", "yellow", "purple", "orange", "white", "black" ]
number=random.randint(1,9)
number.range(50)
i’m assuming this has made a variable that picks random numbers between 1-9, and then makes 50 of them ? i now need some way of linking the numbers to the colours.. i know this question is quite vague but if anyone could point me in the right direction, that would be awesome !
For some reason, your question requires use of
map. It is difficult to help with this question without giving the answer directly, especially because these kinds of manipulations are one-liners. To start, using map and range to get a list of random numbers in the required range:Observe that the argument to lambda,
xis not used. That is at least one reason why I wouldn’t use map here. Then, using the list of numbers, map the indexing function onto the numbers to obtain the list of colours:The answer given by soulcheck, using
random.choice()in a list comprehension, is by far the best way of determining the answer.