Confusion in recursion program of python - python

Hey guys can anyone explain that output to me?
Don't get why its counting down again.
def kaboom(i):
print("first Print: ", i)
if i < 3:
kaboom(i+1)
print("second Print: ", i)
OUTPUT:
first Print: 1
first Print: 2
first Print: 3
second Print: 3
second Print: 2
second Print: 1

Second Print counts down because for every call you make to kaboom(i+1), that call is being put on the top of a stack of calls. Once i >= 3, the stack stops growing and the calls are being popped off where they left off. So 3 is printed and that execution of kaboom(2+1) finishes. Then the call to kaboom(1+1) resumes where it left off and prints 2 and finishes. Finally kaboom(1) resumes and prints 1.

your function is diving to the farthest call then is coming back and is printing second Print
call 1 --> i = 1 back to call 1 --> second Print, i it is still 1
↓ ↑
call 2 --> i = 2 back to call 2 --> second Print, i it is still 2
↓ ↑
cal 3 --> i = 3 (end of call chain, it goes back)

To understand this you need to understand how recursion works. It works on the concept of stacks. You can have a look at the following link, to get a clear understanding : https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/
You are calling the same function again if i<3, so it's printing first print and so on.. but after it's returned, the execution won't end there right. It has to execute rest of the method, which is second print.

recursion strategy uses stacks which works as Last In First Out. In your case, If I am right, your base condition is satisfied only at 3 and until then it is stored in the stack and then getting printed.

Think of it this way: you create a new occurrence of kaboom every time it is called.
the first time kaboom is called i is one. First is printed and kaboom(2) is called. First is printed and kaboom(3) is called. First is printed and kaboom is not called again because i=3. BUT kaboom(3), kaboom(2), and kaboom(1) are not done yet because they still have to print the second time. Because kaboom(3) was opened most recently it has to close first, hence why second 3 is printed first. Then kaboom(2) prints second 2 and finally kaboom(1) finally finishes by finally printing second 1.

Related

Can somebody explain me this recursion?

def name(n):
if n>0:
name(n-1)
name(n-1)
print(n)
name(5)
How this is generating 1,1,2,1,1,2,3.....so on output? like which function is working first or both working simultaneously and how n is printing like this.
Try with smaller numbers. For example if you run name(1) it will just print 1. becase two functions in the middle will just return. If you write name(2) it will run the first inner funtion, which will print 1(like I said previously). Second function will do the same and last statement will print 2. So the output is 1 1 2. If you go for name(3) it will just the same as name(2) but twice and will print 3 at the end (1 1 2) (1 1 2) 3. name(4) will do name(3) twice and print 4 at end and so on
Another way to lok at this is in reverse. eg. you look at the smallest number:
name(0): Prints nothing, thus ""
name(1): calls name(0) twice, and then prints 1, thus "1"
name(2): calls name(1) twice, and then prints 2, thus "112"
name(3): calls name(2) twice before it prints 3, thus "1121123"
name(4): calls name(3) twice before it prints 4, thus "112112311211234"
name(5): calls name(4) twice before it prints 5, thus "1121123112112341121123112112345"
Finally the clue is that there is no spcial treatment of functions that recurse. Every call to a function, even print, will wait for that to return and then continue on the next line as long as the statement didn't include a return in which it would return. that name(5) ends up calling itself with different versions of n at different levels is no problem because each of them has their own version of n that is unique to that call.
Hello I attached this image that shows explanation in details

How do I set a variable to a index of a list?

