Search code examples
pythonpython-3.xlistrecursionascii

Sum the Even Values of a String


In this Exercise, you will sum the value of a string. Complete the recursive function

def sumString(st):

This function accepts a string as a parameter and sums the ASCII value for each character whose ASCII value is an even number.

I know how to sum all the values but the even numbers part is challenging.

def  sumString(st):
     if not st:
        return 0
     else:
        return ord(st[0]+sumString(st[1:])]

I tried something but i am just confused at this point.

def  sumString(st):
     if not st:
        return 0
     t=[ord(st[0]),sumString(st[1:])]
     for item in t:
         if item%2==0:
            return item+t

Solution

  • Maybe something like this?

    def sumString(st):
        if not st:
            return 0
        else:
            out = ord(st[0]) if ord(st[0]) % 2 == 0 else 0
            return out + sumString(st[1:])
            
    
    print(sumString("abcd"))
    

    Output:

    198
    

    The ASCII value for b is 98 and the ASCII value for d is 100. So 100 + 98 gives you the output.