How to Correctly Reverse Digits in Python Using Recursion?

  • Context: Python 
  • Thread starter Thread starter zeion
  • Start date Start date
  • Tags Tags
    Python Recursion
Click For Summary

Discussion Overview

The discussion revolves around implementing a recursive function in Python to reverse the digits of an integer. Participants explore various approaches, challenges, and the constraints of using recursion while adhering to specific assignment guidelines.

Discussion Character

  • Homework-related
  • Exploratory
  • Technical explanation
  • Debate/contested

Main Points Raised

  • One participant presents an initial function that only swaps the last digit to the front without completing the recursion.
  • Another participant suggests that checking the output could be done by printing the number after the function call, but raises concerns about handling integers with more than three digits.
  • Several participants discuss the need for a recursive approach and the challenge of using only one variable, n, while reversing the digits.
  • Some participants propose using the length of the integer to assist in recursion, while others question how to manage the recursion without additional variables.
  • A participant outlines a method involving integer division and modulus to extract digits, suggesting that this could work without additional variables.
  • Another participant acknowledges the proposed method but expresses concern about its conceptual clarity compared to other potential solutions.
  • There is a suggestion to create another variable to accumulate the reversed digits, but this is debated in the context of the assignment's restrictions.
  • Clarification is sought on whether the restriction to a single variable applies only to the function parameter or to local variables as well.
  • A final solution is proposed that uses string manipulation to achieve the reversal recursively, indicating that the function can return the reversed string without additional variables.

Areas of Agreement / Disagreement

Participants express differing views on the constraints of using only one variable and the best approach to implement the recursive function. There is no consensus on the optimal method, and multiple strategies are discussed.

Contextual Notes

Participants mention various constraints from the assignment, including the requirement to use recursion and the potential limitations on variable usage. The discussion reflects uncertainty regarding the interpretation of these constraints.

Who May Find This Useful

Individuals interested in Python programming, particularly those learning about recursion and digit manipulation, may find this discussion beneficial.

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

Replies
55
Views
7K
  • · Replies 17 ·
Replies
17
Views
2K
  • · Replies 11 ·
Replies
11
Views
1K
  • · Replies 34 ·
2
Replies
34
Views
6K
Replies
3
Views
3K
  • · Replies 97 ·
4
Replies
97
Views
10K
  • · Replies 7 ·
Replies
7
Views
5K
  • · Replies 22 ·
Replies
22
Views
6K
  • · Replies 19 ·
Replies
19
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K