📜  Python – 数字字符串中的最大对求和

📅  最后修改于: 2022-05-13 01:54:39.633000             🧑  作者: Mango

Python – 数字字符串中的最大对求和

有时,我们可能会遇到一个问题,即我们需要从字符串中获取 2 个数字的最大总和,但有一个限制是让数字连续。在竞争性编程中可能会出现此类问题。让我们讨论一些可以解决这个问题的方法。

方法 #1:使用max() + zip() + 列表理解
这个问题可以通过上述三个函数的组合来解决,其中 max函数可以用来获取最大值,zip 和列表理解完成将逻辑扩展到整个列表的任务。

# Python3 code to demonstrate
# Maximum Pair Summation in String
# using zip() + max() + list comprehension
  
# initializing string 
test_string = '6543452345456987653234'
  
# printing original string 
print("The original string : " + str(test_string))
  
# using zip() + max() + list comprehension
# Maximum Pair Summation in String
test_string = list(test_string)
res = max(int(a) + int(b) for a, b in zip(test_string, test_string[1:]))
  
# print result
print("The maximum consecutive sum is : " + str(res))
输出 :
The original string : 6543452345456987653234
The maximum consecutive sum is : 17

方法 #2:使用max() + map() + operator.add
上述问题也可以使用另一种功能组合来解决。在这种组合中,map 函数执行将逻辑扩展到整个列表的任务,而 add运算符用于执行加法。

# Python3 code to demonstrate
# Maximum Pair Summation in String
# using max() + map() + operator.add
from operator import add
  
# initializing string 
test_string = '6543452345456987653234'
  
# printing original string 
print("The original string : " + str(test_string))
  
# using max() + map() + operator.add
# Maximum Pair Summation in String
res = max(map(add, map(int, test_string), map(int, test_string[1:])))
  
# print result
print("The maximum consecutive sum is : " + str(res))
输出 :
The original string : 6543452345456987653234
The maximum consecutive sum is : 17