Python Python Basics (2015) Letter Game App Random Item

Ryan Felton
Ryan Felton
Python Web Development Techdegree Student 1,305 Points

not sure what to do

help

item.py
import random 
def random_item(sample):
    random_item=random.randint(0,len(sample)-1)
    return sample

1 Answer

Jeffrey James
Jeffrey James
2,635 Points

You're returning the function argument:

import random 
def random_item(sample):
    random_item=random.randint(0,len(sample)-1)
    return random_item

Try something like returning "random_item", which is the variable you likely intended to return.

>>> import random 
>>> def random_item(sample):
...     random_item=random.randint(0,len(sample)-1)
...     return random_item
... 
>>> random_item([1,3,44,90])
3
>>> [random_item([1,3,44,90]) for x in range(100)]
[0, 2, 0, 2, 3, 1, 2, 0, 3, 1, 2, 0, 3, 2, 3, 2, 0, 1, 0, 1, 3, 0, 1, 0, 3, 3, 3, 1, 2, 1, 1, 2, 2, 0, 3, 0, 0, 3, 1, 0, 3, 3, 1, 3, 3, 0, 3, 3, 0, 1, 0, 3, 2, 2, 1, 1, 3, 1, 2, 3, 2, 3, 0, 3, 1, 0, 2, 2, 0, 2, 0, 3, 1, 0, 3, 1, 3, 3, 3, 0, 3, 0, 2, 0, 1, 1, 1, 3, 3, 0, 2, 3, 1, 0, 3, 3, 0, 0, 0, 2]
Jeffrey James
Jeffrey James
2,635 Points

Also, based on the func you wrote, I would imagine you want to return a random element from the input list? You're just choosing a random integer based on the length of the input array. Try using another method from the random module

>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_acos', '_ceil', '_cos', '_e', '_exp', '_inst', '_log', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']