Hi,

I am trying to generate a list of random numbers where each number in the list is a individual string. This is my code so far:

import random

def make_secret(numdigits):
    a=[]
    secret = random.sample(range(0, 10), numdigits)
    for i in secret:
        a.append(str(secret))
    return a

An example of what i'm trying to output is .
However my code is doing something else entirely.

Any help would be appreiciated as I know this is a simple solution

Thanks

Typecasting the numbers to a string doesn't make much sense to me, but whatever.

You are mistakenly using the sample function.

Here's what you want to do.

import random

def make_secret(numdigits):
    a = []
    for i in range(numdigits):
        a.append(str(random.randrange(0, 10)))
    return a

Thankyou so much, the reason I'm doing it is because I'm trying to compare these numbers to another string. Thanks a lot

There are possible to use sample,can write something compact like this.

>>> from random import sample
>>> map(str,(sample(xrange(10),4)))
['1', '6', '2', '9']
>>>

It depends on whether or not rexona wants the elements of the list to be unique or if each number should be chosen randomly over the whole range.

Sample takes unique elements from the given population. Example: For range 10 and the number of elements taken being 4 the list could be this '[1, 5, 0, 8]' but it could never be this '[2, 2, 6, 3]'.

Edited 6 Years Ago by lrh9: n/a

It depends on whether or not rexona wants the elements of the list to be unique or if each number should be chosen randomly over the whole range.

Yes you are right,i think maybe randrange is more correct.
I dont see rexona mention unique elements,so maybe he ment to use randrange in first script.
Just some fun with a one liner.

>>> map(str,[randrange(0,10) for i in range(4)])
['9', '0', '1', '1']
>>>

Edited 6 Years Ago by snippsat: n/a

Sorry if i forgot to clarify, but yes each element is unique, as in i don't want any repeats, therefore I think probably sample is more accurate? But once i try and use sample again it takes the string of the entire list

Edited 6 Years Ago by rexona: n/a

But once i try and use sample again it takes the string of the entire list

import random

def make_secret(numdigits):
    return map(str,(random.sample(xrange(10),numdigits)))

print make_secret(4)
#-->['4', '7', '0', '1'] #output elements will alway be unique

Edited 6 Years Ago by snippsat: n/a

This question has already been answered. Start a new discussion instead.