Search code examples
pythonrecursionreturn

Getting two different values from a recursive function?


I am trying to create a function in python that splits a string in to two strings, where the first one have all the lower case letters + some other special characters and the second one having all the upper case letters + special characters.

The point is to be able to type:

>>> first_message,second_message=string_split("SomEChaRacTers")
>>> print(first_message, second_message)

to get the result printed.

This is what i have right now:

def string_split(string):
    first_message_signs = "_."
    second_message_signs = " |"
    one = ""
    two = ""
    if len(string) == 0:
        return string
    
    if string[0].islower() or string[0] in first_message_signs:
        one += string[0] + string_split(string[1:])
        return one
    
    elif string[0].isupper() or string[0] in second_message_signs:
        two += string[0] + string_split(string[1:])
        return two
    else:
        return string_split(string[1:])

I am getting this error when making the first call in the prompt: Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack (expected 2)

When i try with only message_one i get all the characters in one string.

What should i do?


Solution

  • Your first line

    first_message,second_message=string_split("SomEChaRacTers")
    

    expects string_split to return two values. However, your function only ever returns one.

    What you want is

    def string_split(string):
        first_message_signs = "_."
        second_message_signs = " |"
        one = ""
        two = ""
        if len(string) == 0:
            return one, two
        
        if string[0].islower() or string[0] in first_message_signs:
            one += string[0]
        elif string[0].isupper() or string[0] in second_message_signs:
            two += string[0]
    
        ret1, ret2 = string_split(string[1:])
        one += ret1
        two += ret2
    
        return one, two
    

    On a side note, there's no compelling reason for string_split to be recursive. Try this:

    def string_split(string):
        first_message_signs = "_."
        second_message_signs = " |"
    
        one = ''.join(c for c in string if c.islower() or c in first_message_signs)
        two = ''.join(c for c in string if c.isupper() or c in second_message_signs)
    
        return one, two