Python How to Correctly Reverse Digits in Python Using Recursion?

  • Thread starter Thread starter zeion
  • Start date Start date
  • Tags Tags
    Python Recursion
AI Thread Summary
The discussion revolves around creating a recursive function in Python to reverse the digits of an integer. The initial attempts at the solution included incorrect logic that only swapped the last digit to the front without fully reversing the number. Participants suggested using recursion effectively by breaking down the problem into smaller parts, such as extracting the last digit and reducing the number in each recursive call. A key point made was that while the function should only have one parameter, local variables could still be used within the function. Suggestions included using string manipulation to achieve the reversal and ensuring that the recursion stops when the number is fully processed. The final proposed solution correctly implements recursion by converting the integer to a string, reversing it, and concatenating the digits appropriately. The conversation highlights the importance of understanding recursion and the logic behind manipulating numbers in Python.
zeion
Messages
455
Reaction score
1

Homework Statement



Code:
def rev(n):
    '''Return the result of reversing the digits in integer n. For example,
    rev(512) should return 215.'''
    
   pass

Homework Equations


The Attempt at a Solution



Code:
def rev(n):
    '''Return the result of reversing the digits in integer n. For example,
    rev(512) should return 215.'''
    
    n = str(n)[-1] + str(n)[:-1]
I'm not sure how to check that it is finished and stop?
 
Technology news on Phys.org
Hi there, checking the solution shouldn't be a problem. You would just have to print the number (n) after and see if it worked right?

I'm also not sure your code will work for integers with more than 3 digits. I'm a little rusty in python but it seems like if n = 1234 that your code might output 4123.

EDIT:

Try this?

Code:
def rev(n):
     reversed = str(n)[-1] + str(n)[:-1]
     return reversed

n = 5112
print rev(n)

So I haven't changed your code at all, I've just added an extra digit onto the number.
inside the function, the return reversed will return the string hopefully switched the way that you want it. So basically when you call the function like I did when I said "print rev(n)", the rev(n) will be the returned value.
 
Yes I haven't finished the function because I don't know how to recurse it.
The part I posted only swaps the last digit to the front.
I didn't put in the recursive step yet because I don't know how to do it.
 
ahh i see what you're trying to do. You want to keep swapping the last digit to the front until the number is reversed. Not a bad strategy. There are a handful of ways to do it, but I think in any case you will need the "len" function. len(n) will return the length of the integer. It should be helpful in your recursion.
 
So I need to cut the number to smaller pieces each time?
How can I swap the digits keep I keep cutting it?
This is confusing because I'm only allowed to use one variable n.
 
Can you give me all of the bounds of your assignment? There are most likely python objects that can do this problem and save you from having to use recursion yourself, but I assume you're not allowed to do that.
 
I don't know how to do it if n is the only variable I can use. I would need to either use higher level objects from a library, or use another variable as a counter in my recursion. I have no way to tell the recursion to stop unless I can define another variable that I can control.
 
dacruick said:
Can you give me all of the bounds of your assignment? There are most likely python objects that can do this problem and save you from having to use recursion yourself, but I assume you're not allowed to do that.

The only instruction is

'''Write the following methods recursively.'''
 
so you aren't restricted to only using 1 variable then. It should be fairly easy. Explain to me your logic, the steps that you plan to go through in your code, and I can try to help you put that logic into code form.
 
  • #10
I'm not very knowledgeable about python, but I think this would work.

I'm assuming that the parameter n is an int.
1) Calculate digit = n % 10. This gives you the current digit in the 1's place.
2) Print digit.
3) Calculate a new value for n: n = n/10. Note that this is integer division, so for example 12/10 == 1 and 8/10 == 0.
4) If n > 0, call rev(n). If n == 0, end the recursion.
 
  • #11
Mark44 said:
I'm not very knowledgeable about python, but I think this would work.

I'm assuming that the parameter n is an int.
1) Calculate digit = n % 10. This gives you the current digit in the 1's place.
2) Print digit.
3) Calculate a new value for n: n = n/10. Note that this is integer division, so for example 12/10 == 1 and 8/10 == 0.
4) If n > 0, call rev(n). If n == 0, end the recursion.

Thats a cool way to do it. This way you actually don't have to use any other variable other than n. I didn't even think about that. However, I don't think this is conceptually the easiest code to write. It's based more on nuances of programming rather than pure logic.
 
  • #12
dacruick said:
Thats a cool way to do it. This way you actually don't have to use any other variable other than n. I didn't even think about that. However, I don't think this is conceptually the easiest code to write. It's based more on nuances of programming rather than pure logic.
Actually, the logic is very pure.

At each step, you take off the last digit, print it, and then work on the remaining number, which has one less digit. This approach comes natural to C and assembly coders.
 
  • #13
Mark44 said:
I'm not very knowledgeable about python, but I think this would work.

I'm assuming that the parameter n is an int.
1) Calculate digit = n % 10. This gives you the current digit in the 1's place.
2) Print digit.
3) Calculate a new value for n: n = n/10. Note that this is integer division, so for example 12/10 == 1 and 8/10 == 0.
4) If n > 0, call rev(n). If n == 0, end the recursion.

So I can only print the last digit each time it recurses?
How can I return the result as one whole string?
 
Last edited:
  • #14
zeion said:
So I can only print the last digit each time it recurses?
How can I return the result as one whole string?

You could simply create another variable and add the digit on each time.

You could also create an indexed list and concatenate it.

So instead of the print digit, it would be digit = digit + newdigit.
the only limitation there is that it would have to be a string.
 
  • #15
dacruick said:
You could simply create another variable and add the digit on each time.

You could also create an indexed list and concatenate it.

So instead of the print digit, it would be digit = digit + newdigit.
the only limitation there is that it would have to be a string.

I understand how to do it with more variables.
I'm asking for the case of only using n as I think that was what Mark was trying to do.
 
  • #16
technically he uses a "Calculate Digit" variable. You could probably take that out, but there is no way for you to save a set of numbers without a new variable. The only option you have for keeping a single variable is to find a recursive process that retains all of the information that it started with. For example, the first idea that you had where you keep moving the last digit to the first digit would allow you to just print n at the end. The only problem you have there is to figure out how to break the loop without an index.
 
  • #17
Where does it say you are allowed to use only one variable? I don't see that restriction in what you have for the problem statement. Your function should have only a single parameter, n, but that doesn't mean you can't have other local variables.
 
  • #18
So I've clarified this and n is supposed to be the only parameter.
Here is the solution:

Code:
 def rev(n):
    '''Return the result of reversing the digits in integer n. For example,
    rev(512) should return 215.'''
    n = str(n)
    if not n:
       return (n)
    else:
       return rev(n[1:]) + n[0]
 

Similar threads

Back
Top