Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
60 views
in Technique[技术] by (71.8m points)

python - calculating mass of a word algorithm

I have to write a function that takes in a word only in uppercase and calculate it's mass according to vowels, the problem goes like this; "vowels are ranged according to their position in the alphabet so A=1, E=5,I=15 etc etc and the vowel exists in my word if it does then we do it's range*it's position in the word to find the mass. My attempt:

    ch=input()
def poids(word):
    poids=0
    alpha="ABCDEFGHIJKLMNOPQRSTUVXYZ"
    voy=["A","E","I","O","U","Y"]
    for i in range(len(alpha)):
        p=0
        p1=0
        for j in voy:
            if alpha[i]==j:
                p=alpha.find(j)+1
        print("p=",p)        
        for k in range(len(ch)):
             for m in voy:
                 if ch[k]==m:
                     p1=ch.find(m)
                 
             poids=p*p1
                     
    return poids
print(poids(ch))
question from:https://stackoverflow.com/questions/65872988/calculating-mass-of-a-word-algorithm

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I will do this way. Please try it.

import string

alphas = string.ascii_uppercase
lookup =  {char: idx for idx, char in enumerate(alphas, 1)} # a dictionary 

print(alphas)  # can comment out later
print(lookup)  # can comment out

def poids(word):
    weight = 0
    vowels = 'AEIOU'

    for char in word:
        if char in vowels:
            weight += lookup[char]
        else:
            continue
    
    return weight


if __name__ == '__main__':
    word  = input('type a word: ')
    print(poids(word))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...