
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find out the sum of evenly spaced elements in an array in Python
Suppose, there is an array 'nums' of size n containing positive integers. We have another array 'queries' that contain integer pairs (pi, qi). For every query in the array queries, the answer will be the sum of numbers in the array nums[j] where pi <= j < n and (j - pi) is divisible by qi. We have to return the answer of all such queries, and if it is a large value, we return the answer modulo 10^9 + 7.
So, if the input is like nums = [2, 3, 4, 5, 6, 7, 8, 9, 10], queries = [(2, 5), (7, 3), (6, 4)], then the output will be [13, 9, 8].
To solve this, we will follow these steps −
A := nums
Q := queries
n := length of nums
M := 10^9 + 7
m := integer value of (n ^ 0.5) + 2
P := a new list containing the list A m times
for i in range 1 to m, do
for j in range n-1 to -1, decrease by 1, do
if i+j < n, then
P[i, j] := (P[i, j]+P[i, i+j]) modulo M
for each value b, k in Q, do
if k < m, then
return [value from index P[k, b]]
otherwise
return [sum(A[b to k]) modulo M]
Example
Let us see the following implementation to get better understanding −
def solve(A, Q): n, M = len(A), 10**9+7 m = int(n**0.5)+2 P = [A[:] for _ in range(m)] for i in range(1,m): for j in range(n-1,-1,-1): if i+j < n: P[i][j] = (P[i][j]+P[i][i+j]) % M return [P[k][b] if k < m else sum(A[b::k]) % M for b, k in Q] print(solve([2, 3, 4, 5, 6, 7, 8, 9, 10], [(2, 5), (7, 3), (6, 4)]))
Input
[2, 3, 4, 5, 6, 7, 8, 9, 10], [(2, 5), (7, 3), (6, 4)]
Output
[13, 9, 8]
- Related Articles
- Java program to find the sum of elements of an array
- Python program to find sum of elements in list
- Program to find sum of unique elements in Python
- Find the sum of array in Python Program
- C Program to find sum of perfect square elements in an array using pointers.
- Python Program to find out the sum of values in hyperrectangle cells
- Find sum of elements in list in Python program
- Python Program to find the sum of array
- Program to find sum of elements in a given array in C++
- C/C++ Program to find the sum of elements in a given array
- Program to find running sum of 1d array in Python
- Python Program to find out the number of matches in an array containing pairs of (base, number)
- Create an evenly spaced color stops with CSS Radial Gradients
- Program to find sum of odd elements from list in Python
- Program to Find Out Median of an Integer Array in C++
