Skip to content

Commit 1ae19a4

Browse files
committed
Completed implementation of reverse a string program using recursion.
1 parent 2e5a31b commit 1ae19a4

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""
2+
Implement a function that reverses a string using iteration...and then recursion!
3+
4+
For example, given a string 'hello', the function should output 'olleh'.
5+
"""
6+
7+
8+
# Function definition
9+
10+
# Method to reverse a string using recursion.
11+
def reverse_string_recursion(to_reverse):
12+
# Check if the end of the string is reached, can be done other way is to check the length of the string is 0.
13+
if to_reverse == "":
14+
return to_reverse # Will return "" at the end.
15+
else:
16+
return reverse_string_recursion(to_reverse[1:]) + to_reverse[0] # Keep doing recursion until end of string.
17+
18+
19+
# Method to reverse a string using iteration. Time and Space complexity is O(n).
20+
def reverse_string_iteration(to_reverse):
21+
reversed_string = []
22+
for i in reversed(list(to_reverse)):
23+
reversed_string.append(i)
24+
return ''.join(reversed_string)
25+
26+
27+
# Declaration
28+
string = 'This is so cool!'
29+
print(reverse_string_iteration(string))
30+
print(reverse_string_recursion(string))

0 commit comments

Comments
 (0)