使用 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() 計算這些生成數的總和。

方法 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)來查詢生成的隨機數的總和。

更新於: 2023-10-03

502 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.