Пользовательская сортировка в массиве с методом, определенным внутри класса - PullRequest
0 голосов
/ 05 апреля 2020

У меня есть такой класс в Python 3:

from typing import List
from functools import cmp_to_key

class Solution:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def cmp(self, v1: int, v2: int) -> int:
        if (v1 < v2):
            return -1
        elif (v1 == v2):
            return 0
        elif (v1 > v2):
            return 1

    def moveZeroes(self, nums: List[int]) -> None:
        nums.sort(key = cmp_to_key(cmp))

Мне нравится вызывать метод moveZeros следующим образом:

p1 = Solution("John", 36)

nums = [0,7, 2, 3, 4, 5,0,9]

p1.moveZeroes(nums);
print(nums)

И получаю эту ошибку:

name 'cmp' is not defined
Stack trace:
 >  File "E:\LeetcodePython\LeetcodePython\Solution.py", line 20, in moveZeroes
 >    nums.sort(key = cmp_to_key(cmp))
 >  File "E:\LeetcodePython\LeetcodePython\Solution.py", line 28, in <module>
 >    p1.moveZeroes(nums);
Loaded '__main__'
Loaded 'runpy'
Traceback (most recent call last):
  File "C:\Python38\lib\runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Python38\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy\__main__.py", line 45, in <module>
    cli.main()
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy/..\debugpy\server\cli.py", line 361, in main
    run()
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy/..\debugpy\server\cli.py", line 203, in run_file
    The thread 'MainThread' (0x1) has exited with code 0 (0x0).
runpy.run_path(options.target, run_name="__main__")
  File "C:\Python38\lib\runpy.py", line 263, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "C:\Python38\lib\runpy.py", line 96, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "C:\Python38\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "E:\LeetcodePython\LeetcodePython\Solution.py", line 28, in <module>
    p1.moveZeroes(nums);
  File "E:\LeetcodePython\LeetcodePython\Solution.py", line 20, in moveZeroes
    nums.sort(key = cmp_to_key(cmp))
NameError: name 'cmp' is not defined
The program 'python.exe' has exited with code 1 (0x1).

Но, если я просто переместу функцию cmp из класса, она будет найдена идеально:

from typing import List
from functools import cmp_to_key

def cmp(v1: int, v2: int) -> int:
    if (v1 < v2):
        return -1
    elif (v1 == v2):
        return 0
    elif (v1 > v2):
        return 1

class Solution:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def moveZeroes(self, nums: List[int]) -> None:
        nums.sort(key = cmp_to_key(cmp))

########################################################################
p1 = Solution("John", 36)

nums = [0,7, 2, 3, 4, 5,0,9]

p1.moveZeroes(nums);
print(nums)

Но мне нравится иметь функцию сравнения внутри класса так что код может быть более понятным.

Есть ли способ в python 3?

1 Ответ

0 голосов
/ 05 апреля 2020

Спасибо, @ Марк Майер за вашу помощь.

Я могу вызвать функцию сравнения следующим образом -

nums.sort(key = cmp_to_key(self.cmp))

Итак, полный код -

from typing import List
from functools import cmp_to_key

class Solution:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def cmp(self, v1: int, v2: int) -> int:
        if (v1 < v2):
            return -1
        elif (v1 == v2):
            return 0
        elif (v1 > v2):
            return 1

    def moveZeroes(self, nums: List[int]) -> None:
        nums.sort(key = cmp_to_key(self.cmp))

p1 = Solution("John", 36)

nums = [0,7, 2, 3, 4, 5,0,9]

p1.moveZeroes(nums);
print(nums)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...