2

I have two string list: A = ['YELLOW'] B = ['BA']

I want to combine these two string using a recursive function to get ['YBAEBALBALBAOBAWBA']

HERE IS my function :

def Combine(A, B):

    if len(A) > 0:
        return str(A[0]) + str(B) + Combine(A[:0], B)

-- I have no idea how recursive works? Could someone please help me!

1
  • what is the question ? Commented Oct 22, 2017 at 2:20

1 Answer 1

4

You were very close!

def Combine(A, B):
    if len(A) > 0:
        return str(A[0]) + str(B) + Combine(A[1:], B) # <-- fix 1
    else:
        return '' # <-- fix 2
  1. in order to call recursively with the rest of A you should call A[1:]
  2. you took care of the case that len(A) > 0 but forgot to take care of the case that A ran out of characters (the else)

Running

A = 'YELLOW'
B = 'BA'

print(Combine(A, B))

OUTPUT

YBAEBALBALBAOBAWBA
Sign up to request clarification or add additional context in comments.

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.