l = [1,2,4]
for i in range(3):
a = l[i]
im tryihng to do that above but it isn't working and it says
'builtin_function_or_method' object cannot be interpreted as an integer. can anyone say why this is and tell me how to fix this
edit:There was something earlier in the code before this and it was because i was doing .lower and not .lower() sorry guys
Let's explain what your code does before solving it. Edit available at the bottom of the answer
for i in range(3):
a = l[i]
What this does is creates a "range" of numbers from 0 to 2, however its supposed to go from 1 (or 0) to 3. Why? Computers have been trained to start counting from 0 instead of 1 like a normal human and subsequently they are 1 less. (This is a simplified one, there's a longer one that you'll learn over time)
Now your 2nd line of code assigns the variable a the value of one of the items in the list l. Let's look at what value 'a' would be assigned during this time
1 (1st item)
2 (2nd item)
IndexError: Out of range error (there is no 3rd item)
So how do you solve this? One way is to add more items to your list l.
So let's then add 2 more items into l (3 and 4)
This is our variable l now
l = [1, 2, 3, 4]
Here's our output now
1 (1st item)
2 (2nd item)
3 (3rd item)
As you noticed, it skips the 4th item since we specified to only iterate over 3 items in the list. If you wanted to "iterate over a list" look no further!.
Observe
for i in l:
print(i)
This creates a for loop that goes over each item in the list l one by one from start to finish that allows you to see the current item in the variable i! In our code, it simply prints the variable i each time the for loop goes to the next item in the list.
1
2
3
4
And simply stops once it reaches the end!
Don't worry, we've all been there while learning code :)
UPDATE: Based on what you were saying, I'm assuming if you wanted to assign the variable a the 2nd place in the list 'l' you would use
a = l[1]
Yes to get the 2nd place you need to type 1. The same goes for accessing the 1st item, you change the l[1] with l[0]. This is because computers count from 0 instead of human's traditionally counting from 1
the code you wrote isn't even syntactically correct.
l = [1,2]
for i in range(len(l)):
# you had no colon, so the first error you should have gotten is a syntax error.
# the second error you would have gotten is a value error, because you try to set 'a' to values
# that don't exist. a more dynamic way to do it anyways is to cycle through the
# length of the list.
a = l[i]
im not sure why you want to do this, as it will result in a = 2. staying true to your question, the only reasonable way to do what you're asking is something as easy as this.
a = l[2] # or whatever index you're trying to get
you're method, even if it compiled correctly, would not have accomplished what you say you want.
as mentioned by 'meh' and 'shriakhilc', keep in mind that indexing starts at 0, so the list l would only have indexes of 0 and 1.

What is the output of the loop in python?

This is a loop in PYTHON 3.X.
for i in range(2, 2):
print(i)
The result that I got after running this program was a blank console.
What type of output we get from this loop.
The range of numbers returned are integers from start to stop. ( the first param being start, and second being stop when 2 are given)
It includes the start int, but not the stop int.
hence, range(2,2) contains no numbers in between.
range(2,4) returns 2,3 but not 4.
Documentation here.
The reason you're getting blank output is because what the range() function does.
The first argument in the range() function tells the function which number to iterate to.
So, if this was your code:
for i in range(2):
print(i)
Then your output would be:
0
1
It starts from 0 and prints two numbers, because of the two.
However, the second parameter in your code tells it what to count by. For example, you added a 2 for the second parameter. This tells the program to skip count by 2, and since you have only 2 output in the first place, the program doesn't print anything
Read up on range in python 3.
Hopefully this helps!

Print function calling functions together

