Oscar ChongPro Student 292 Points
pls help me out
Here is the question:
First, import the random library.
Then create a function named random_item that takes a single argument, an iterable. Then use random.randint() to get a random number between 0 and the length of the iterable, minus one. Return the iterable member that's at your random number's index.
Check the file for an example.
Can you tell me how to solve it with steps? Thanks
# EXAMPLE # random_item("Treehouse") # The randomly selected number is 4. # The return value would be "h" import random def random_item(xyz): random.randint(0,3)
Stuart Wright41,071 Points
There are a few steps to get to the correct solution here - hopefully this leads you in the right direction:
- Find the length of the iterable passed into the function (xyz as you have called it). You can do this using len(xyz).
- You need to subtract 1 from this number, then pass that number to randint() in place of the 3 that you currently have hardcoded in to your solution.
- Once you have this random number, you need to return the item at that index in the iterable you passed in. You can do that using square brackets.
# EXAMPLE # random_item("Treehouse") # The randomly selected number is 4. # The return value would be "h" import random def random_item(iterable): index = random.randint(0, len(iterable) - 1) return iterable[index]