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

Code Challenge: Dungeon-Game, Random Choices

Hi everyone,

I've been away from the Python class for a couple of months, so I'm a little rusty.

The prompt says "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."

I don't know what exactly I'm doing incorrectly. Could I please get a helpful hint on this?

Thanks!

choices.py
import random

def nchoices(n,y):
  random_items = []
  for i in range(n):
    random_items.append(random.choice(y))

  return(random_items)

#nchoices(4, [4,5,6,7])

2 Answers

Vittorio Somaschini
Vittorio Somaschini
33,371 Points

Hello Hani.

It took me a while to figure out what you wanted to do and I think this was because you just gave the iterable and the integer a single letter name.

You gotta make sure that the first parameter is the iterable and the second the is the integer.

In your code though, what you could do is swapping n and y on line 5 and 6 and it should do. This is because the range would be based on the integer, while the random.choice is based on the iterable.

Probably the fact that you gave single letter names led to confusion.

Also, probably a while loop would be simpler in this case.

Let me know if all clear.

Vittorio

Hi Vittorio. Thank you, swapping the two parameters did the job well.