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

choice.random test?

Why doesn't this pass?

choices.py
import random

def nchoices(n, t):
  num = n + 1
  times = t
  output = []
  my_range = list(range(num))
  for time in list(range(times)):
    my_random = random.choice(my_range)
    output.append(my_random)
  print (output)

nchoices(100,25)

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,064 Points

The challenge asks to pick random items from a iterable. The iterable can be any container such as a list, set, dict, string. I've updated your code to treat the "n" argument as a container.

import random

def nchoices(n, t):
  '''Return t random item from iterable n'''
  #num = n + 1
  times = t
  output = []
  #my_range = list(range(num))
  for time in list(range(times)):
    my_random = random.choice(n) #<-- choose from n instead of my_range
    output.append(my_random)
  #print (output)
  return output #<-- need to return instead of print

#nchoices(100,25) #<-- comment out.

This can be simplified. Using 'iterable' as more descriptive argument than 'n' and 'times' directly as the argument

import random

def nchoices(iterable, times):
  '''Return random items from iterable'''
  output = []
  # range returns a list
  for time in range(times):
    output.append(random.choice(iterable)) #<-- can combine steps
  return output

I guess I was close, I think I read the question wrong or the question was not clear enough. Thanks for the clarity. Also, didn't now that range() is an actual list() type object. : ) Kool.

Chris Freeman
Chris Freeman
Treehouse Moderator 68,064 Points

range is actually a range type object that behaves like a list when iterated upon. Try help(range) in the python shell.