Python - 最大得分词
给定一个字符串,任务是编写一个Python程序来计算最大得分单词,即由具有最大位置总和的字符组成的单词。
例子:
Input : test_str = ‘geeks must use geeksforgeeks for cs knowledge’
Output : geeksforgeeks
Explanation : Sum of characters positional values for “geeksforgeeks” word is maximum, hence result.
Input : test_str = ‘geeks love geeksforgeeks’
Output : geeksforgeeks
Explanation : Sum of characters positional values for “geeksforgeeks” word is maximum, hence result.
方法 #1:使用split() + loop + ord() + ascii_lowercase
在此,我们最初使用 split() 拆分每个单词,使用 ord() 获取位置大小,ascii_lowercase 检查选择用于评估的正确字符池。
Python3
# Python3 code to demonstrate working of
# Maximum Scoring word
# Using split() + loop + ord() + ascii_lowercase
import string
# initializing string
test_str = 'geeks must use geeksforgeeks for cs knowledge'
# printing original string
print("The original string is : " + str(test_str))
score = 0
max_sc = 0
res = ''
for wrd in test_str.split():
score = 0
# computing score
for lttr in wrd:
if lttr in string.ascii_lowercase:
score += ord(lttr) - 96
# updating maximum
if score > max_sc:
max_sc = score
res = wrd
# printing result
print("Maximum scoring word : " + str(res))
Python3
# Python3 code to demonstrate working of
# Maximum Scoring word
# Using sum() + loop + ord()
import string
# initializing string
test_str = 'geeks must use geeksforgeeks for cs knowledge'
# printing original string
print("The original string is : " + str(test_str))
score = 0
max_sc = 0
res = ''
for wrd in test_str.split():
# computing score
# sum for cumulation
score = sum(ord(lttr) - 96 for lttr in wrd if lttr in string.ascii_lowercase)
# updating maximum
if score > max_sc:
max_sc = score
res = wrd
# printing result
print("Maximum scoring word : " + str(res))
输出:
The original string is : geeks must use geeksforgeeks for cs knowledge
Maximum scoring word : geeksforgeeks
方法#2:使用sum() + loop + ord()
与上述方法类似,这里唯一的区别是 sum() 用于求和任务而不是内部循环。
蟒蛇3
# Python3 code to demonstrate working of
# Maximum Scoring word
# Using sum() + loop + ord()
import string
# initializing string
test_str = 'geeks must use geeksforgeeks for cs knowledge'
# printing original string
print("The original string is : " + str(test_str))
score = 0
max_sc = 0
res = ''
for wrd in test_str.split():
# computing score
# sum for cumulation
score = sum(ord(lttr) - 96 for lttr in wrd if lttr in string.ascii_lowercase)
# updating maximum
if score > max_sc:
max_sc = score
res = wrd
# printing result
print("Maximum scoring word : " + str(res))
输出:
The original string is : geeks must use geeksforgeeks for cs knowledge
Maximum scoring word : geeksforgeeks