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 等编程语言时,用户需要掌握列表和数值计算背后的所有概念。

更新时间: 2023-09-04

浏览量:106

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.