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

Jamie Evans
Jamie Evans
2,092 Points

nchoices, I passed but not happy with my answer, is there a better way?

Hello all

I have passed the challenge, but i am not happy that this is a good way of doing it. if someone could please show me a better more efficient way of doing it. Don't think its very python like.

choices.py
import random

def nchoices(lst1, int1):
  count = 0
  new_list = []
  for item in lst1:
    if count < 5:
      new_list.append(random.choice(item))
      count+=1
    else:
      break
  return new_list
Jamie Evans
Jamie Evans
2,092 Points

I tried doing while count < 5: instead of if, but "code took too long to run" for some reason:)

2 Answers

Michael Parthum
Michael Parthum
1,468 Points

Below is what I passed with. This is as simple as I was able to break it down to.

import random

def nchoices(supplied_list, n):
  count = 0
  random_list = []
  while count < n:
    random_list.append(random.choice(supplied_list))
    count += 1
  return random_list
anhedonicblonde
anhedonicblonde
3,133 Points

Awesome, that makes sense to me! thanks much for posting your code! :)

Mike Tribe
Mike Tribe
3,827 Points

Same

import random

def nchoices(itr, intgr):
  randList = []
  count = 0
  while count < intgr:
    randList.append(random.choice(itr))
    count += 1
  return randList
Jamie Evans
Jamie Evans
2,092 Points

Turns out I completely got the wrong end of the what the challenge was meant to be. It was supposed to give the random.choice for the number in the integer:)

import random

def nchoices(lst1, int1):
  count = 0
  new_list = []
  for item in lst1:
    if count < int1:
      new_list.append(random.choice(item))
      count+=1
    else:
      break
  return new_list
anhedonicblonde
anhedonicblonde
3,133 Points

I'm completely lost with this one. Can someone explain this to me? I had no idea how to do this challenge and I still don't really get it. Thanks in advance.