Python – Generate random number except K in list
Last Updated :
05 May, 2023
Sometimes, while working with python, we can have a problem in which we need to generate random number. This seems quite easy but sometimes we require a slight variation of it. That is, we require to generate random number from a list except K. Lets discuss certain ways in which this task can be performed.
Method #1: Using choice() + list comprehension The combination of above functions can be used to perform this task. In this, we first filter out the numbers except K using list comprehension and then feed that list to choice() for random number generation.
Python3
import random
test_list = [ 4 , 7 , 8 , 4 , 6 , 10 ]
print ("The original list is : " + str (test_list))
K = 4
res = random.choice([ele for ele in test_list if ele ! = K])
print ("The random number except K is : " + str (res))
|
Output :
The original list is : [4, 7, 8, 4, 6, 10]
The random number except K is : 8
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), constant extra space is needed
Method #2: Using filter() + lambda + choice() This is yet another way in which this task can be performed. In this, we perform method of creating new list using filter and lambda.
Python3
import random
test_list = [ 4 , 7 , 8 , 4 , 6 , 10 ]
print ("The original list is : " + str (test_list))
K = 4
res = random.choice( list ( filter ( lambda ele: ele ! = K, test_list)))
print ("The random number except K is : " + str (res))
|
Output :
The original list is : [4, 7, 8, 4, 6, 10]
The random number except K is : 8
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), constant extra space is needed
Method #3: Using numpy
Note: Install numpy module using command “pip install numpy”
In this method, we use the numpy library to generate a random number from the list. The list comprehension is used to filter out the numbers except K. The np.random.choice function is used to generate a random number from the filtered list.
Python3
import numpy as np
test_list = [ 4 , 7 , 8 , 4 , 6 , 10 ]
K = 4
res = np.random.choice([x for x in test_list if x ! = K])
print ( "The random number except K is : " , res)
|
Output:
The random number except K is : 8
Time Complexity: O(1) for choosing the random number from the list, O(n) for filtering the list.
Auxiliary Space: O(n) for storing the filtered list.
Share your thoughts in the comments
Please Login to comment...