~/Prefix Scan Example in Python

Jul 15, 2021


A prefix scan, also called prefix sum, computes the cumulative sum of a list up to each index. It is often used in array algorithms.

Here is a simple Python example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def prefix_scan(arr):
    result = []
    total = 0
    for num in arr:
        total += num
        result.append(total)
    return result

data = [1, 2, 3, 4, 5]
print(prefix_scan(data))  # Output: [1, 3, 6, 10, 15]
Tags: [algorithm]