What is the output of following function when head node of following linked list is passed as input?
1->2->3->4->5
def fun(head):
if(head==None):
return
if head.get_next().get_next()!= None:
print(head.get_data()," ", end='')
fun(head.get_next())
print(head.get_data()," ",end='')
There is a call to print(head.get_data()," ",end='') before AND after the recursive call to fun(head.get_next()). The first print is on line 5 in the if block, and the second print is on line 7 outside of the if block.
When on the first node, this means the function will first print 1, then perform the recursive calls, then print 1 again. So we should expect the output to be:
1 [output of recursive call on second node] 1
When on the second and third nodes, the same thing happens; so the output of the call on the second node is:
2 [output of recursive call on third node] 2
Therefore we should expect the output on first node to be:
1 2 [output of recursive call on third node] 2 1
Same thing happens on node 3, so we should expect the output on first node to be:
1 2 3 [output of recursive call on fourth node] 3 2 1
During the call on the fourth node, the if block is not executed, because head.get_next().get_next() is None. Hence the first print and the recursive call don't happen. So we're left with just one print, which means the output of the call on fourth node is just 4.
Finally, putting all that together we can see that the output of the call on first node is:
1 2 3 4 3 2 1
A nice way to think of what is happening is to imagine a "call stack". The call to fun on the first node results in:
print 1 { TO DO }
recursive call on second node { TO DO }
print 1 { TO DO }
When the recursive call is performed, execution of the function is interrupted while waiting for the end of the recursive call. Hence the new call is "stacked" on top of the previous, unfinished, call. So the first layer of the stack is now:
print 1 { DONE}
recursive call on second node { IN PROGRESS }
print 1 { TO DO }
And a new layer is put on top:
print 2 { TO DO}
recursive call on third node { TO DO }
print 2 { TO DO }
As recursive calls progress, new layers are put on the call stack, with the first print becoming {DONE} and the last print remaining {TODO}.
Once the call on the first node terminates, it is unstacked. So the call on the third node is on top again; its remaining print 3 instruction is executed, then it is unstacked; now the call on the second node is on top again; its remaining print 2 is executed, then it is unstacked; the call to first node is on top again; its remaining print 1 is executed; finally, the call on the first node is unstacked, and the call stack is empty, meaning that execution of the whole program is finished.
Related
I've been assigned a task to create a circular linked list in Perl with given arguments, without using arrays or hashes to store the data, only using references. The first element in the structure has a value of 0, irrelevant to the input of the user. It should also support the traversal of the current chosen element using '-' and '+'. The output of the program always starts from the pre-defined element, with the value of 0. So the result should be like this:
./task.pl 3 2 1
0 3 2 1
./task.pl A D - B C + E
0 A B C D E
./task.pl A - B
0 B A
The current code I came up with is :
#!/usr/bin/perl
use strict;
use warnings;
my #elements = #ARGV;
my ($first, $last);
$first = { value => '0', 'prev' => $first, 'next' => $first };
my $pointer = \$first;
for (#elements) {
if ($_ == '-') {
} elsif ($_ == '+') {
} else {
$_ = $pointer->{'next'};
$_ = { value => "$_", 'prev' => $pointer, 'next' => undef};
$pointer = \$_;
$last = $_;
}
}
I am not sure how to proceed further with this, also no imports like Class::Struct can be used.
First of all, you are using a hash. {} creates a hash and returns a reference to it. THIS IS CORRECT. The hash is being used as a struct/class, which isn't what the assignment wants you to avoid.
Secondly, you have $first and $last and a bogus initial element. All of that is wrong. You just need my my $pointer;, although I would call it my $current;.
Thirdly, you use references to scalars (\$var). This is not useful here. The references to the hashes returned by {} are sufficient.
On to the code. There are three different components: Inserting the first element, + and -, insertions, and printing the list that was built.
Inserting the first element
The first argument is special. It can't be + and -. Other insertions always insert after another element, but that's not the case for the first insertion.
In short, we create a list that consists entirely of a node whose value is the first element.
We used undef to indicate a non-existent node.
my $pointer = { value => shift(#elements), prev => undef, next => undef };
+ and -
+ and - change the current node (as indicated by $pointer).
If + is received, you want $pointer to the point to the node to which the current node's prev field points.
If - is received, you want $pointer to the point to the node to which the current node's prev field points.
You always have to ask yourself if there's a special cases, and there is one for each of + and -. There could be an attempt to reach a node before the first (A - -), and there could be an attempt to reach a node after the last (A +). You should die if an attempt is made to reach a non-existent node.
Insertions
We always insert after the current node (the one $pointer references).
Again we ask ourselvves if there's a special case (like trying to use - when already at the first node). But there are none. $pointer will always point to a valid node.
After inserting a node in the list, we want to make $pointer reference the newly created/inserted node.
Printing the list
We want to print the entire list from start to end, so we will need to start by finding the start of the list. This is the same operation as - applied repeatedly until the first node is found. (The first node is the one which has no previous node.)
Then, it's just a question of traversing the list in the other direction (like + does), printing the values as you go along.
I have a method called fibs_rec that results in an unexpected output:
def fibs_rec(n)
if n == 1 || n == 0
return 1
else
a = fibs_rec(n-1) + fibs_rec(n-2)
puts a
return a
end
end
fibs_rec(5)
The call fibs_rec(5) should return 1,1,2,3,5 but here is the actual output:
2
3
2
5
2
3
8
Not only is the output incorrect, it lacks a number from the beginning.
Can someone explain why is this happening?
This is correct since your recursion is splitting into two sub-problems every time it recurses. If you want the series to appear properly then you should try doing this via dynamic programming for O(n) time complexity. As is, the first and second position won’t be printed because of the base case in the recursion.
As for the incorrect answer, it seems you have not accounted for the sequence starting with 0 index. Either find 4 index in the function which will give the fifth element or modify your function to work with position instead of index.
What is going on here? I didn't understand how we got that output.
for (var i = 1; i <=4; i++) {
(function(j) {
setTimeout(function() {
console.log(j);
},j*1000);
})(i)
}
// output: undefined, log 1, 2, 3, 4 with a second interval.
for (var i = 1; i <=4; i++) {
...
}
makes a loop that iterates four times. The value of i is 1 in the first iteration, then 2, then 3, then 4.
(function(j) {
...
})(i)
creates an anonymous function with one parameter, j, and immediately invokes it by passing the value i. This is called IIFE, and you can read more about it at What is the (function() { } )() construct in JavaScript?. As a result, j is the value of i, but it will not change as i changes.
setTimeout(function() {
...
},j*1000);
sets a timeout for a certain number of milliseconds, and execute the function when the timeout expires. Note that setTimeout exits immediately, it only schedules the function to be executed later. In JavaScript world, this is called asynchronous execution.
console.log(j);
prints 1, 2, 3 or 4 on the console. Remember that due to setTimeout, this will happen 1, 2, 3 or 4 seconds later.
As a result, for executes almost instantaneously, as the only job it does is to schedule four functions for the future. The value of this execution is undefined, which is what will be printed to the console if you execute the snippet there. 1000ms after the snippet exits, the first scheduled function is triggered, and prints the value of its local variable j (which is 1). 2000ms after the loop (1 second after 1 is printed), the next scheduled function is executed, printing 2. This happens two more times.
I created a recursive function that tries to parse the information from the parsed list. It's kind of hard to explain, but it's something like
In a parse function that parses either a wikipedia Movie page or an Actor page, starts by parsing a filmography list from a wikipedia actor page -> call the same function on the parsed list -> repeat
I set a global variable that counts the number of iterations, but when I try to break out from the function and move on to the next step by doing,
if $counter > 10
return nil
end
but it does not immediately ends since there are still functions to be called left (since it's recursive). I tried to use "abort" but this one just terminated the program instead of moving on to the next one.
Is there a way to immedately stop the recursive run and move on to the next step without aborting the program?
A bit hard to answer without more code. But i guess you looking for next or break to jump out of recursiveness.
next
Jumps to the next iteration of the most internal loop. Terminates execution of a block if called within a block (with yield or call returning nil).
for i in 0..5
if i < 2 then
next
end
puts "Value of local variable is #{i}"
end
Result:
Value of local variable is 2
Value of local variable is 3
Value of local variable is 4
Value of local variable is 5
break
Terminates the most internal loop. Terminates a method with an associated block if called within the block (with the method returning nil).
for i in 0..5
if i > 2 then
break
end
puts "Value of local variable is #{i}"
end
Result:
Value of local variable is 0
Value of local variable is 1
Value of local variable is 2
def add_one(number)
number + 1
end
puts add_one(5)
def add_two(number)
number = add_one(number)
add_one(number)
end
puts add_two(3)
Hello. I completely understand the first method. However, I am now trying to understand combining methods as we can see from method add_two. I am clueless to how the second method can return 5?
From my knowledge, we call the method add_two and pass the number '3' into the argument. From there we get one local variable number with the object 3. From there I do not understand how we can include the add_one method when we haven't defined it below? Can someone walk me through the second method?
Let me help you understand my logic by breaking the components down below:
first method:
add_one(5)
5 + 1 = 6
second method:
add_two(3)
3 = number + 1
number + 1
Am I right by thinking of the second method like this above?
In add_two method, the line number = add_one(number) overrides the value in number with the result of add_one(number):
For example, when you call add_two(3), this happens:
number = add_one(number)
number = add_one(3)
number = 4
On the second line you call add_one again, but with the modified number, that is, it no longer has value 3 it is now 4, as it was overwritten in previous line.
So second line add_one(number) becomes add_one(4), thus the result is 5.
your interpretation of the second function is incorrect.
second method:
add_two(number(3))
number = number(3) + 1 #=> 4
number(4) + 1 #=> 5
the first line in the second function is processed as add_one(number) store result at number so number after that line is now 4 not 3
the second line is processed as add_one(number) and return result which is 5