Skip to content

Commit

Permalink
Fenwick Tree impl in py (#3)
Browse files Browse the repository at this point in the history
Signed-off-by: jparisu <[email protected]>
  • Loading branch information
jparisu authored Mar 3, 2024
1 parent 4de33f6 commit f19d354
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 20 deletions.
20 changes: 7 additions & 13 deletions docs/md/intermedio/fenwick/fenwick_cpp.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
# Bucles [C++]

```{contents}
:local:
:depth: 2
```

# Fenwick [C++]

```cpp
#include <iostream>
Expand All @@ -21,11 +15,11 @@ struct FenwickTree {
{}

// O(logN)
// Add value to the element at index (index starts on 0)
void update(int index, int value) {
// Add delta to the element at index (index starts on 0)
void update(int index, int delta) {
index++;
while (index <= n) {
tree[index - 1] += value;
tree[index - 1] += delta;
index += index & -index;
}
}
Expand Down Expand Up @@ -54,9 +48,9 @@ struct FenwickTree {
}

// O(logN)
// Return the sum from a to b (both included)
int biquery(int a, int b) {
return query_includes(b) - query(a);
// Return the sum from start to end (both included) (index starts on 0)
int query_range(int start, int end) {
return query_includes(end) - query(start);
}

vector<int> tree;
Expand Down
47 changes: 40 additions & 7 deletions docs/md/intermedio/fenwick/fenwick_py.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,43 @@
# Bucles [Python]
# Fenwick [Python]

```{contents}
:local:
:depth: 2
```
```py
class FenwickTree:

# O(N)
# Create a Fenwick tree with n elements, all initialized to zero
def __init__(self, size):
self.size = size
self.tree = [0] * (size)

# O(logN)
# Add delta to the element at index (index starts on 0)
def update(self, index, delta):
index += 1
while index <= self.size:
self.tree[index - 1] += delta
index += index & -index

# O(logN)
# Return the sum from 0 to index (no included) (index starts on 0)
def query(self, index):
acc = 0
while index > 0:
acc += self.tree[index - 1]
index -= index & -index
return acc

# O(logN)
# Return the sum from 0 to index (included) (index starts on 0)
def query_includes(self, index):
acc = 0
index += 1
while index > 0:
acc += self.tree[index - 1]
index -= index & -index
return acc

```{todo}
`Work In Progress`
# O(logN)
# Return the sum from start to end (both included) (index starts on 0)
def query_range(self, start, end):
return self.query_includes(end) - self.query(start)
```

0 comments on commit f19d354

Please sign in to comment.