Python – 获取随机范围平均值
给定元素的范围和大小,提取范围内的随机数,并对其进行平均。
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.
方法 #1:使用循环 + uniform()
上述功能的组合可以用来解决这个问题。在此,我们使用 uniform() 执行提取数字的任务,并使用循环来执行数字相加。最后通过除以大小来计算平均值。
# 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))
输出 :
The average value : 42.980287235196116
方法#2:使用sum() + uniform()
+ 生成器表达式
上述功能的组合可以用来解决这个问题。在此,我们使用 sum() 执行平均任务以计算 sum(),并且整个逻辑使用生成器表达式封装在单行中。
# 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))
输出 :
The average value : 42.980287235196116