-4

When I try to compare the current state of j and nums[i+1], it says "List index out of range". But I saw the other post did the same and worked compare current item to next item in a python list Why?

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        nums.sort()
        
        count = -1
        for i,j in enumerate(nums):
            count += 1
            if count > len(nums) / 2:
                return nums[i]
            if j != nums[i+1]:
                count = 0
jason
  • 3
  • 1
  • 2
    Probably because the other post does something different from what you've done. You enumerate `nums`, it enumerates `mylist[:-1]`. The variable name is irrelevant, but what does that `[:-1]` thing do...? – ChrisGPT was on strike Jul 12 '20 at 18:00
  • @Chris No need to be sarcastic mate. It is an easy thing to overlook for a beginner – kyriakosSt Jul 12 '20 at 18:02
  • 1
    @kyriakosSt, I'm not being sarcastic. Getting OP to ask that question, and find the answer, is likely going to stick with them a lot better than somebody just telling them what's wrong. That's basically the fundamental skill in programming. I've slightly adjusted the wording. Do you find this less offensive now? – ChrisGPT was on strike Jul 12 '20 at 18:03

2 Answers2

3

You can go through the algorithm step by step. What does it do? It iterates over a list of numbers and compares them with their right neighbor (nums[i+1]).

The problem is the last element in the list. There is no right neighbor. Therfore, the requested index is out of range.

The answer you mentioned, therfore, iterates over all elements except the last one (nums[:-1])

Querenker
  • 2,242
  • 1
  • 18
  • 29
2

You have to use this: enumerate(nums[:-1])
Because you are comparing j and num[i+1] and i+1 would be out the the range.

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        nums.sort()
        
        count = -1
        for i,j in enumerate(nums[:-1]):
            count += 1
            if count > len(nums) / 2:
                return nums[i]
            if j != nums[i+1]:
                count = 0
fro
  • 402
  • 3
  • 8