Reputation:
I was trying a simple recursive problem in python and was stumped by the for-loop-esq implementation in python. The implementation uses the range(x,y,z) function.
Here is the code in python:
num = 25
f1 = 0
f2 = 1
for num in range(1,num,1):
num = f1 + f2
f1 = f2
f2 = num
print("num is : ", num)
Same code in java:
int num = 25;
int f1 = 0;
int f2 = 1;
for(int i = 1; i < num; i++){
num = f1 + f2;
f1 = f2;
f2 = num;
}
System.out.println("# at 25 is : " + num);
The java implementation will never spit out the right answer (75025) because num
is overwritten in the first line of the for-loop (num = f1 + f2
).
Where as in python, the code executes and delivers the right answer. How come? Does python implement some sort of i
counter under the hood?
I'm using the pyCharm debugger to test this.
Upvotes: 1
Views: 6421
Reputation: 1
My guess is that the function in range(1, num, 1)
only sees something like this in range(1,25,1)
or in other word it is function with arguments passed by value.
The return value of the function range should be something like [1,2,3 ...25]
.
Upvotes: 0
Reputation: 190
I believe the difference is that the range function in Python has arguments passed by value. So even after you give the num variable a new value, the function still holds on to the 25 you gave it originally, and thus iterates 25 times.
In Java the loop is checking the value of num after every iteration to see when to stop. Since the value of num changed to 1 during the first iteration, it met the criteria to stop the loop, so it only iterates one time.
I hope that makes sense!
Upvotes: 2
Reputation: 1750
In the first iteration of the for loop, you set num to 1 (num = f1 + f2
). Since num
is used in your loop condition, the loop will stop after the first iteration. To get it working the same way as the python code you will need another variable and keep num
at 25
int num = 25;
int f1 = 0;
int f2 = 1;
int res = 0;
for (int i = 1; i < num; i++) {
res = f1 + f2;
f1 = f2;
f2 = res;
}
System.out.println("# at 25 is : " + res);
Upvotes: 1