Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (Retired) Dungeon Game Random Choices

Renato Ribeiro
Renato Ribeiro
4,821 Points

I don't understand the question. Can you give me an example? (input/output)

"Create a function that returns a list of random items from an iterable. The function, named nchoices(), should take an iterable and an integer for the number of items to return. Duplicates are allowed." It's not clear for me. I wrote a code below but it's wrong ;-(

choices.py
import random

def nchoices(arg1, arg2):
    list1 = []
    for item in range(arg2):
        list1.append([item, random.choice(arg1)])

    return list1


nchoices(['a', 'b', 'c', 'd'], 4)

Firstly, the list that you're currently returning includes the choice number/index and the choice. The prompt just asks for a list of the random items, so it should be changed to:

list1.append(random.choice(arg1))

However, this line is not enough! The prompt also asks you to make sure that you don't return a list with repeated values. So, we have to make sure this doesn't happen by adding a pop() to that line in the code. We'll get the random choice, then pop the value from the original list (we need to provide an index to pop) and append that to our list:

list1.append(arg1.pop(arg1.index(random.choice(arg1))))

Replacing this within your for loop will solve your problem prompt.

(Another solution is to first store the random.choice(arg1) in a variable, say choice, then call arg1.remove(choice))

1 Answer

Joshua Ferdaszewski
Joshua Ferdaszewski
12,716 Points

You are returning a list of lists, not a list of items. That sounded confusing, so here is an example. When I ran your code above, nchoices() returned this: [[0, 'b'], [1, 'a'], [2, 'd'], [3, 'a']] not what the spec asks for. You probably intended to return this ['b', 'a', 'd', 'a']

Take a close look at this line in your code:

list1.append([item, random.choice(arg1)])

Change what you are appending to list1 and your code should work as intended. I hope that helps guide you to the correct answer without just giving it to you. Let me know if you have any other questions and good luck learning Python!

Renato Ribeiro
Renato Ribeiro
4,821 Points

list1.append(random.choice(arg1))

Yes, it works!!! My English isn't very well. Thank you very much.