Python 3D Academyবাংলা

Recursion on strings and lists

🌍 In real life. To read a word backwards, you could say: "the backwards word is the backwards version of everything after the first letter, followed by the first letter". It sounds like a riddle, but it works, because "everything after the first letter" is a shorter word, and an empty word backwards is still empty.

Strings and lists shrink nicely like that, which makes them a natural fit for recursion.

The idea in one sentence: with strings and lists, the smaller problem is usually the same thing without its first item (s[1:]), and the base case is the empty string or the empty list.

Its words:

  • s[0]: the first item; s[1:]: everything after it
  • empty base case: "" or [], the smallest string or list
  • palindrome: a word that reads the same both ways, like "level"

Step by step, for rev("abc"):

  1. rev("abc") = rev("bc") + "a".
  2. rev("bc") = rev("c") + "b", and rev("c") = rev("") + "c".
  3. rev("") is the base case, "". Coming back up: "c", then "cb", then "cba".
def rev(s):
    if s == "":
        return ""
    return rev(s[1:]) + s[0]

print(rev("abc"))
print(rev("python"))

The same idea adds up a list: the first number, plus the sum of the rest.

def sum_list(nums):
    if not nums:
        return 0
    return nums[0] + sum_list(nums[1:])

print(sum_list([4, 1, 5]))
print(sum_list([]))

A palindrome reads the same both ways. Check the first and last letters, then the middle, which is a smaller string:

def is_palindrome(s):
    if len(s) <= 1:
        return True
    if s[0] != s[-1]:
        return False
    return is_palindrome(s[1:-1])

print(is_palindrome("level"))
print(is_palindrome("lever"))

What it costs. There's one call per item, but each s[1:] copies the rest of the string (Lesson 4.2), so the copies add up: for a string of length n, about n + (n − 1) + … + 1, roughly n²/2 characters copied. Fine for words; slow for a book. A loop, or recursion that passes an index instead of slicing, avoids the copies. And the depth limit still applies: a list of 5,000 items is too deep.

Mistakes and edge cases.

  • No empty-string base case. rev("") would call rev(""[1:]), which is rev("") again, forever.
  • Indexing an empty list. nums[0] on [] gives IndexError: list index out of range; check the base case first.
  • Joining in the wrong order. s[0] + rev(s[1:]) just rebuilds the original string.
  • Forgetting the palindrome's short cases. Both "" and a single letter are palindromes; len(s) <= 1 catches both.

Quiz

  1. What does this print?

    def rev(s):
        if s == "":
            return ""
        return rev(s[1:]) + s[0]
    
    print(rev("hey"))
  2. What does this print?

    def sum_list(nums):
        if not nums:
            return 0
        return nums[0] + sum_list(nums[1:])
    
    print(sum_list([1, 2, 3]))
  3. What does this print?

    def length(s):
        if s == "":
            return 0
        return 1 + length(s[1:])
    
    print(length("tiger"))
  4. What is "code"[1:]?

    • "ode"
    • "c"
    • "cod"
  5. Which line has a mistake?

    def sum_list(nums):
        if len(nums) == 1:
            return nums[0]
        return nums[0] + sum_list(nums[1:])
    
    print(sum_list([]))

Coding tasks

  1. Write a recursive reverse(s) that returns the string s backwards. Don't use [::-1].

  2. Write a recursive count_char(s, ch) that returns how many times the letter ch appears in s.

  3. Write a recursive biggest(nums) that returns the largest number in a non-empty list. Don't use max.