bapors
bapors

Reputation: 909

How to have a list of random numbers by ensuring all of them at least once used?

I am trying to have a list of numbers from 1 to 10 with many occurrences, therefore I began with using the following code:

list(range(1,11))

However, it only gives every number only once. I need to have an output in double size, half of it having the arbitrarily ordered numbers and half should have random numbers in the given range like following:

[1,2,3,4,5,6,7,8,9,10,3,4,2,7,5,7,5,2,8,9]

My approach was:

1) Making a random list

a = random.randint(0,9)

2) Combining with the output of range

b = list(range(1,11))
result = a+b

Is it possible to have it in other way?

Upvotes: 3

Views: 687

Answers (3)

syntaxError
syntaxError

Reputation: 866

import random

l = [x for x in range(11)] + [random.randint(0, 10) for x in range(11)]

edit If you would like the 2nd half of list to only contain elements from the first half, but in a random order

a = [x for x in range(11)]
b = a[:]
random.shuffle(b)
a.extend(b)

>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 7, 4, 10, 1, 5, 9, 3, 0, 6, 2, 8]

Upvotes: 3

zwer
zwer

Reputation: 25769

What's wrong with:

import random

your_array = list(range(1, 11)) + random.sample(range(1, 11), 10)  
#  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3, 7, 8, 2, 1, 9, 5, 10, 6, 4]

On a second read... If you want repeats in your second part you can do it as:

your_array = list(range(1, 11)) + [random.randrange(1, 11) for _ in range(10)]
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 4, 8, 1, 5, 1, 10, 5, 2, 10]

Upvotes: 2

Use the random built-in.

import random

my_list = list(range(1,11))
for i in range(10):
    my_list.append(random.randint(0, 10))

print(my_list)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 6, 5, 10, 8, 6, 10, 6, 5, 6, 6]

Upvotes: 2

Related Questions