Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (Retired) Dungeon Game Random Choices

Alexander Hansson
Alexander Hansson
2,083 Points

Is there any better way than this?

I see that my code works but I failed the assignment. Could someone please provide with other possible examples for completing this task with some explanations? Thank you.

choices.py
import random

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

nchoices("hej",3)

2 Answers

Vittorio Somaschini
Vittorio Somaschini
33,371 Points

Hello Alexandre.

I think that is pretty neat.

Maybe this could be a good solution too?

import random

def nchoices(iterable, integer):
    new_list = []
    for number in range(0, integer):
        new_list.append(random.choice(iterable))
    return new_list

Vitto

Steven Parker
Steven Parker
218,860 Points

:point_right: You don't need to call your function, the challenge does that for you.

But otherwise, you code solves the challenge. I tried cut-and-paste directly into the challenge and it passed.

Good job! :+1:

Alexander Hansson
Alexander Hansson
2,083 Points

Oh, thanks. =) But are there any other possible neat solutions that you could explain? That would be awesome since I tried to improve the code but didn't manage come up with an alternative solution.