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

steveovens3
steveovens3
2,671 Points

Collections: 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?

choices.py
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

Hi Steve,

If you return the list rather than print it your code will pass.

Also, 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:

import random

def nchoices(iter1, num):
  choices = []
  for _ in range(num):
    choices.append(random.choice(iter1))
  return choices

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.

steveovens3
steveovens3
2,671 Points

derp...

hahah wow you know its time to take a break when...

Thanks