Create a set of sorted random numbers from a specific range

I would like to create a set of x unique random numbers and sort them in Python. For example: range (1000, 10000) x = 100

I decided to import random and use the random.randrange method, then loop to get 100 random numbers and sort them at the end.

However, I do not know how to get unique numbers (so that they do not repeat) - should I check each cycle? Or is there another way to do this? And how to sort them?

Thanks y'all!

+4
source share
2 answers

Use random.sample

 numbers = random.sample(xrange(1000, 10000), 100) # or `range` in Python 3 

The sorting element is simple - use the list.sort method.

 numbers.sort() 

By default, this sorts it from the smallest to the largest, but it requires an optional key argument, which determines what to sort it.

There is also a sorted function that does not change the list in place, but rather returns a sorted list.

 numbers_sorted = sorted(numbers) 

It also has an optional key argument.

+9
source

more_itertools implements random_combinations itertools recipe, which returns r sorted random numbers if a sorted input is given.

 import more_itertools as mit mit.random_combination(range(1000, 10000), r=100) # (1016, 1112, 1233, 1367, 1446, 1460, 1518, 1807, 1832, 1956, ...) 

Unlike random.sample , which returns an unsorted result.


More details

Looking at the recipe, we can understand why this order is established.

From itertools recipes :

 def random_combination(iterable, r): """Return a random *r* length subsequence of the elements in *iterable*. >>> random_combination(range(5), 3) # doctest:+SKIP (2, 3, 4) This equivalent to taking a random selection from ``itertools.combinations(iterable, r)``. """ pool = tuple(iterable) n = len(pool) indices = sorted(sample(range(n), r)) return tuple(pool[i] for i in indices) 

range() is essentially sorted and becomes a pool from which random elements are selected. Although indexes are randomly selected, they are subsequently sorted. Because pool and indices sorts are sorted, results are also sorted.

In general, this does the same as @Volatility's answer, except that sorting is handled for you.

Cavaet: random_combinations requires that the length of the iterability exceeds the value of r , otherwise an error occurs.

0
source

All Articles