In Python we do for loop like:
for i in range(len(nums))
In java: we have:
for (int i = 0; i < nums.length; i++)
Are these two for loop identical? If we made some change within the for loop, let's say in the for loop i has been plus 3, for Java, next i in for loop will be 4? while Python still start i from 2
Leetcode 594. Longest Harmonious Subsequence.
We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1
The solution written in Java as follow:
nums=[1,3,2,2,5,2,3,7]
public class Solution {
public int findLHS(int[] nums) {
Arrays.sort(nums);
int prev_count = 1, res = 0;
for (int i = 0; i < nums.length; i++) {
int count = 1;
if (i > 0 && nums[i] - nums[i - 1] == 1) {
while (i < nums.length - 1 && nums[i] == nums[i + 1]) {
count++;
i++;
}
res = Math.max(res, count + prev_count);
prev_count = count;
} else {
while (i < nums.length - 1 && nums[i] == nums[i + 1]) {
count++;
i++;
}
prev_count = count;
}
}
return res;
}
}
I converted to Python:
nums=[1,3,2,2,5,2,3,7]
nums=sorted(nums)
prev_count=1
res=0
i=0
for i in range(len(nums)-1):
count=1
if i>0 and nums[i]-nums[i-1]==1:
while i<len(nums)-1 and nums[i] == nums[i+1]:
count+=1
i+=1
res=max(res,count+prev_count)
prev_count=count
else:
while i<len(nums)-1 and nums[i] == nums[i+1]:
count+=1
i+=1
prev_count=count
print (res)
In Java
for (int i = 0; i < nums.length; i++) {
int count = 1;
if (i > 0 && nums[i] - nums[i - 1] == 1) {
while (i < nums.length - 1 && nums[i] == nums[i + 1]) {
count++;
i++;
}
i++ inside for loop so the i started from whatever i has been added.
In Python:
for i in range(len(nums)-1):
count=1
if i>0 and nums[i]-nums[i-1]==1:
while i<len(nums)-1 and nums[i] == nums[i+1]:
count+=1
i+=1
after i+=1, it only applied to While loop, for loop still start from i=2 not 4 instead.
Java returns answer as 5 while python is 4. I debug the code and looks like Java start i for whatever i has been added while Python didn't take added i and always start for last i.
In java the for loop semantics are borrowed from C.
for (<initilization>; <termination condition>; <what to do in after each iteration>)
Do something at the start(intialization), after that until some condition is reached (termination condition), do something to make progress (what to do after each iteration). The idiomatic for-loop with i
works because the state of the iteration is maintained within i
. So if you make changes to i
in the body of the loop, the state of iteration also changes.
The python syntax is akin to the bash
loops:
for i in some_iterable:
Here i
takes on each of the values from the some_iterable
and the loop runs once for each value of i
. If you change i
within the body of the loop, doesn't matter; i
is assigned the next value from the iterable during the next iteration. The state of the loop is maintained in the iterable, not i
. i
is just what lets you access the current value of the iterable.