Skip to content
Advertisement

Updating a variable inside the for loop is not working

in this below code, I am trying to update rsum value to (rsum – lsum – nums[i]) inside for loop, it’s giving me the wrong output. But if I declare a new variable name and assign (rsum – lsum – nums[i]) value to that, it gives me the right output. What’s the reason behind this?

  1. Code that gives wrong output

    def pivotIndex(nums: List[int]) -> int:
        n = len(nums)
    
        if n == 1: return 0
    
        lsum = 0
        rsum = sum(nums)
    
        for i in range(n):
            rsum = rsum - lsum - nums[i]
            if lsum == rsum:
                return i
    
            lsum += nums[i]
    
        return -1
    
  2. Code that gives me the right output

    def pivotIndex(nums: List[int]) -> int:
        n = len(nums)
    
        if n == 1: return 0
    
        lsum = 0
        rsum = sum(nums)
    
        for i in range(n):
            total = rsum - lsum - nums[i]
            if lsum == total:
                return i
    
            lsum += nums[i]
    
        return -1
    

Advertisement

Answer

On line 11 where you are getting the wrong output, you are changing rsum’s value each so when you do (rsum-lsum-num[i]), you will get the new rsum value from which we’ll remove lsum and num[i]. When you will be checking lsum == rsum it may be true once but than as rsum’s value will have changed, it may not be equal.

On the code where you are getting the correct input, rsum will remain the same, which is sum(nums) and you will each time remove lsum and nums[i].

I don’t know if I’m clear enough, and if I’m not, please tell me.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement