samedi 31 juillet 2021

Recursive function that removes all odd numbers in a string; how to include negative symbol

Basically what the title says. It takes a string, removes all odd numbers in the string via recursion, and returns a modified string. For example, "54364" becomes "464", "4234" becomes "424", etc.

def removeOddDigits(inString):
#base case
    if inString == "":
        return inString
    else:
#if it's an even number keep it
        if int(inString[0]) % 2 == 0:
            return str(inString[0]) + str(removeOddDigits(inString[1:]))
        else:
#if it's an odd number skip it
            return removeOddDigits(inString[1:])
        
        
print(removeOddDigits(input("Enter String:")))

For the most part the code works as suspected, but I also want it to also include negative numbers. The problem is that it's only comparing int values, and the "-" character results in an invalid literal error. And I cannot use type() != int comparison either because it's all consisted of strings. Is there a way to bypass this so that it not only keeps even digits but also non-numerical characters?

Aucun commentaire:

Enregistrer un commentaire