Update & Sum Queries – IntegerList

Update & Sum Queries – IntegerList: The program must accept a list of integers and Q queries as the input. For each query, the program must perform the operation based on the following conditions.
– If the query type is 1, then the program must update the integers in the given range by adding the given value.
– If the query type is 2, then the program must print the sum of integers in the given range.

Your task is to define the class IntegerList so that the program runs successfully.

The calling code Hello.py is as given below.

from integerlist import IntegerList

numList = IntegerList(list(map(int, input().strip().split())))
Q = int(input().strip())
for ctr in range(Q):
    query = input().split()
    queryType = int(query[0])
    if queryType == 1:
        left, right, val = map(int, query[1:])
        numList.updateRange(left, right, val)
    elif queryType == 2:
        left, right = map(int, query[1:])
        print(numList.getSum(left, right))

Example Input/Output 1:
Input:
10 20 30 40 50 60
5
1 2 4 5
2 1 3
1 1 6 -5
2 1 6
2 2 4

Output:
70
195
90

Explanation:
The given list of integers are 10 20 30 40 50 60.
Query 1: After updating the integers in the range(24) by adding 5, the integers become 10 25 35 45 50 60.
Query 2: The sum of integers in the range(13) is 70 (10+25+35).
Query 3: After updating the integers in the range(16) by adding -5, the integers become 5 20 30 40 45 55.
Query 4: The sum of integers in the range(16) is 195 (5+20+30+40+45+55).
Query 5: The sum of integers in the range(24) is 90 (20+30+40).

Example Input/Output 2:
Input:
12 10 10 10 15 15 15 10 12
8
1 1 4 -10
2 1 4
1 5 8 10
2 5 8
1 3 6 -20
2 1 9
1 1 9 5
2 1 9

Output:
2
95
29
74

class IntegerList:
    def __init__(self,numList):
        self.numList = numList

    def updateRange(self,left,right,val):
        for index in range(left-1,right):
            self.numList[index]+=val

    def getSum(self,left,right):
        return sum(self.numList[left-1:right])
Previous Article

function splitEvenLengthWords

Next Article

Print Vowels and Consonants

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *