1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Why do I get NameError when calling my own method in a Python class?

Discussão em 'Python' iniciado por Stack, Setembro 16, 2025.

  1. Stack

    Stack Membro Participativo

    I’m trying a LeetCode hard problem about arrays and medians. I wrote a Python class with a method to solve it and wanted to use recursion in it. i read about this type of algoriths here Medium but after understanding and following each instruction and try it on Leetcode it seems there is an error im trying to figure out.

    here is my code

    class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
    n1, n2 = len(nums1), len(nums2)
    if n1 > n2:
    return findMedianSortedArrays(nums2, nums1)

    n = n1 + n2

    left = (n1 + n2 + 1) // 2
    low, high = 0, n1

    while low <= high:
    mid1 = (low + high) // 2
    mid2 = left - mid1

    l1, l2, r1, r2 = float('-inf'), float('-inf'), float('inf'), float('inf')

    if mid1 < n1:
    r1 = nums1[mid1]
    if mid2 < n2:
    r2 = nums2[mid2]
    if mid1 - 1 >= 0:
    l1 = nums1[mid1 - 1]
    if mid2 - 1 >= 0:
    l2 = nums2[mid2 - 1]

    if l1 <= r2 and l2 <= r1:
    if n % 2 == 1:
    return max(l1, l2)
    else:
    return (float(max(l1, l2)) + float(min(r1, r2))) / 2.0

    elif l1 > l2:
    high = mid1 - 1
    else:
    low = mid1 + 1
    return 0


    here is the error it show me on the terminal

    NameError: global name 'findMedianSortedArrays' is not defined
    return findMedianSortedArrays(nums2, nums1)
    Line 5 in findMedianSortedArrays (Solution.py)
    ret = Solution().findMedianSortedArrays(param_1, param_2)
    Line 69 in _driver (Solution.py)
    _driver()
    Line 83 in <module> (Solution.py)


    i tried already deleting the function name and i just leave return (nums2, nums1) but now it show me as wrong answer:

    Input
    nums1 = [1,3]
    nums2 = [2]
    Output
    [[2.00000],[1.00000,3.00000]]
    Expected
    2.00000


    Not sure where the bug might be but based on leetcode terminal i know this is on that specific line of n1 > n2: return findMedianSortedArrays(nums2, nums1) but based on what i did it was supposed to worked out. I will appreciate any help.

    Continue reading...

Compartilhe esta Página