Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Unsure why I am getting 'try again'
In Python Collections I have the following task:
Create a function named nchoices() that takes an iterable and an integer. The function should return a list of n random items from the iterable where n is the integer. Duplicates are allowed.
def nchoices(choice_count, my_iter): random_list =  while choice_count > 0: random_list.append(random.choice(my_iter)) choice_count -= 1 return random_list
My test (using Pycharm) was to call nchoices as follows:
grid = list(range(30)) print(nchoices(5, grid))
Results appears to be within the expected set:
[6, 24, 0, 7, 20] [20, 26, 1, 19, 25] etc.
Am I misreading the question? I get no errors with executing the code but it doesn't pass the check work validation.
Thanks in advance for your help!
Haider AliPython Development Techdegree Graduate 24,724 Points
Hi Tony, there are just a couple of things wrong with your code. Firstly, the order of the arguments passed in should be the iterable then the number. Secondly, you forgot to import random. Also, the challenge asks you to pick something out of the iterable for each number in
range(the_number_you_passed_in). This can be done with the following code:
import random def nchoices(my_iter, choice_count): #you should have passed arguments in this way round random_list =  for i in range(choice_count): random_list.append(random.choice(my_iter)) return random_list
If you have any further questions, please feel free to leave a comment. :)
Hi guys, could someone please explain me, why you are using 'while' and decrease it within your for loop. Shouldn't the for loop already do its job?
Haider Ali – you are decreasing the variable in your for loop, you use as an for-loop-argument, why is that so? Shouldn't it be working with just the for-loop?
Thanks for your help
Thanks Haider for your quick reply and pointing it out, I was just confused :D and unsure what the deeper meaning of this could be.
Gianmarco Mazzoran22,052 Points
I think it's because you need a for loop in order to randomly appends items to the
Here's my code (that's ok for the challenge):
import random def nchoices(iterable, integer): rand_list =  for item in iterable: while integer > 0: rand_list.append(random.choice(item)) integer -= 1 return rand_list