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

FHATUWANI Dondry MUVHANGO
FHATUWANI Dondry MUVHANGO
17,796 Points

problems with choices.py

it says that: "expected 5 items, got 26". now how in the world im a giving it 26 items?????

choices.py
import random

def nchoices(iterable, integer):
    my_list = []
    integer = 0
    for item in iterable:
        my_list.append(random.choice(item))
    integer += 1
    return my_list

2 Answers

Ryan S
Ryan S
27,276 Points

Hi Fhatuwani,

The challenge is basically testing your code with a list of 26 items, and an integer of 5. So it will expect you to return a list of 5 random items. The reason you are getting 26 items is that you are essentially looping through the entire "iterable" and rebuilding a copy of the list.

The first reason for this is that you are using random.choice(item) instead of random.choice(iterable). "item" is not an iterable in this case, it is a single member of a list so you are trying to randomize a single item every pass of the loop.

Second, you have immediately reset the "integer" argument to zero, The "integer" will be defined when taken in as the function argument so immediately setting it to zero defeats the purpose of having it as an argument. Also you are incrementing it by 1 outside of the loop. So after the loop ends it will simply equal 1 and hasn't been utilized in any other way. If you want to count or limit loops using this method, you will need to make sure the increment/decrement statement is inside the loop. But that being said, the challenge requires a different approach.

The third thing is that you are using a for loop that ends when it reaches the end of the iterable, so in this case you will run through it 26 times. Instead of a for loop, try a while loop that ends after "integer" counts down to zero (or becomes False). And in the while loop, append my_list as you are doing, but with "iterable" instead of item.

import random

def nchoices(iterable, integer):
    my_list = []
    while integer != 0:
        my_list.append(random.choice(iterable))
        integer -= 1
    return my_list

Hope this clears things up.

FHATUWANI Dondry MUVHANGO
FHATUWANI Dondry MUVHANGO
17,796 Points

yeaaah what a mouth full Ryan. thanks for your efforts, and i do get it now.

THANK YOU SO MUCH!!!!