user11669928
user11669928

Reputation:

Generate random Numbers in Ascending order?

How to generate random numbers in ascending order like this in a loop and append them into a list

12345 12346 12347 12348.....

tried this, this code will generate random integer, Need them in ascending order.

lists = []
for z in range(3000):
    lists.append((randint(12345,13333)))

lists_1=[str(cell) for  cell in lists_phone]
print(lists_1)

Upvotes: 0

Views: 2991

Answers (3)

Peter O.
Peter O.

Reputation: 32908

Just generate the integers then sort them. In Python, sort() sorts a list:

listvar = [randint(12345,13333) for _ in range(3000)]
listvar.sort()
print(listvar)

Upvotes: 3

DeepSpace
DeepSpace

Reputation: 81684

numpy's version to @Peter O's approach. If you already have numpy you can use it for a much better performance:

import numpy as np
from timeit import Timer
from random import randint

print(min(Timer(lambda: [randint(12345, 13333) for _ in range(3000)].sort()).repeat(100, 100)))
print(min(Timer(lambda: np.random.randint(12345, 13333, 3000).sort()).repeat(100, 100)))

Outputs

0.5073430000000023
0.016132899999999673

Numpy is 31 times faster

Upvotes: 0

epsilonmajorquezero
epsilonmajorquezero

Reputation: 599

If you must generate them one by one and they must be already in order:

lists = []
min = 12345
max = 13333
for z in range(3000):
    lists.append(max * z + (randint(min,max)))

lists_1=[str(cell) for  cell in lists_phone]
print(lists_1)

But probably what you are really looking for is @Peter O. answer.

Upvotes: 0

Related Questions