Python – Get Random Range Average
Last Updated :
14 Mar, 2024
Given range and Size of elements, extract random numbers within a range, and perform average of it.
Input : N = 3, strt_num = 10, end_num = 15 Output : 13.58 Explanation : Random elements extracted between 10 and 15, averaging out to 13.58. Input : N = 2, strt_num = 13, end_num = 18 Output : 15.82 Explanation : 2 elements average to 15.82 in this case.
Method #1 : Using loop + uniform() The combination of above functions can be used to solve this problem. In this, we perform the task of extracting numbers using uniform() and loop is used to perform addition of numbers. The average is computed at end by dividing by size.
Python3
# Python3 code to demonstrate working of
# Random Range Average
# Using loop + uniform()
import random
# initializing N
num = 4
# Initialize strt_num
strt_num = 15
# Initialize end_num
end_num = 60
# Using loop + uniform()
res = 0.0
for _ in range(num):
# performing summation of range elements
res += random.uniform(strt_num, end_num)
# performing average
res = res / num
# printing result
print("The average value : " + str(res))
OutputThe average value : 42.980287235196116
Method #2 : Using sum() + uniform() + generator expression The combination of above functions can be used to solve this problem. In this, we perform the task of performing average using sum() to compute sum() and whole logic is encapsulated in one-liner using generator expression.
Python3
# Python3 code to demonstrate working of
# Random Range Average
# Using sum() + uniform() + generator expression
import random
# initializing N
num = 4
# Initialize strt_num
strt_num = 15
# Initialize end_num
end_num = 60
# Using sum() + uniform() + generator expression
# shorthand, using generator expression to form sum and division by Size
res = sum(random.uniform(strt_num, end_num) for _ in range(num)) / num
# printing result
print("The average value : " + str(res))
OutputThe average value : 42.980287235196116
Method #3 : Using recursion + uniform()
This approach uses NumPy’s random.uniform function to generate an array of N random numbers between strt_num and end_num. It then uses NumPy’s mean function to calculate the average of the array.
Python3
import random
def random_range_average(N, strt_num, end_num):
# Generate a list of N random floating-point numbers between strt_num and end_num using a list comprehension
random_nums = [random.uniform(strt_num, end_num) for _ in range(N)]
# Calculate the sum of the random numbers using the sum function, and then divide by N to get the average
return sum(random_nums) / N
# Example usage
N = 2
strt_num = 13
end_num = 18
print(random_range_average(N, strt_num, end_num)) # Prints the average of 2 random numbers between 13 and 18
Time complexity: O(N)
Auxiliary space: O(N)
Method #3 : Using numpy():
Algorithm :
1.Initialize the number of random numbers to generate (num), the starting point of the range (strt_num), and the ending point of the range (end_num).
2.Use numpy to generate a sequence of num random numbers within the range of strt_num to end_num.
3.Calculate the average of the generated numbers using numpy’s mean function.
4.Print the calculated average.
Python3
import numpy as np
num = 4
strt_num = 15
end_num = 60
np.random.seed(0) # set the random seed to reproduce the same sequence of random numbers
random_numbers = np.random.uniform(strt_num, end_num, size=num)
average = np.mean(random_numbers)
print("The average value : " + str(average))
#This code is contributed by Jyothi pinjala.
Output:
The average value : 41.473505114621176
The time complexity : O(num), as it takes a constant amount of time to generate each random number and to calculate the average of the generated numbers.
The space complexity : O(num), as it needs to store the generated numbers in memory before calculating the average. However, the space complexity can be reduced by generating the numbers one by one and calculating the average on-the-fly, which would result in a space complexity of O(1).
Approach#4: Using lambda
The lambda function takes three arguments, N for the number of random elements to generate, strt_num as the starting range, and end_num as the ending range. It generates N random numbers using random.uniform() function and calculates their mean using statistics.mean() function. Finally, it returns the mean of the randomly generated numbers.
Algorithm
1. Input three parameters, N, strt_num, and end_num.
2. Generate N random numbers using random.uniform() function.
3. Calculate the mean of the generated numbers using statistics.mean() function.
4. Return the calculated mean.
Python3
import random
import statistics as stats
result = lambda N, strt_num, end_num: stats.mean(random.uniform(strt_num, end_num) for _ in range(N))
print(result(3, 10, 15))
print(result(2, 13, 18))
Output13.05643776832048
15.221901001123129
Time complexity: O(N). The time complexity of the random.uniform() function is O(1) as it generates a single random number at a time. The time complexity of the statistics.mean() function is O(n) as it calculates the sum of the numbers and then divides by the length of the list.
Auxiliary Space: O(N), The lambda function generates a list of N random numbers and calculates the mean of the generated numbers.
Similar Reads
Python - Random range in list
We are given a list we need to find random range in list. For example, a = [10, 20, 30, 40, 50, 60] we need to find random ranges so that given output should be random list and it changes in every execution. Using random.samplerandom.sample can randomly pick elements from the list and preserve origi
2 min read
Python - Non-overlapping Random Ranges
Sometimes, while working with Python, we can have problem in which we need to extract N random ranges which are non-overlapping in nature and with given range size. This can have applications in which we work with data. Lets discuss certain way in which this task can be performed. Method : Using any
4 min read
Python - Generate Random String of given Length
Generating random strings is a common requirement for tasks like creating unique identifiers, random passwords, or testing data. Python provides several efficient ways to generate random strings of a specified length. Below, weâll explore these methods, starting from the most efficient. Using random
2 min read
Python Generate Random Float Number
Generating random numbers plays an important role in programming. It can be used in data analysis, cryptography, or even in simulating games like dice rolls, choosing lottery numbers, or creating unpredictable patterns. When we talk about "float" numbers, we mean numbers with decimals (like 3.14 or
3 min read
How to generate a random letter in Python?
In this article, let's discuss how to generate a random letter. Python provides rich module support and some of these modules can help us to generate random numbers and letters. There are multiple ways we can do that using various Python modules. Generate a random letter using a string and a random
1 min read
Python | Average of two lists
The problem of finding a average values in a list is quite common. But sometimes this problem can be extended in two lists and hence becomes a modified problem. This article discusses shorthands by which this task can be performed easily. Letâs discuss certain ways in which this problem can be solve
5 min read
Get Random Dictionary Pair - Python
We are given a dictionary and our task is to retrieve a random key-value pair from it. For example, given the dictionary: d = {'aryan': 10, 'harsh': 20, 'kunal': 30} then a possible output could be any one of these: ('aryan', 10), ('harsh', 20), or ('kunal', 30). Using random.choice() In this method
2 min read
Python - Random Numbers Summation
We need to do summation of random numbers. For example, n = [random.randint(1, 10) for _ in range(5)] it will generate random numbers [4, 8, 9, 4, 6] between 1 to 10 so the resultant output should be 29. Using random.randint()random.randint(a, b) function generates a random integer between a and b (
2 min read
Python | Remove random element from list
Sometimes, while working with Python lists, we can have a problem or part of it, in which we desire to convert a list after deletion of some random element. This can have it's application in gaming domain or personal projects. Let's discuss certain way in which this task can be done. Method : Using
3 min read
Python | Record elements Average in List
Given a list of tuples, write a program to find average of similar tuples in list. Examples: Input: [('Geeks', 10), ('For', 10), ('Geeks', 2), ('For', 9), ('Geeks', 10)] Output: Resultant list of tuples: [('For', 9.5), ('Geeks', 7.333333333333333)] Input: [('Akshat', 10), ('Garg', 10), ('Akshat', 2)
3 min read