MO 's Algorithm (Query Square Root Decomposition) | Set 1 (Introduction) | Function that accepts array and list of queries and print sum of each query ; Traverse through each query ; Extract left and right indices ; Compute sum of current query range ; Print sum of current query range ; Driver script
def printQuerySum ( arr , Q ) : NEW_LINE INDENT for q in Q : NEW_LINE INDENT L , R = q NEW_LINE s = 0 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT s += arr [ i ] NEW_LINE DEDENT print ( " Sum ▁ of " , q , " is " , s ) NEW_LINE DEDENT DEDENT arr = [ 1 , 1 , 2 , 1 , 3 , 4 , 5 , 2 , 8 ] NEW_LINE Q = [ [ 0 , 4 ] , [ 1 , 3 ] , [ 2 , 4 ] ] NEW_LINE printQuerySum ( arr , Q ) NEW_LINE