如何在Python中计算s字符串的权重?

2024-05-16 00:47:15 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个字符串S,我们将它的权重定义为元音在字符串中位置的乘积(从1开始)。例:重量(“e”)=1体重(“年龄”)=3;重量(“pippo”)=10

我试过这个:

def weight(s):
    vowels = ['a','e','i','o','u']
    numbers = []
    for c in s:
        if c in vowels:
                n = s.index(c)+1
                numbers.append(n)
    result = 1
    for x in numbers:
        result = result*x
    print(result)

但它只适用于不同的元音。如果字符串中有相同的元音,则数字是错误的。 我错过了什么

谢谢大家


Tags: 字符串infor定义defresult权重乘积
3条回答

您可以使用以下选项:

s = 'pippo'
np.prod([i+1 for i,v in enumerate(s) if v in ['a','e','i','o','u']])

10

也许这不是一个最佳的方法,但这是有效的

vowels = ['a', 'e', 'i', 'o', 'u', 'y']
mystring = 'pippo'
weight = 1
i = 0
while i < len(mystring):
    if mystring[i] in vowels:
        weight *= i+1
    i += 1
if weight == 1 and mystring[0] not in vowels:
    weight = 0
print(weight)

最后一个IF语句消除了字符串包含0个元音的一个例外情况

str.index()的工作原理与str.find类似,因为:

Return the lowest index in the string where substring sub is found [...]

Source: str.index -> str.find)

仅返回第一个事件索引

functools.reduceoperator.mul以及enumerate (from 1)使其成为一行:

from operator import  mul
from functools import reduce

value = reduce(mul, (i for i,c in enumerate("pippo",1) if c in "aeiou"))

或者对于所有字符串:

for t in ["e","age","pippo"]:
    # oneliner (if you omit the imports and iterating over all your given examples)
    print(t, reduce(mul, (i for i,c in enumerate(t,1) if c in "aeiou")))

输出:

e 1
age 3
pippo 10

相关问题 更多 >