Home > database >  Sum the Even Values of a String
Sum the Even Values of a String

Time:10-23

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

CodePudding user response:

When posting code which causes an error, make sure to include that error TypeError: unsupported operand type(s) for : 'int' and 'list' in this case.
No offense, but the code you have written is a hot mess. You create a list with the ord of the first char, then the output of the function.
I think you then attempt to check if both values are even (not needed), and then return the sum (which you dont do since the return statement is inside the loop).
To do this you only need to check the first value of the string, then hand the rest to the same function

def sumString(st):
    if not st:
        return 0
    out = sumString(st[1:]) # get output of the rest of the string
    if ord(st[0]) % 2 == 0: # check if first char in str is even
        out  = ord(st[0])
    return out

CodePudding user response:

Maybe something like this?

def sumString(st):
    if not st:
        return 0
    else:
        return sum((ord(st[0]), sumString(st[2:])))
        

print(sumString("aaaa"))

Output:

194
  • Related