I am trying to write a recursive function that prints from 0 to n, but I have no idea how to do it. I accidentally made one that prints from n to 0 though:
def countdown(n):
print(n)
if n == 0:
return 0
return countdown(n - 1)
I don't know if that helps or not, maybe I can change something in the code to make it go from 0 to n?
You're about 99% there.
Think of your base case and your recursive step - when you hit 0, what do you want to do? When you're still working your way down from n, what do you want to happen?
If you reverse the order in which you print the value, you'll reach your desired result.
def countdown(n):
if n != 0:
countdown(n-1)
print(n)
The reason this works is that recursive calls go on the call stack. As you push calls onto the stack, while your end case isn't met, you'll keep adding more calls until you reach your base case of n == 0, and then you'll exclusively start printing the values.
The other calls will then fall through to the print statement, as their execution has returned to the line after the conditional.
So, the call stack looks something like this:
countdown(5)
countdown(4)
countdown(3)
countdown(2)
countdown(1)
countdown(0)
print(0)
print(1)
print(2)
print(3)
print(4)
print(5)
You almost got it! here's a fixed, simplified version:
def countup(n):
if n >= 0:
countup(n - 1)
print(n)
Notice that:
You don't have to return anything from a recursive function that only prints values
For printing in ascending order, the print statement must be placed after the recursive call
The recursion exits when n < 0, given that we're only printing, there's nothing left to be done afterwards and it's ok to return None (Python's default return value)
UPDATE
It seems that writing a tail recursive solution is all the rage around here :) oh well, here's my shot at it, a simplified and tail-recursive version of #AndyHayden's idea - using the tail call optimization decorator recipe:
#tail_call_optimized
def countup(N, n=0):
print(n)
if n < N:
countup(N, n + 1)
Either way, it works as expected:
countup(5)
=> 0
1
2
3
4
5
You can replace the 0 and the n, and the + with a - to make your recursive countdown function to a recursive countup:
def countup(N, n=0):
print(n)
if n == N:
return
return countup(N, n + 1)
And call it as follows:
countup(3)
#JFSebastian points out this algorithm has the benefit of being O(1) rather than O(n), as discussed in this excellent article about the difference between a linear and iterative recursion, if used with the #tail_call_optimized decorator.
You can do this
def fun(num,n):
if num<n:
print(num)
fun(num+1,n)
n=int(input())
print(fun(0,n+1))
you can try this method as well:
def recursion_print(n):
if n==0:
print(n)
else:
recursion_print(n-1)
print(n)
recursion_print(9)
It should be best answer from my side.I hope u like this
def countdown(n):
if n >0: #this condition if n is greater than 0 untill run the program.
countdown(n-1) #this is recursion (calling itself).
print(n) #print the numbers.
countdown(10) #function arguments.
Related
Given 1 to 100 numbers, for multiples of 3 it should print "he" ,for multiples of 5 it should print "llo" ,for both multiples of 3 and 5 it should print "hello".
This is what I have:
for i in range (1,100):
if(i%3==0):
print("he")
elif(i%5==0):
print("llo")
elif(i%3==0 and i%5==0):
print("hello")
How would I do this recursively?
How about the code below?
def find_multiples(current, last_num=100):
# Base Case
if current > last_num:
return
result = ""
if current % 3 == 0:
result += "he"
if current % 5 == 0:
result += "llo"
if result:
print(f"{current}: {result}")
find_multiples(current+1, last_num)
find_multiples(1)
Base case is if current reaches last_num or the maximum number you'd like to check.
Here is a general outline for doing simple recursive things in python:
BASE_CASE = 1 #TODO
def f(current_case):
if current_case == BASE_CASE:
return #TODO: program logic here
new_case = current_case - 2 #TODO: program logic here ("decrement" the current_case somehow)
#TODO: even more program logic here
return f(new_case) + 1 #TODO: program logic here
Of course, this doesn't handle all possible recursive programs. However, it fits your case, and many others. You would call f(100), 100 would be current_value, you check to see if you've gotten to the bottom yet, and if so, return the appropriate value up the call stack. If not, you create a new case, which, in your case, is the "decrement" logic normally handled by the "loop" construct. You then do things for the current case, and then call the function again on the new case. This repeated function calling is what makes it "recursive". If you don't have an "if then" at the beginning of the function to handle the base case, and somewhere in the function recall the function on a "smaller" value, you're probably going to have a bad time with recursion.
This recursive function prints multiples of a number! hope it helps
def multi(n,x):
if x == 12:
print(n*x)
else :
print(n*x,end =",")
multi(n,x+1)
print(multi(4,1));
I'm trying to convert below code to recursive function but seems i'm quite confusing how could i write below in recursive function. could help me to give some thoughts?
Basically, what I'm generating below is the sum of the first n odd numbers.
def sum_odd_n(n):
total=0
j=2*n-1
i=1
if i>j:
return 1
else:
total =((j+1)/2)**2
i+=2
return total
> >>> sum_odd_n(5)
> 25.0
> >>> sum_odd_n(4)
> 16.0
> >>> sum_odd_n(1)
> 1.0
This smells somewhat like homework so I'm going to offer some advice instead of a solution.
Recursion is about expressing a problem in terms of itself.
Suppose you know the sum of the odd numbers from N to N - 2.
Can you write the total sum in terms of this sum and the function itself (or a related helper function)?
Recursive functions have at least one base case and at least one recursive call. Here are some hints:
def f(n):
# Base case - for which
# n do we already know the answer
# and can return it without
# more function calls? (Clearly,
# this must also terminate any
# recursive sequence.)
if n == ???:
return ???
# Otherwise, lets say we know the answer
# to f(n - 1) and assign it to
# the variable, 'rest'
rest = f(n - 1)
# What do we need to do with 'rest'
# to return the complete result
return rest + ???
Fill out the question marks and you'll have the answer.
Try:
def sum_of_odd(n):
if n>0:
x=(n*2)-1
return x+sum_of_odd(n-1)
else:
return 0
The answer of this:
sum_of_odd(5)
will be:
25
Try :
def sum_odd_n(n):
if n>0:
if n==1:
return 1
else:
return 2*n-1 + sum_odd_n(n-1)
This question regarding exercise 5.5 from Think Python 2 has been asked and answered already, but I still don't understand how this function works. Here's the function in question:
def draw(t, length, n):
if n == 0:
return
angle = 50
t.fd(length*n)
t.lt(angle)
draw(t, length, n-1)
t.rt(2*angle)
draw(t, length, n-1)
t.lt(angle)
t.bk(length*n)
I see a recursive loop here:
def draw(t, length, n):
if n == 0:
return
angle = 50
t.fd(length*n)
t.lt(angle)
draw(t, length, n-1)
After the function calls itself a sufficient number of times to cause n == 0, how does it move on to the next step, namely t.rt(2*angle)? Once n == 0, shouldn't the function return None and simply end? If not, where is returning to? The same thing happens again the next time it calls itself, and then the function continues to perform work long after the state n == 0 has been satisfied (twice!). I'm obviously missing a key concept here and would appreciate any light anyone can shed on this topic. Thanks in advance~
The return statement returns execution of the program back to the line where the function that returned was called.
If you're not familiar with what a call stack is, think of it as a stack of functions - whenever something gets called, it's placed on top of the stack and that's what's running. When that returns, it's removed from the stack and so the function that called it (one below in the stack) is now the top, so that's where execution picks up again.
That particular function will return when n == 0 (so that's your base case), so once its recursive call draw(t, length, n-1) - and, by consequence, its subsequent recursive calls, since it won't finish execution until they do - reach that point, it'll move over to the next line.
Take a simpler function foo(sum, n) instead:
def foo(sum, n):
if (n == 0):
return sum
sum += foo(sum, n-1)
sum /= 2
return foo(sum, n-1)
Whenever you call that, it won't move from sum += foo(sum, n-1) until that call and all of the recursive calls made return. This function is structurally comparable to the one you showed and it might help you visualize a little better what's going on.
I've posted a picture explaining this in the following question , for a fast navigation here's my picture :
I am new to Python and I have been working with it for a bit, but I am stuck on a problem. Here is my code:
def collatz(num,ctr):
if(num != 1):
ctr+=1
if(num%2==0):
collatz(num/2,ctr)
else:
collatz(num*3+1,ctr)
return ctr
test=collatz(9,0)
For any number I put in for num, let's say 9 for instance, and 0 for ctr, ctr always comes out as 1. Am I using the ctr variable wrong?
EDIT:
I am trying to print out how many times the function is recursed. So ctr would be a counter for each recursion.
The variable ctr in your example will always be 1 because of the order of the recursive call stack. As one value of ctr is returned, then the call stack will start returning the previous values of ctr. Basically, at the very last recursive call, the highest value of ctr will be returned. But since the method call at the bottom of the call stack returns the very last value aka the value that will be stored in test, test will always be 1. Let's say I input parameters into collatz that would result in five total calls of the method. The call stack would look like this coming down,
collatz returns ctr --> 5
collatz returns ctr --> 4
collatz returns ctr --> 3
collatz returns ctr --> 2
collatz returns ctr --> 1 //what matters because ctr is being returned with every method call
As you can see, no matter how many times collatz is called, 1 will always be returned because the call at the bottom of the call stack has ctr equaling 1.
The solution can be a lot of things, but it really depends on the purpose of what you're trying to accomplish which isn't clearly stated in your question.
EDIT: If you want ctr to end up being the number of times a recursive call is made, then just assign ctr to the value of the method call. It should look like this,
def collatz(num,ctr):
if(num != 1):
ctr+=1
if(num%2==0):
ctr = collatz(num/2,ctr)
else:
ttr = collatz(num*3+1,ctr)
return ctr
test=collatz(9,0)
I changed your recursive calls to set the value received back from the recursive calls into ctr. The way you wrote it, you were discarding the values you got back from recursing.
def collatz(num,ctr):
if(num != 1):
ctr+=1
if(num%2==0):
ctr=collatz(num/2,ctr)
else:
ctr=collatz(num*3+1,ctr)
return ctr
test=collatz(9,0)
An example:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
n = input("Give me a number: ")
while n != 1:
n = collatz(int(n))
Function parameters in Python are passed by value, not by reference. If you pass a number to a function, the function receives a copy of that number. If the function modifies its parameter, that change will not be visible outside the function:
def foo(y):
y += 1
print("y=", y) # prints 11
x = 10
foo(x)
print("x=", x) # Still 10
In your case, the most direct fix is to make ctr into a global variable. Its very ugly because you need to reset the global back to 0 if you want to call the collatz function again but I'm showing this alternative just to show that your logic is correct except for the pass-by-reference bit. (Note that the collatz function doesn't return anything now, the answer is in the global variable).
ctr = 0
def collatz(num):
global ctr
if(num != 1):
ctr+=1
if(num%2==0):
collatz(num/2)
else:
collatz(num*3+1)
ctr = 0
collatz(9)
print(ctr)
Since Python doesn't have tail-call-optimization, your current recursive code will crash with a stack overflow if the collatz sequence is longer than 1000 steps (this is Pythons default stack limit). You can avoid this problem by using a loop instead of recursion. This also lets use get rid of that troublesome global variable. The final result is a bit more idiomatic Python, in my opinion:
def collats(num):
ctr = 0
while num != 1:
ctr += 1
if num % 2 == 0:
num = num/2
else:
num = 3*num + 1
return ctr
print(collatz(9))
If you want to stick with using recursive functions, its usually cleaner to avoid using mutable assignment like you are trying to do. Instead of functions being "subroutines" that modify state, make them into something closer to mathematical functions, which receive a value and return a result that depends only on the inputs. It can be much easier to reason about recursion if you do this. I will leave this as an exercise but the typical "skeleton" of a recursive function is to have an if statement that checks for the base case and the recursive cases:
def collatz(n):
if n == 1:
return 0
else if n % 2 == 0:
# tip: something involving collatz(n/2)
return #???
else:
# tip: something involving collatz(3*n+1)
return #???
The variable will return the final number of the collatz sequence starting from whatever number you put in. The collatz conjecture says this will always be 1
I was doing an online course for python and on the functions part of the course, they made two functions (one for determining prime numbers and one printing them)
def isprime(n):
if n == 1:
return False
for x in range(2, n):
if n % x == 0:
return False
else:
return True
def primes(n=1):
while(True):
if isprime(n): yield n
n += 1
for n in primes():
if n > 100: break
print(n)
what i don't understand is the parameter of the function primes. Why is it n=1. I'm new to programming in general as you could probably tell and I'm not very knowledgeable on functions and generators. Any help would be greatly appreciated.
It's a default value. If a parameter is passed to the function it will behave "normally", otherwise it will use the default.
def my_print(num=1):
print num
my_print()
>> 1
my_print(7)
>> 7
Keyword argument in the function call means a match by name, and in the
function header it specifies a default for an optional argument.