Python – 列表中平方數的乘積
在當今世界,Python 語言是最流行的語言之一,它允許使用者靈活地訪問和使用。Python 語言擁有列表、字典、元組和字串等資料結構。本文將重點介紹列表資料結構,其中資料型別可以在整數、浮點數和字串之間選擇。一旦列表被賦值,其值就不能更改。在列表中,元素按順序排列,構成一個一維陣列。
列表中平方數的乘積
列表由元素組成,允許程式設計師儲存不同物件的數。下面給出儲存不同資料型別元素的簡單語法:
list1 = [1, 2, 'Welcome', “45”]
上述列表資料結構在陣列的第一個位置儲存值 1,第二個位置儲存值 2,第三個位置儲存字串資料型別的值“welcome”,最後第四個元素的值等於 45。
平方數是指一個數乘以自身得到的數。另一種表示方法是將該值提升到 2 的冪。平方數的基本語法如下:
Squarenum = X**2
以下方法的輸入為 [9, -4, 8, -1],並將其分配給名為 list1 的變數。因此,求平方數乘積涉及的數學計算如下所示。
List1 = (9)2 * (-4)2 * (8)2 * (-1)2 = 81 * 16 * 64 * 1 = 82944
給定的數字首先被平方,然後將所有平方數相乘以得到平方數的乘積。使用 Python 功能以非常簡單快捷的方式列印相同的輸出,而不會出現任何人為錯誤。
方法
方法 1 - 使用迭代方法
方法 2 - 使用 functools 模組
方法 1:使用迭代方法計算列表中平方數乘積的 Python 程式
迭代方法用於透過計算每個元素的平方值並將其與結果相乘來遍歷列表中的每個元素。以下程式碼的時間複雜度為 0(n)。
演算法
步驟 1 - 初始化包含整數資料物件的列表輸入,其中包含正負號,例如 [9, -4, 8, -1]。
步驟 2 - 將結果初始化為 1,因為需要將乘積乘以 1 以獲得該值
步驟 3 - 當結果初始化為 0 時,它將返回 0 值。
步驟 4 - 使用 for 迴圈遍歷給定列表,然後計算數字的平方。
步驟 5 - 然後將值為“1”的結果與平方數相乘。
步驟 6 - 最後,取平方數的乘積,列印結果。
示例
#initializing the list with integer elements list1 = [9,-4,8,-1] #declaring the outcome variable as 1 to get the product value outcome = 1 #iterating through the list using for loop for num in list1: #the syntax to calculate the square number sq =num**2 #Later the square number is multiplied by the outcome outcome*=sq #Printing the final result print("The result after the multiplying the number is: ", outcome)
輸出
The result after the multiplying the number is: 82944
方法 2:使用 functools 模組計算列表中平方數乘積的 Python 程式
lambda 函式可以在不定義函式的情況下使用。以下程式碼的時間複雜度為 0(n),其中 n 表示列表的長度。
演算法
步驟 1 - 匯入 functools 庫以使用 reduce 方法。
步驟 2 - 初始化列表,其中包含四個具有不同符號的整數元素。
步驟 3 - 宣告結果變數以儲存結果值。
步驟 4 - reduce 函式有兩個引數:lambda 函式和包含平方值的子列表。
步驟 5 - 列印結果。
示例
#reduce() function is imported from the functools module from functools import reduce #initialize the list data structure list1 = [9, -4, 8, -1] #reduce method with two parameters # first parameter is a lambda function # second parameter holds the iteration outcome = reduce(lambda a,b: a*b, [m**2 for m in list1]) #the print function will return the product of the squared number print("The result after the multiplying the number is: ", outcome)
輸出
The result after the multiplying the number is: 82944
結論
給出了使用手動計算在給定列表中查詢平方數乘積的數學步驟,然後提供了使用 functools 和迭代方法等模組的簡單程式碼。在使用 Python 等程式語言時,使用者需要掌握列表和數值計算背後的所有概念。