-2

I cannot figure out, why the exact same Python code is giving different results in Java. I mean is there any difference in the array handling of the two languages or something that I am missing in the following codes.

In the following codes (i.e., trying to solve https://leetcode.com/problems/unique-paths/), java gets accepted while Python gets rejected. I checked out for possible failure cases: for uniquePaths(7,3) Python is returning result 7 but Java is returning 28 (which is the correct answer).

I tried to debug and find for any possible differences in the code that's causing the difference, but no luck.

Can anyone please provide some insight for such behavior or any mistake on my implementation? Thank you

** Java Code** ::

class Solution {
    public int uniquePaths(int m, int n) {
        int[][] dp = new int[m+1][n+1];


        return pathHelper(1,1,m, n, dp);
    }

    private int pathHelper(int loc_x, int loc_y, int m, int n, int[][] dp){
        if(loc_x==m && loc_y==n)return 1;

        if(loc_x >m || loc_y>n)return 0;

        if(dp[loc_x][loc_y] != 0)return dp[loc_x][loc_y];

        int count = pathHelper(loc_x + 1, loc_y, m, n, dp) + pathHelper(loc_x, loc_y+1, m, n, dp) ;

        dp[loc_x][loc_y] = count;

        return count;


    }
}

Python Code ::

class Solution(object):
    def uniquePaths(self, m, n):
        dp = [[0]*(n+1)]*(m+1)

        return self.pathHelper(1,1,m, n, dp)

    def pathHelper(self, loc_x, loc_y,  m, n, dp):
        if(loc_x==m and loc_y==n):
            return 1

        if(loc_x >m or loc_y>n):
            return 0


        if(dp[loc_x][loc_y] != 0):
            return dp[loc_x][loc_y]

        count = self.pathHelper(loc_x + 1, loc_y, m, n, dp) + self.pathHelper(loc_x, loc_y+1, m, n, dp)

        dp[loc_x][loc_y] = count

        return count

Code01
  • 37
  • 6
  • Variable and function names should follow the `lower_case_with_underscores` style. The parentheses around the if statements are unnecessary (I suggest using some kind of linter, they're great). What are the 0 and 1 return values meant to indicate? – AMC Dec 30 '19 at 02:02

1 Answers1

2

dp = [[0]*(n+1)]*(m+1) is not the correct way to define a 2D list in Python. Use this instead: dp = [[0]*(n+1) for _ in range(m+1)]

Julien
  • 13,986
  • 5
  • 29
  • 53