-1

Inverting a string is easy:

def invert(text):
    if text == "":
        return text
    else:
        return invert(text[1:]) + text[0]

I'm trying to create a recursive function that also keeps the original string, i.e.: 1234 -> 1234 4321 and 123 -> 12321. What's the most efficient way to do this?

student
  • 177
  • 2
  • 10

1 Answers1

0

Given a recursive function, build_all_palindromes, build all possible palindromes given a list of characters and a target length. The function has 4 parameters: current_string, target_length, current_length, and list_letters.

First, you have to make the base case when the target length is equal to the current length. Now, if the target length is even we can increment the current length by two, and increment by one if odd. Once the function has built the palindrome of desired target length, it will print the string and return. Here is where it gets tricky. You have to loop through each letter in the list of letters and then call the function on itself (the recursive part) if two conditions are met. Does the palindrome have a seed or not, i.e. the length of current string is zero, and if so, is the target length even or odd?

If we do not have a seed, we check to see if the target length is even/odd. Else we add the current letter to the beginning and end of the current_string. and increase the current_length by two since we added a single character to both ends of the string.

Now, if we do have a seed and the target_length is even, add the current letter to the current_string twice and increase current_length by two. Else, if the target_length is odd, just add the current letter once and increase the current_length by one.

Here is what I have:

<!-- language: lang-python -->
    def build_all_palindromes(current_str, target_len, current_len, letters):
    if target_len == current_len: #current_len:
        print(current_str)
        return
    for i in letters:
        if current_len == 0: # need seed
            if target_len % 2 == 0: # is even
                build_all_palindromes(i*2, target_len, 2, letters)
            else: # is odd
                build_all_palindromes(i, target_len, 1, letters)
        else: # have seed
            build_all_palindromes(i + current_str + i, target_len, current_len+2, letters)

    if __name__ == "__main__":
        letters = ["c", "i", "v"]
        build_all_palindromes("", 3, 0, ["c", "i", "v"])

Should return:

ccc
ici
vcv
cic
iii
viv
cvc
ivi
vvv