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 trialsteveovens3
2,671 PointsCollections: Code Challenge Random Choices
I am not quite sure why this is being rejected
If I do this
nchoices(['apps', 'bans', 'grapes', 'sources'], 7)
It returns something like this:
['sources', 'sources', 'apps', 'grapes', 'sources', 'bans', 'sources']
If I do this
nchoices([1,2,3,4,5,6], 7)
It returns something like this:
[6, 5, 1, 1, 6, 4, 1]
Maybe I misunderstood the point for the exercise. Can anyone help clarify?
import random
def nchoices(my_it, my_int):
list_to_return = []
counter = 0
while counter < int(my_int):
random_item = [x for x in range(0, len(my_it))]
random_item = random.choice(random_item)
list_to_return.append(my_it[random_item])
counter +=1
print(list_to_return)
2 Answers
Jason Anello
Courses Plus Student 94,610 PointsHi Steve,
If you return
the list rather than print it your code will pass.
steveovens3
2,671 Pointsderp...
hahah wow you know its time to take a break when...
Thanks
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsAlso, you're doing more work here than you need to.
It looks like you're creating a list of the valid indices for the iterable, randomly choosing an index and then accessing the item at that index.
You could instead randomly choose an item directly from the iterable passed in.
Also, you could make use of the range() function and a for loop so that you don't have to manually keep track of a loop counter.
Something like this:
The underscore in the for loop is used in place of a variable name when you have a throwaway variable that you don't need to use.