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 trialJames Whiting
39,124 Pointschoice.random test?
Why doesn't this pass?
import random
def nchoices(n, t):
num = n + 1
times = t
output = []
my_range = list(range(num))
for time in list(range(times)):
my_random = random.choice(my_range)
output.append(my_random)
print (output)
nchoices(100,25)
2 Answers
Chris Freeman
Treehouse Moderator 68,457 PointsThe challenge asks to pick random items from a iterable. The iterable can be any container such as a list, set, dict, string. I've updated your code to treat the "n" argument as a container.
import random
def nchoices(n, t):
'''Return t random item from iterable n'''
#num = n + 1
times = t
output = []
#my_range = list(range(num))
for time in list(range(times)):
my_random = random.choice(n) #<-- choose from n instead of my_range
output.append(my_random)
#print (output)
return output #<-- need to return instead of print
#nchoices(100,25) #<-- comment out.
This can be simplified. Using 'iterable' as more descriptive argument than 'n' and 'times' directly as the argument
import random
def nchoices(iterable, times):
'''Return random items from iterable'''
output = []
# range returns a list
for time in range(times):
output.append(random.choice(iterable)) #<-- can combine steps
return output
James Whiting
39,124 PointsI guess I was close, I think I read the question wrong or the question was not clear enough. Thanks for the clarity. Also, didn't now that range() is an actual list() type object. : ) Kool.
Chris Freeman
Treehouse Moderator 68,457 Pointsrange
is actually a range
type object that behaves like a list when iterated upon. Try help(range)
in the python shell.