Home > Blockchain >  Issues with list comprehensions
Issues with list comprehensions

Time:11-26

My goal was to create a method that would take an array as parameter, and output the sum of the min() value of each of its subarrays. However, I really don’t understand what’s wrong with my list comprehension.

class Solution(object):
    def sumSubarrayMins(self, arr):
        s = 0
        self.subarrays = [arr[i:j] for i in range(j-1,len(arr))for j in range(1,len(arr) 1)]
        for subarray in self.subarrays:
            s  = min(subarray)
        return s

sol = Solution()
sol.sumSubarrayMins([3,1,2,4])

I often try debugging with python tutor but it is really no help in this case.

CodePudding user response:

Your subarray calculation logic is wrong. You are trying to use j in the first loop, before you define it. Try this:

self.subarrays = [arr[i:j] for i in range(0, len(arr)) for j in range(i 1, len(arr) 1)]
  • Related