rosesareblue
rosesareblue

Reputation: 13

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

Upvotes: 0

Views: 400

Answers (3)

cards
cards

Reputation: 4965

Here a method recursive and non:

def recursive_sum_even_ascii(s):
    if s:
        first, *other = s
        value = 0
        if not ord(first) % 2:
           value = ord(first)
        return value + recursive_sum_even_ascii(other)
    return 0


def sum_even_ascii(s):
    return sum(ord(char) for char in s if not ord(char) % 2)


# test
s = "23" 

out_rec = recursive_sum_even_ascii(s)
out = sum_even_ascii(s)

print(out_rec == out)

Upvotes: 0

CozyCode
CozyCode

Reputation: 504

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.

Upvotes: 1

SollyBunny
SollyBunny

Reputation: 846

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

Upvotes: 0

Related Questions