2

So I am working with recursion,

The problem is:

" Good(43) Morning"

I have to use recursion to print all the information inside parenthesis like this: "(43)"

My code so far is:

def extractor(myString):
    if len(myString) == 0:
        return ""



    if myString[0] == "(":
        return myString[0]
    if myString[0] == ")":
        return myString[:]
    else:
        return extractor(myString[1:])

I can only get parenthesis. How could I change it?

2 Answers 2

1

You're almost there:

def extractor(myString):
    if not myString:  # empty strings are falsy
        return ""
    if myString[0] == "(":
        if myString[-1] == ")": # success
            return myString
        else:  # only starts with (, trim from the end
            return extractor(myString[:-1])
    else:  # doesn't start with (, trim from beginning
        return extractor(myString[1:])
Sign up to request clarification or add additional context in comments.

3 Comments

That's work but I can not use any build in function except len()
str.startswith and str.endswith are methods, not functions, but fair enough, I'll change it.
@David.Lin Am I correct input is "(43)" & not " Good(43) Morning" to function extractor
0

If you are interested, here is an iterative version of your code. :)

def iterative_extractor(mystring):
    if not mystring:
        return ""

    while mystring[0] != "(" or mystring[-1] != ")":
        if mystring[0] != "(":
            mystring = mystring[1:]
        else:
            mystring = mystring[:-1]
    return mystring

OR:

def iterative_extractor(mystring):
    if not mystring:
        return ""

    while mystring[0] != "(":
        mystring = mystring[1:]

    while mystring[-1] != ")":
        mystring = mystring[:-1]

    return mystring

Output:

mystring = "Lol (234) mate!"
print(iterative_extractor(mystring))
>>> "(234)"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.