- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to define data structure that supports range sum in Python
Suppose we want to develop a data structure that can build up with a list of integers, and there is a function to find sum of elements from index i to index j-1 whenever we require in an efficient way. There are two functions.
- Constructor that constructs a new instance with the integer array.
- get_sum(i, j) returns the sum of integers of array elements from starting index i and ending index j-1.
So, if the input is like array = [5,2,3,6,4,7,8,9,3,2] then construct an object obj, and call functions obj.get_sum(1,5) and obj.get_sum(4,8), then the output will be 15 and 28 respectively. As the first range elements are [2,3,6,4] so sum is 15 and second range elements are [4,7,8,9] here the sum is 28.
To solve this, we will follow these steps −
- Define constructor. This will take array
- sums := this is a list, initially insert 0
- for each x in array, do
- insert (x + (last item of sums)) at the end of sums
- Define a function get_sum() . This will take i, j
- return sums[j] - sums[i]
Let us see the following implementation to get better understanding −
class RangeSum: def __init__(self, array): self.sums =  for x in array: self.sums.append(x + self.sums[-1]) def get_sum(self, i, j): return self.sums[j] - self.sums[i] array = [5,2,3,6,4,7,8,9,3,2] obj = RangeSum(array) print(obj.get_sum(1,5)) print(obj.get_sum(4,8))
[5,2,3,6,4,7,8,9,3,2] obj.get_sum(1,5) obj.get_sum(4,8)
- Program to define data structure that supports rate limiting checking for user in Python
- Program to define set data structure without using library set class in Python
- Range Trees in Data Structure
- Program to create data structure to check pair sum is same as value in Python
- How to define a structure in C#
- Python Program to Implement Queue Data Structure using Linked List
- Program to find range sum of sorted subarray sums using Python
- Program to count subsets that sum up to k in python
- C++ Program to Implement Disjoint Set Data Structure
- Java Program to Implement the graph data structure
- Java Program to Implement the queue data structure
- Rectangle Data in Data Structure
- What are the various locators that Selenium supports?
- Halfedge data structure