Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a string without using reversed() or [::-1]?

I came across a strange Codecademy exercise that required a function that would take a string as input and return it in reverse order. The only problem was you could not use the reversed method or the common answer here on stackoverflow, [::-1].

Obviously in the real world of programming, one would most likely go with the extended slice method, or even using the reversed function but perhaps there is some case where this would not work?

I present a solution below in Q&A style, in case it is helpful for people in the future.

like image 720
samrap Avatar asked Sep 08 '13 17:09

samrap


People also ask

How do you reverse a string without using the reverse method?

You can reverse a String in several ways, without using the reverse() function. Using recursion − Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function.

How do you reverse a string in Python without 1?

Reverse a string using for loop in Python for i in my_string: Now, since we are iterating, we will be using the iterating variable. We will concatenate the empty string str with the value of an iterating variable which will reverse the string one letter at a time.

How do you reverse a string in Python without function?

Method 4: Reverse string in Python using an extended slice Extended slice offers to put a “step” field as [start, stop, step], and giving no field as start and stop indicates default to 0 and string length respectively, and “-1” denotes starting from the end and stop at the start, hence reversing a string.


1 Answers

You can also do it with recursion:

def reverse(text):     if len(text) <= 1:         return text      return reverse(text[1:]) + text[0] 

And a simple example for the string hello:

   reverse(hello)  = reverse(ello) + h           # The recursive step  = reverse(llo) + e + h  = reverse(lo) + l + e + h  = reverse(o) + l + l + e + h  # Base case  = o + l + l + e + h  = olleh 
like image 181
Blender Avatar answered Sep 24 '22 02:09

Blender