📜  Python|字符串中的最大差异

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

Python|字符串中的最大差异

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

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

# Python3 code to demonstrate
# Maximum Difference 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 Difference in String
test_string = list(test_string)
res = max(abs(int(a) - int(b)) for a, b in zip(test_string, test_string[1:]))
  
# print result
print("The maximum consecutive difference is : " + str(res))
输出 :
The original string : 6543452345456987653234
The maximum consecutive difference is : 3

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

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