Skip to content

Commit 3c9a591

Browse files
Merge pull request #416 from shakeelsamsu/master
Implemented fenwick tree in python
2 parents a4a4a9b + feba1f7 commit 3c9a591

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
"""
2+
@author: shakeelsamsu
3+
https://gihtub.com/shakeelsamsu
4+
Oct 7 18 9:42:35 PM
5+
"""
6+
7+
class fenwick:
8+
"""Fenwick Tree"""
9+
10+
#def __init__(self, list):
11+
# """Initialize BIT with list in O(n*log(n))"""
12+
# self.array = [0] * (len(list) + 1)
13+
# for idx, val in enumerate(list):
14+
# self.update(idx, val)
15+
16+
def __init__(self, list):
17+
""""Initialize BIT with list in O(n)"""
18+
self.array = [0] + list
19+
for idx in range(1, len(self.array)):
20+
idx2 = idx + (idx & -idx)
21+
if idx2 < len(self.array):
22+
self.array[idx2] += self.array[idx]
23+
24+
def prefix_query(self, idx):
25+
"""Computes prefix sum of up to including the idx-th element"""
26+
idx += 1
27+
result = 0
28+
while idx:
29+
result += self.array[idx]
30+
idx -= idx & -idx
31+
return result
32+
33+
def range_query(self, from_idx, to_idx):
34+
"""Computes the range sum between two indices (both inclusive)"""
35+
return self.prefix_query(to_idx) - self.prefix_query(from_idx - 1)
36+
37+
def update(self, idx, add):
38+
"""Add a value to the idx-th element"""
39+
idx += 1
40+
while idx < len(self.array):
41+
self.array[idx] += add
42+
idx += idx & -idx
43+
44+
45+
if __name__ == '__main__':
46+
array = [1, 7, 3, 0, 5, 8, 3, 2, 6, 2, 1, 1, 4, 5]
47+
bit = fenwick(array)
48+
print('Array: [{}]'.format(', '.join(map(str, array))))
49+
print()
50+
51+
print('Prefix sum of first {} elements: {}'.format(13, bit.prefix_query(12)))
52+
print('Prefix sum of first {} elements: {}'.format(7, bit.prefix_query(6)))
53+
print('Range sum from pos {} to pos {}: {}'.format(1, 5, bit.range_query(1, 5)))
54+
print()
55+
56+
bit.update(4, 2)
57+
print('Add {} to element at pos {}'.format(2, 4))
58+
new_array = [bit.range_query(idx, idx) for idx in range(len(array))]
59+
print('Array: [{}]'.format(', '.join(map(str, new_array))))
60+
print()
61+
62+
print('Prefix sum of first {} elements: {}'.format(13, bit.prefix_query(12)))
63+
print('Prefix sum of first {} elements: {}'.format(7, bit.prefix_query(6)))
64+
print('Range sum from pos {} to pos {}: {}'.format(1, 5, bit.range_query(1, 5)))
65+
print()

0 commit comments

Comments
 (0)