A prefix-total array stores cumulative amounts so a static half-open interval can be answered by subtracting two stored totals.
Python range exercise: immutable prefix totals and exclusive endpoints
Operation contract
The exercise builds an owned prefix array from bounded exact integers. Prefix position zero represents the sum before any record. A query for positions left through right-minus-one returns prefix[right] minus prefix[left]. Empty intervals return zero. Editing the source list afterward does not change the already built numeric snapshot.
Failure and ownership boundary
This snapshot cannot track subsequent edits. Replacing or adding amounts requires a new prefix build or an update-capable structure. Exposing the prefix list also allows a caller to corrupt its invariant; this fixture passes only its own constructed result. Python segment tree: point replacement and half-open range sums and Python lazy segment tree: defer interval additions and retain correct totals serve changing datasets.
Working program
def prefix_totals(amounts):
if len(amounts) > 128 or any(type(amount) is not int for amount in amounts):
raise ValueError("bounded integer amounts required")
prefix = [0]
for amount in amounts:
prefix.append(prefix[-1] + amount)
return prefix
def interval_total(prefix, left, right):
count = len(prefix) - 1
if any(type(index) is not int for index in (left, right)) or not 0 <= left <= right <= count:
raise ValueError("invalid half-open interval")
return prefix[right] - prefix[left]
amounts = [125, 250, 75]
prefix = prefix_totals(amounts)
print(prefix)
print(interval_total(prefix, 1, 3))
print(interval_total(prefix, 2, 2))
amounts[0] = 999
print("snapshot total:", interval_total(prefix, 0, 3))Output
[0, 125, 375, 450]
325
0
snapshot total: 450Costs and limits
Building n totals takes O(n) arithmetic work and O(n) retained integers. A query uses two lookups and one subtraction, with digit-dependent numeric costs. Rebuilding after every change can erase that query-time advantage.
Common Mistakes
- Prefix position zero is required for intervals starting at zero.
- The snapshot does not update when the original list changes.
Connected lessons
Python segment tree: point replacement and half-open range sums, Python lazy segment tree: defer interval additions and retain correct totals, Python shallow and deep copies: preserve aliases deliberately.
