Home > Blockchain >  Updating a variable inside the for loop is not working
Updating a variable inside the for loop is not working

Time:03-20

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
    

CodePudding user response:

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.

  • Related