It looks like you're using an Ad Blocker.

Please white-list or disable AboveTopSecret.com in your ad-blocking tool.

Thank you.

 

Some features of ATS will be disabled while you continue to use an ad-blocker.

 

Reversing a string in python

page: 1
2

log in

join
share:

posted on Feb, 17 2023 @ 05:45 AM
link   
In Python, I want to use recursion to reverse a string such that the characters are shown reversed (for example, "Hello" will become "olleh"/"o ll e h").

I created one that works iteratively:

def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
n = n + 1
result = s[ start: n ] + " " + result
start = n
return result

But how can I accomplish this in a recursive manner? I'm perplexed by this aspect, especially since I was just reading from this source and learning about it, and I don't work with Python or recursion very often.

Any assistance would be much appreciated.



posted on Feb, 17 2023 @ 06:29 AM
link   
a reply to: Mobo01

Not sure kind of rusty, but something like this will reverse a string.

def reverse_string(s):
if len(s) == 0:
return s
else:
return reverse_string(s[1:]) + s[0]


print(reverse_string("Hello World!"))



posted on Feb, 17 2023 @ 07:06 AM
link   

edit on 2/17/2023 by trollz because: (no reason given)



posted on Feb, 17 2023 @ 09:53 AM
link   
a reply to: Mobo01

To reverse a string recursively in Python, you can use the following function:

def reverse_string(s):
if len(s) == 0:
return s
else:
return reverse_string(s[1:]) + s[0]

Here's how this function works:

The base case of the recursion is when the string is empty. In that case, the function returns the empty string.
If the string is not empty, the function makes a recursive call to itself with the string minus its first character (i.e., s[1:]) as the argument. It then concatenates the first character of the original string (i.e., s[0]) to the end of the result of the recursive call.
Here's an example of how you can call this function:

s = "Hello"
print(reverse_string(s))

This will output "olleH", which is the reversed string of "Hello". Note that this implementation doesn't include the spaces in the reversed string. If you want to keep the spaces, you can modify the function to handle them accordingly.

-Answer per ChatGPT



posted on Feb, 17 2023 @ 10:14 AM
link   
You need to be able to think abstractly about what is happening during the recursion process to understand what is going on.

Let's say you have a list [], and we're going to limit the things you can do with that list. You can add items to it by list.append(). You can process and remove the last item with list.pop().

This is called a last-in-first-out stack, and it's a simple concept to understand how recursion is processed.

You call some function, and a copy of that is appended to an in memory stack. [f_copy(x, y)]

As you append more copies, [f_copy_(x, y), f_copy_1(a, b), f_copy_2(c, d)], and then ultimately begin the computations, you pop() the last item, and continue until one of your win/lose conditions are met.


stack = []

# iter 1 starts
f(x, y)
stack.append(f_copy(a,b)) # calls itself
stack = [f_copy(a, b)]

# iter 2 starts
stack.pop() = f_copy(a, b)
stack.append(f_copy_1(c, d)) # calls itself
stack = [f_copy_1(c, d)]

# iter 3 starts
stack.pop() = f_copy_1(c, d)
# iter 3 returns, some condition met
stack = [] # never called itself during iter 3
# iter 2 returns, statisfied
# iter 1 returns, satisfied



That's not exactly how recursion works, mind you, but that's kind of the idea.
edit on 17-2-2023 by rounda because: (no reason given)



posted on Feb, 17 2023 @ 12:59 PM
link   
nm
edit on 17-2-2023 by rounda because: (no reason given)



posted on Feb, 17 2023 @ 05:11 PM
link   
a reply to: Mobo01

I am studying Python right now, and I love it. You guys are really speaking my language!!



posted on Feb, 17 2023 @ 09:52 PM
link   
Is there a reason you don't want to use the string slicing method?

txt = "Hello World"[::-1]
print(txt)



posted on Feb, 23 2023 @ 05:27 AM
link   

s = "Hello"
reversed_s = reverse_string(s)
print(reversed_s)
a reply to: Mobo01
To reverse a string using recursion in Python, you can use the following function:



def reverse_string(s):
if len(s) == 0:
return s
else:
return reverse_string(s[1:]) + s[0]


In this function, we check if the length of the input string s is zero. If it is, we simply return the empty string. Otherwise, we recursively call the function with the string s[1:] (which is the original string with the first character removed) and add the first character of the original string s[0] to the end of the reversed string obtained from the recursive call.

Here's how you can use the reverse_string() function to reverse a string:



s = "Hello"
reversed_s = reverse_string(s)
print(reversed_s)


This will output:




olleH


Note that we use slicing to remove the first character of the string in each recursive call, which gradually reduces the size of the string until the base case is reached. The characters are then concatenated in reverse order as the function unwinds the call stack.



new topics

top topics



 
2

log in

join