0

I was solving some algorithm problems and in one of the solutions saw this expression, but can't figure out what does.

return [b, a][nums.count(a) > len(nums)//2]

In case the whole code is needed

def majorityElement6(self, nums):
    if not nums:
        return None
    if len(nums) == 1:
        return nums[0]
    a = self.majorityElement(nums[:len(nums)//2])
    b = self.majorityElement(nums[len(nums)//2:])
    if a == b:
        return a
    return [b, a][nums.count(a) > len(nums)//2]
mkrieger1
  • 10,793
  • 4
  • 39
  • 47
Luis Miranda
  • 1
  • 1
  • 1
  • 1
    There are more than half the amount in nums is a, return a; else return b – Jason Yang Jul 19 '20 at 22:49
  • 1
    It creates a list with two elements, then indexes into that list with an expression that always produces 0 or 1 (thus being a valid index for the list). – jasonharper Jul 19 '20 at 22:49
  • `[b, a]` is a list with two elements, meaning that the valid indices are 0 and 1. `nums.count(a) > len(nums//2)` is a boolean expression that can be either `True` or `False`. I 'll let you figure out the rest. – mkrieger1 Jul 19 '20 at 22:52
  • 1
    Maybe this is written like that for historical reasons, see https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator – mkrieger1 Jul 19 '20 at 22:55

1 Answers1

0

A comparison like > returns a boolean, where False == 0 and True == 1.

The clearer way to write this is as a conditional expression:

return a if nums.count(a) > len(nums)//2 else b
wjandrea
  • 16,334
  • 5
  • 30
  • 53