1

Leetcode problem : https://leetcode.com/problems/eliminate-maximum-number-of-monsters/

My Python solution is below:

class Solution(object):
    def eliminateMaximum(self, dist, speed):
        """
        :type dist: List[int]
        :type speed: List[int]
        :rtype: int
        """
        mapped = []
        killed = 0
        for i, v in enumerate(zip(dist, speed)):
            mapped.append([v[0]/v[1], v[0], v[1]])
            mapped.sort(key=lambda x: x[0])
        iterator = iter(mapped)
        while True:
            try:
                next(iterator)[1] = -1
                killed += 1
            except StopIteration:
                return killed
            for v in mapped[killed:]:
                v[1] = v[1]-v[2]
                if v[1] <= 0:
                    return killed

sol = Solution()
r = sol.eliminateMaximum([4,8,6,8,2,7,4], [1,3,3,1,10,1,1])
print(r)

The output of Python console is 4 (as expected), but that of Leetcode is 2, which is the wrong answer.

Ankit_M
  • 276
  • 1
  • 3
  • 15
and_noob
  • 33
  • 5
  • 3
    On Leetcode you run the code with python2 (the deafult python version on the site), if you run it with python3 you will get 4. Looking at your code the problem would be that in python 2 `/` is floor (or integer) division, i.e. always returns int – buran Apr 01 '23 at 12:46
  • 3
    Does this answer your question? [Integer division in Python 2 and Python 3](https://stackoverflow.com/questions/21316968/integer-division-in-python-2-and-python-3) – buran Apr 01 '23 at 12:48
  • Thanks a lot) I haven't thought about it before) – and_noob Apr 01 '23 at 13:43

1 Answers1

1

Python uses python2, in which integer division is different from python3. You can see the language info here:

enter image description here

enter image description here

enter image description here

When choosing python3, it works.

I ran this code:

class Solution:
    def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:
        mapped = []
        killed = 0
        for i, v in enumerate(zip(dist, speed)):
            mapped.append([v[0]/v[1], v[0], v[1]])
            mapped.sort(key=lambda x: x[0])
        iterator = iter(mapped)
        while True:
            try:
                next(iterator)[1] = -1
                killed += 1
            except StopIteration:
                return killed
            for v in mapped[killed:]:
                v[1] = v[1]-v[2]
                if v[1] <= 0:
                    return killed

And it perfectly ran enter image description here

preemptible
  • 161
  • 5