This python code is giving the right answer on Pycharm IDE but not on leet code.


  • 0
    S

    for the input [],[2,3] leetcode gives 2 as answer whereas pycharm gives 2.5 which is the right answer, I am not sure where i am going wrong.

    i = 0
    j = 0
    res = []
    c = 0
    m = len(nums1)
    n = len(nums2)
    mn = m+n
    if m == 0:
        if n % 2 != 0:
            return nums2[int(mn / 2)]
        else:
            return ((nums2[int(mn / 2)] + nums2[int(mn / 2) -1])/2)
    if n == 0:
        if m % 2 != 0:
            return nums1[int(mn / 2)]
        else:
            return (nums1[mn / 2] + nums1[(mn / 2) -1])/2
    
    while i < len(nums1) and j < len(nums2):
    
        if (c == int(((mn / 2) + 1))):
            if (m + n) % 2 == 0:
                return (res[c-1] + res[c - 2]) / 2
            else:
                return res[c-1]
    
        if nums1[i] > nums2[j]:
            res.append(nums2[j])
            c += 1
            j += 1
        else:
            res.append(nums1[i])
            c += 1
            i += 1

  • 1
    Z

    The difference between pycharm IDE and the leetcode is the way they treat the expression x/2. In leetcode, when we want to get a float from the expression x/2, we should use x/2.0.
    So, you can get the right answer when you modify your code like "return (res[c-1] + res[c - 2]) / 2" to "return (res[c-1] + res[c - 2]) / 2.0" . And, the same as the expression "return (nums1[mn / 2] + nums1[(mn / 2) -1])/2"


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.