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

Feedback for code (Random Choices challenge)?

My code feels very broken down as I was only able to understand making this function in this particular way. I feel like there is an easier way create this function. I am mostly wondering if there is a way to simplify this/shorten the code Any criticism would be appreciated!

from random import choice

def nchoices(itr, num):
  make_list = []
  choice_list = []
  for char in itr:
    make_list.append(choice(char))
  for times in range(num):
    choice_list.append(choice(make_list))
  return choice_list

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

It's unclear what make_list is for. It seems you're trying to scramble the input before selecting a random element. This is redundant. You code passes with this removed:

def nchoices(itr, num):
    # make_list = []
    choice_list = []
    # for char in itr:
    #     make_list.append(choice(char))
    # for num loops...
    for times in range(num):
        # append an element choosen at random
        choice_list.append(choice(itr))  # <-- changed to use itr
    return choice_list

An alternate solution would be to use a list comprehension:

def nchoices(itr, num):
    return [choice(itr) for times in range(num)]
from random import choice

def nchoices(itr, num):
  make_list = []
  choice_list = []
  for char in itr:
    make_list.append(char)    # Originally, I accidentally added the choice function here. Didn't mean to.
  for times in range(num):
    choice_list.append(choice(make_list))
  return choice_list

My logic for the make_list variable was to store itr in it as a list, then randomly select from make_list and then append the random choice to the choice_list.

I do now understand that I could just take that block of code out, though. This helped a lot. Thanks, Chris.