0

I just learned what recursion is and I am trying to find a way to duplicate letters in a word recursively. It's just a way to practice. If there is a better way to do it without recursion, I am open to any feedback. However, I'm primarily trying to find a solution in order to illuminate what recursion is before I go back to looking at coursework and lecture slides. It won't print the final letter twice.

My code:

def makeDups(young):
    if len(young) <= 1:
        return young
    elif young[0] != young[1]:
        return 2 * (young[0]) + makeDups(young[1:])
    else:
        return makeDups(young[1:])

young = 'abcdefg'
print(young)
print(makeDups(young))
Karup
  • 2,024
  • 3
  • 22
  • 48
yvtfg4
  • 11
  • 1
  • 6

2 Answers2

0

This doesn't need recursion.

echo "abcd" | perl -pe 's/(.)/$1$1/g'

Output:

aabbccdd
Sobrique
  • 52,974
  • 7
  • 60
  • 101
0

Your solution also fails to reduplicate a letter that's already doubled. For instance, "aabc" should return "aaaabbcc", right? You specifically avoid that case, returning "aabbcc" instead.

The correction is to eliminate that test, promoting the recursive call to the else clause:

def makeDups(young):
    if len(young) <= 1:
        return 2 * young
    else:
        return 2 * (young[0]) + makeDups(young[1:])

Finally, one last Pythonic update: your code is clean enough to turn this into a single statement:

def makeDups(young):
    return 2 * young if len(young) <= 1 \
        else 2 * (young[0]) + makeDups(young[1:])
Prune
  • 76,765
  • 14
  • 60
  • 81