Why do I get a different result in Leetcode compared to python console?

Question:

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.

Asked By: and_noob

||

Answers:

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

Answered By: ComplexOperator
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.