3

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.

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Python for-loops are essentially the same as Java's enhanced for-loops. For your example, since range(len(nums)) returns [0, 1, 2, ...], these two are more or less equivalent:

Python:

    array = [0, 1, 2, 3, 4, 5, 6]
    for i in array:
        // i represents each item in the array

Java:

    int[] array = {0, 1, 2, 3, 4, 5, 6};
    for (int i : array) {
        // i represents each item in the array
    }

Comments

1

This does not work in python - the i is "reset" every time it gets back to the for i in .... :

for i in range(20) :
   print(i)    # prints i
   i += 99     # has no influence over the next iterations i
   print(i)    # prints (i + 99) 

A way to solve it in python would be:

from collections import Counter

nums=[1,3,2,2,5,2,3,7]

c = Counter(nums)

# create possible keys from c that are 1 apart
one_apart_keys = [ (a, a+1) for a in c if a+1 in c]     

# get the key that has the max value of counts
# will pick first one if multiple equals possible
max_key = max(one_apart_keys, key = lambda x: c[x[0]]+c[x[1]]) 

# get all the numbers in order from list
collec = [x for x in nums if x in max_key]  

print(collec)

# c is                Counter({2: 3, 3: 2, 1: 1, 5: 1, 7: 1})
# one_apart_keys is   [(1, 2), (2, 3)]
# max_key is          (2, 3)

Output:

[3, 2, 2, 2, 3]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.