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 trialFrank Sherlotti
Courses Plus Student 1,952 PointsRandom choices challenge. Need a little bit of help please.
I think i'm doing this correctly but I can't make it stop at the n integer. If someone would point me in the right direction that would be greatly appreciated! THANKS (: !
def nchoices(things, n):
new_list = []
import random
for item in things:
random.choice(things)
new_list.append(things)
# if things == len(n):
# This is the closest way I could think of making it stop at the n integer.
# But it doesn't seem to work and i'm confused.
return new_list
4 Answers
Tony Gibbons
1,573 PointsWow this has taken me the best part of an evening to work out! Thanks Frank your code gave me something to work from, I had been going in all sorts of crazy directions. I think the biggest thing we had been missing was a while loop.
import random
def nchoices(things, n):
new_list = []
for item in things:
while n > 0:
nl = random.choice(things)
new_list.append(nl)
n -=1
return new_list
Logan R
22,989 Points-- Nevermind, lol --
Frank Sherlotti
Courses Plus Student 1,952 PointsI've now come up with this. Which is giving me 26 results instead of the needed 5. All I need to do is figure out how to stop it at the 'n' integer and it should be good. Still have made no progress on that front lol.
def nchoices(things, n):
new_list = []
import random
for item in things:
random.choice(item)
new_list = things
return new_list
Arvin Dwarka
5,499 PointsI don't think you need a for loop here; a while loop will do the trick.
import random
def nchoices(iterable_1, integer):
new_list = []
while integer > 0:
new_list.append(random.choices(interable_1))
integer -= 1
return new_list
Also, I've found it to be best practices to do all imports at the very beginning of your code :)
Frank Sherlotti
Courses Plus Student 1,952 PointsFrank Sherlotti
Courses Plus Student 1,952 PointsThanks for the help it's greatly appreciated!