Quick actions

cmd+k|ctrl+k

Navigation

Languages

Exercise: Reverse String With Recursion

Snippet info

Language

Python

Visibility

public

Author

rakeshbhatia87

Created

2023-01-09T21:32:04.96887Z

Updated

2023-01-10T08:30:56.360567Z

#Implement a function that reverses a string using iteration...and then recursion!
def reverseStringIterative(word):
    word = list(word)
    i, j = 0, len(word)-1
    while i < j:
        word[i], word[j] = word[j], word[i]
        i += 1
        j -= 1
    return ''.join(word)
    
def reverseStringRecursive(word):
    if len(word) == 1:
        return word
    return reverseStringRecursive(word[1:]) + word[0]

result = reverseStringIterative('yoyo mastery')
print(result)

result = reverseStringRecursive('yoyo mastery')
print(result)

#should return: 'yretsam oyoy'
INFO