Home > Blockchain >  Get the Sum of the Values of Letters in a Name
Get the Sum of the Values of Letters in a Name

Time:10-26

Numerologists claim to be able to determine a person's character traits based on the "numeric value" of a name. The value of a name is determined by summing up the values of the letters of the name. For example, the name Zelle would have the value 26 5 12 12 5 = 60. Write a function called get_numeric_value that takes a sequence of characters (a string) as a parameter. It should return the numeric value of that string. You can use to_numerical in your solution.

Just to preface, this is an exercise I have to do for a lab in my programming class. It's been asked here before (sorry!) but none of the results really helped address the issue I was having with it.

First, my code for to_numerical (a function I had to make to convert letters to numbers [notably not the ASCII codes; had to start from A = 1, etc.]) was this:

def to_numerical(character): 
    if character.isupper():
        return ord(character) - 64
    elif character.islower():
        return ord(character) - 96

In regards to the actual problem, I'm stuck since I can only get the function to return the value of the Z in Zelle (which is supposed to be 26 here). I've pasted what I have so far below:

def get_numeric_value(string):
    numerals = []
    for character in string:
        if character.isupper():
            return ord(character) - 64
        elif character.islower():
            return ord(character) - 96
        return numerals
    addition = sum(numerals)
    return addition

I was thinking I would probably have to use sum() at some point, but I think the issue is more that I'm not getting all of the letters returned to the numerals list. How can I get it so the code will add up and return all the letters? I've been trying to think something up for an hour but I'm stumped.

CodePudding user response:

You should just use a sum variable and add to it each character value and then return that sum:

def get_numeric_value(string):
    numerals = []
    sum = 0
    for character in string:
        if character.isupper():
            sum  = ord(character) - 64
        elif character.islower():
            sum  = ord(character) - 96
    return sum
  • Related