I was testing with something and I wrote this code for example purposes.I felt the output I got was weird.I expected that function calls are executed one after the other but according to this code both the print statements are getting executed after each other and then the return values are printed together.What does this mean and what is the flow of the code in this case?
global num
num=5
def demo(num):
num+=1
print("hi")
return(num)
print(demo(num),demo(num))
output-
hi
hi
6 6
I expected that function calls are executed one after the other
That's exactly what happens.
But there's no way the print can happen before the demo calls, because it's trying to print out the values returned by those calls. (You can loosely think of this as a special case of anywhere you see parentheses: 2 * (3+4) can't multiply by 2 until it's added 3+4, and print(demo(num), demo(num)) can't print the results of demo(num) and demo(num) until it's called them. But don't take that too literally.)
So, those demo calls happen left to right, then the print call happens.
In more detail, let's step through how it evaluates this line:
print(demo(num),demo(num))
… Python has to do this:
Evaluate print by looking it up as a builtin name, which finds the builtin print function.
Evaluate the first argument.
Evaluate demo by looking it up as a global name, which finds the global demo function that you defined.
Evaluate num by looking it up as a global name, which finds the global 5 value.
Call the function on the argument.
The parameter num gets the value passed in, 5.
num += 1 updates the local variable (parameters are local variables) num to 6.
print("hi") prints out hi.
return(num) returns the value of the local variable, 6.
Evaluate the second argument.
… same as above, it prints out hi and returns 6.
Call the function returned by evaluating print on the two arguments returned by the two calls, so it prints out 6 6.
If you want the rigorous definition, he details are covered in Calls in the reference documentation. In particular (stripping out irrelevant bits)
call ::= primary "(" [argument_list] ")"
 …
The primary must evaluate to a callable object…. All argument expressions are evaluated before the call is attempted.
according to this code both the print statements are getting executed after each other and then the return values are printed together
Yes. The two function calls have to be executed in order, so that it can get the values to pass to the print function. Executing them prints out Hi twice. Then it has all the values, so it can print them, which prints out 6 6, since both values are 6.
Program evaluation has an order of operations just like arithmetic does. And similarly, it's not always intuitive, especially when we "consume" things left to right, up to down while reading.
So, what gives? Lets become the python interpreter and see why order of operations is important.
# A wild statement appears. Time to compute!
print(demo(num),demo(num))
# I cant't print yet! i'm missing info!
I need to evaluate this first demo(num), and by default im going to do it a closed room away from globals
# evaluating demo(num=5) - num here is a new local variable, it has no relation to the global one defined above
num+=1 # num = 6
print("hi") # [[[PRINT hi]]] ~> to console
return 6 # returns the value 6 filling in another piece of the puzzle
Where are we at now? Almost ready to call this print, just need to do this demo thing again
print(6, demo(num))
# What is num though?
# Well, the only num I know of out here in global space is 5
print(6, demo(5))
# evaluate: demo(5)
This seems familiar!
# evaluating: demo(num=5) - again, a NEW local variable is created just for this function call
num+=1 # num = 6
print("hi") # [[[PRINT hi]]] ~> to console
return 6
Finally, print has all its arguments it needs
print(6, 6) # [[[PRINT 6 6]]] ~> to console
print is not magic, it's just another function! Same as the demo you wrote.
And functions will not evaluate until all their parameters are supplied.
print(a, b) needs the values of a & b before it can do its thing.

Python: Iterating a string with an int(variable) through a function

I'm an absolute beginner and have read many related topics but I just can't get my mind around it.
I try to create a function which iterates through the string s exactly "n" times.
s="hello"
n=2
If I simply type in
s[::n]
it does work, however, if I try to express this in a function everything goes haywire.
My function looks like this:
def printEvery(s,n):
for n in range(len(s)):
print(s[::n])
ValueError: slice step cannot be zero
I really don't get why it doesn't work in a function as in my head it only makes sense this way. I'd deeply appreciate any help.
E: Sorry for the format and thank you for the edit khelwood!
def printEvery(s,n):
for x in range(1, len(s) + 1):
print(s[::n])
printEvery("Hello", 2)
Not quite sure why you would ever need this though
As I already mentioned in the comment, range starts at 0, so you cannot slice a string to return every zero-th element.
Another problem with your function is, that the parameter "n" is immediately overwritten by the for loop, so no matter with what second argument you call printEvery, it will always print the same text. This is equivalent:
def printEvery(text):
for stepsize in range(1, len(text)):
print(text[::stepsize])
def printEvery(text):
for i in range(len(text)+1,1,-1):
print (text[::i])
Every for loop starts at 0
Range's instruction is
range([start], stop[, step])
in which it indicates that where should the number start, then when should it stop and how many steps should it undergo.
In this case, it starts at 11, as I wrote len(text)+1 and I supposed len(text) is 10. I told Python to stop when it reachs 1, and each time it is -1 each time so if you replace
print (text[::i])
#replace this line to this:
print i
This would be printed:
11
10
9
8
7
6
5
4
3
2
1
I hope it works for you. I am not really good at English so sorry for my bad English :)

Categories