使用 Python 查找随机数的总和
在本文中,我们将学习使用 Python 语言查找随机数总和的不同方法。在某些情况下,我们需要生成一些随机数并找到其总和,因此我们将看到从基本到改进版本的函数,使用这些函数我们可以完成此任务。
让我们看看一些查找随机数总和的方法。
方法 1. 使用简单循环
示例
import random n = 10 rand_nums = [] for _ in range(n): rand_nums.append(random.randint(1, 100)) total = sum(rand_nums) print("Random Numbers:", rand_nums) print("Summation of random numbers:", total)
输出
Random Numbers: [84, 67, 73, 29, 55, 69, 54, 76, 53, 85] Summation: 645
解释
在这个例子中,我们通过创建列表推导式生成 10 个随机数,并使用 sum 函数计算生成的随机数的总和。
方法 2. 使用 NumPy。
示例
import numpy as np n = 10 rand_nums = np.random.randint(1, 101, n) total = np.sum(rand_nums) print("Random Numbers:", rand_nums) print("Summation of random numbers:", total)
输出
Random Numbers: [53 25 52 28 37 19 18 89 57 35] Summation of random numbers: 413
解释
在上面的程序中,我们导入了 numpy,并使用 **np.random.randint()** 函数生成了 10 个介于 1 到 100 之间的随机数。生成随机数后,我们使用 np.sum() 计算这些生成数的总和。
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
方法 3. 使用 While 循环
示例
import random requied_sum = 100 summ = 0 rand_nums = [] while summ < requied_sum: num = random.randint(1, 20) if summ + num <= requied_sum: rand_nums.append(num) summ += num print("Random Numbers:", rand_nums) print("Summation of random numbers:", summ)
输出
Random Numbers: [14, 19, 4, 19, 17, 3, 5, 8, 9, 2] Summation of random numbers: 100
解释
在上面的程序中,我们导入了 random 模块来生成随机数。我们取一个变量 **required_sum** 作为我们的目标总和,直到我们得到的总和等于或大于目标,我们将继续生成随机数并将总和加入到我们的 summ 变量中。这里 rand_nums 是一个列表,用于追加生成的数字。
方法 4. 使用 Random.simple() 函数
示例
import random n = 10 rand_nums = random.sample(range(1, 101), n) total = sum(rand_nums) print("Random Numbers:", rand_nums) print("Summation of random numbers:", total)
输出
Random Numbers: [90, 87, 76, 22, 77, 6, 82, 63, 53, 3] Summation of random numbers: 559
解释
在上面的程序中,我们导入了 random 模块,用于生成随机数。我们使用 **random.simple()** 函数生成了 10 个介于 1 到 100 之间的随机数。random.simple() 函数用于生成唯一的随机数集。生成随机数后,我们使用 sum 方法将总和计算到 total 变量中。
方法 5. 使用生成器表达式
示例
import random n = 10 rand_nums = [random.randint(1, 100) for _ in range(n)] total = sum(rand_nums) print("Random Numbers:", list(rand_nums)) print("Summation of random numbers: ", total)
输出
Random Numbers: [34, 89, 92, 36, 3, 54, 79, 16, 22, 12] Summation of random numbers: 437
解释
在上面的程序中,我们导入了 random 模块用于生成随机数。我们取一个变量作为要生成的随机数的总数 n。我们将使用生成器表达式来生成随机数,并使用 sum 函数将生成的数字添加到 rand_sum 变量中。然后我们将生成器表达式转换为列表。
因此,我们了解了如何生成随机数并找到这些生成数字的总和。我们看到了使用各种方法(如简单循环、生成器函数、numpy)来查找生成的随机数的总和。