DSA 24: Recursion - 3 More Examples [Part 5]

Summation, String-Reversal & Counting-Letter
data structures
algorithms
Author

Tony Phung

Published

February 7, 2025

1. Summation of an array

def sum(arr):
    if not arr:
        return 0
    return arr[0] + sum(arr[1:])

arr=[1,2,3,4,5]
sum(arr)
15

2. Reversing a string

def rev_string(string):
    # string "abcde"    
    # return rev_string("bcde")
    if not string:
        return ""
    return rev_string(string[1:]) + string[0]

string = "abcde"
rev_string(string)
'edcba'

3. Count character occurence in a string

def count_ys(string):
    if not string:
        return 0
    if string[0]=="y":
        return 1+count_ys(string[1:])
    else: 
        return count_ys(string[1:])
        
string = "yaybyc"
count_ys(string)
3