Python中的连续元素最大乘积
Python具有强大的库来处理数据。我们可能会需要找到两个连续数字的最大乘积,这是大字符串的一部分。在本文中,我们将介绍实现该目标的方法。
zip和max
我们把字符串转换成一个列表。然后在切片的帮助下从连续的元素中创建成对的元素。应用*我们将一对相乘,然后从每对相乘的结果中取最大值。
示例
Astring = '5238521'
# Given string
print("Given String : ",Astring)
# Convert to list
Astring = list(Astring)
print("String converted to list:\n",Astring)
# Using max()res = max(int(a) * int(b) for a, b in zip(Astring, Astring[1:]))
# Result
print("The maximum consecutive product is : " ,res)输出结果
运行上面的代码给我们以下结果-
Given String : 5238521 String converted to list: ['5', '2', '3', '8', '5', '2', '1'] The maximum consecutive product is : 40
map和max
我们采用与上述类似的方法。但是我们使用map函数来继续生成一对连续的整数。然后使用运算符模块中的mul函数将这对数字相乘。最后应用max函数获得结果的最大值。
示例
from operator import mul
Astring = '5238521'
# Given string
print("Given String : ",Astring)
# Convert to list
Astring = list(Astring)
print("String converted to list:\n",Astring)
# Using max()res = max(map(mul, map(int, Astring), map(int, Astring[1:])))
# Result
print("The maximum consecutive product is : " ,res)输出结果
运行上面的代码给我们以下结果-
Given String : 5238521 String converted to list: ['5', '2', '3', '8', '5', '2', '1'] The maximum consecutive product is : 40
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短