Python - N Random Tuples list


The problem statement is to find the N random tuples list using Python functionalities. Sometimes we need to generate some random numbers or we can say random tuples in our daily life applications. So in this problem we can generate random tuples using the random library of Python.

Understanding the Problem

So let us understand the problem first, suppose we have given the limit of the tuple numbers and also the number of tuples we have to generate using the algorithm. To understand this phenomenon we will see the below image −

Number of tuples = 5
Minimum value of tuples = 0
Maximum value of tuples = 10
Generated list of tuples = [(4, 1), (2, 10), (5, 3), (6, 3), (1, 7)]

Logic for The Above Problem

To solve the above problem we first import the random module of Python. With this module we enable generating random numbers for the specified range. Next, we will define the function to carry out this task. And also use some arguments to specify the values of the minimum and maximum value in the tuples and also the number of tuples to generate. Then using the random module we will generate each tuple and return its value.

Algorithm

  • Step 1 − As we have to generate N random tuples list, we will first import the random module.

  • Step 2 − Here we will define the function called N_random_tuples and inside this function we pass three parameters as num_of_tuples, min and max values.

  • Step 3 − Using the random function we will generate random integers within the given range of tuples as min and max.

  • Step 4 − Return the list of tuples at the end and print its value.

Example

# Import the random library
import random
# Define the function to find n random tuples
def n_random_tuples(num__of_tuples, min, max):
   tuple_list = [(random.randint(min, max), random.randint(min, max)) for _ in range(num__of_tuples)]
   return tuple_list

# Example usage
num__of_tuples = 5
min_value = 0
max_value = 10

the_tuples = n_random_tuples(num__of_tuples, min_value, max_value)
print("N random tuples list is: ",the_tuples)

Output

N random tuples list is:  [(3, 9), (8, 10), (8, 2), (10, 1), (6, 9)]

We can see in the above Output that there are 5 numbers of tuples as we have given the value and the range of each number inside the tuples is within 0 to 10 as we have given.

Complexity

The time complexity for finding the N random tuples list using Python is O(N), here N is the number of tuples within the list. As we have created the N tuples in the list using a random module.

Conclusion

So we have effectively generated the list of tuples of size N. We have basically used a random module of Python, which makes our code easy and faster to create N tuples in the list.

Updated on: 18-Oct-2023

54 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements