Recursion practise question help (Python)

In summary: That's not too hard though. You can either do this by reworking your code a bit, or by using a library function. I don't think you're allowed to use library functions though.If you're going to do it that way though, you're going to have to create a new variable for the result. Then you'll have to make sure that variable stays in scope as you recurse. So it would have to be declared outside of the function call. Does that make sense?In summary, the task given is to write a recursive function that reverses the digits of an integer. The function should take in one variable, n
  • #1
zeion
466
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
  • #2
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.
 
  • #3
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.
 
  • #4
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.
 
  • #5
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.
 
  • #6
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.
 
  • #7
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.
 
  • #8
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.'''
 
  • #9
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]
 

1. What is recursion in Python?

Recursion in Python is a programming technique where a function calls itself repeatedly until a certain condition is met. This allows for solving complex problems by breaking them down into smaller, simpler problems.

2. How does recursion work in Python?

In Python, a recursive function calls itself with a smaller input until it reaches the base case, which is the simplest form of the problem. Once the base case is reached, the function stops calling itself and returns a result. The results from each recursive call are then combined to solve the original problem.

3. What is the difference between recursion and iteration in Python?

Recursion and iteration are both ways to achieve repetitive execution in Python. The main difference is that recursion involves a function calling itself, while iteration uses loops to repeat a block of code. Recursion can be more elegant and concise, but it can also be less efficient and use more memory compared to iteration.

4. What are the benefits of using recursion in Python?

Recursion can help solve complex problems in a simpler, more elegant way by breaking them down into smaller, more manageable problems. It can also lead to more concise and readable code. Additionally, some problems are inherently recursive in nature, making recursion the most efficient and logical approach to solving them.

5. What are some common mistakes when using recursion in Python?

One common mistake is forgetting the base case, which can lead to an infinite loop. Another mistake is not properly breaking down the problem into smaller subproblems, resulting in inefficient code. Additionally, too many recursive calls can lead to stack overflow, which can be avoided by optimizing the recursive function.

Similar threads

  • Programming and Computer Science
2
Replies
55
Views
4K
  • Programming and Computer Science
Replies
11
Views
810
  • Programming and Computer Science
Replies
34
Views
2K
  • Programming and Computer Science
Replies
7
Views
3K
Replies
9
Views
1K
  • Programming and Computer Science
Replies
12
Views
1K
  • Programming and Computer Science
Replies
1
Views
2K
  • Programming and Computer Science
3
Replies
97
Views
7K
  • Programming and Computer Science
Replies
8
Views
951
  • Programming and Computer Science
Replies
19
Views
2K
Back
Top