Python - Feedback Appreciated


  • -1
    K

    This works, but I feel like it could be better. Any tips/feedback?

    class Solution:
        def dominantIndex(self, nums):
            largest = max(nums)
            completed = False
            half = largest/2
            
            for x in nums:
                print(x)
                if x == largest:
                    continue
                elif half < x:
                    return -1
                    completed = True
                    break
            if completed != True:
                print(nums.index(largest))
                return nums.index(largest)
    

  • 1

    @kcheng0222 Can be shortened much more:

    class Solution(object):
        def dominantIndex(self, nums):
            largest = max(nums)
            return nums.index(largest) if all([largest == num or num * 2 <= largest for num in nums]) else -1
    

  • 0
    K

    here's my one liner:
    return nums.index(max(nums)) if all([max(nums) >= 2 * num or num == max(nums) for num in nums]) else - 1


  • 1

    @krsnik93 BTW that's O(n^2) because you're doing max() in every loop


  • 1
    H

    @yangshun your answers are always sublime


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.