Open In App

Python – Get a sorted list of random integers with unique elements

Improve
Improve
Like Article
Like
Save
Share
Report

Given lower and upper limits, generate a sorted list of random numbers with unique elements, starting from start to end. 

Examples:

Input: num = 10, start = 100, end = 200
Output: [102, 118, 124, 131, 140, 148, 161, 166, 176, 180]

Input: num = 5, start = 1, end = 100
Output: [37, 49, 64, 84, 95]

To generate random numbers in Python, randint() function of random module is used. 

Syntax:

randint(start, end)

randint() accepts two parameters: a starting point and an ending point. Both should be integers and the first value should always be less than the second. Below is the implementation. 

Python3




# Python program to create
# a sorted list of unique random
# numbers
 
 
import random
 
 
# Function to generate a sorted list 
# of random numbers in a given
# range with unique elements
def createRandomSortedList(num, start = 1, end = 100):
    arr = []
    tmp = random.randint(start, end)
     
    for x in range(num):
         
        while tmp in arr:
            tmp = random.randint(start, end)
             
        arr.append(tmp)
         
    arr.sort()
     
    return arr
  
# Driver's code
print(createRandomSortedList(10, 100, 200))
print(createRandomSortedList(5)))


Output:

[102, 118, 124, 131, 140, 148, 161, 166, 176, 180]
[37, 49, 64, 84, 95]

Time complexity: O(nlogn), where n is the length of the test_list. 
Auxiliary Space: O(n), where n is the number of elements in the arr

Note: Install numpy module using command “pip install numpy”

Another approach would be to use the numpy library to generate random unique integers within a given range and then sort the resulting array.

Python3




import numpy as np
# Python program to create
# a sorted list of unique random
def createRandomSortedList(num, start = 1, end = 100):
    arr = np.random.choice(np.arange(start, end + 1), size=num, replace=False)
    arr.sort()
    return arr
 
# Driver's code
print(createRandomSortedList(10, 100, 200))
print(createRandomSortedList(5))


Output:

[102 105 106 112 114 119 129 152 176 198]
[ 4 62 77 86 98]

This approach uses the numpy function random.choice() to generate an array of random integers between start and end (inclusive) of size num without replacement. Time complexity is O(n) as it takes linear time to sort the array of size n. Space complexity is O(n) as it creates an array of size n.



Last Updated : 17 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads