PracticeArrays
Add a Document's Token Span
Context
A document analysis tool assigns each token an integer impact score. For one review request, the tool receives the scores and the positions of the first and last token in a highlighted span. Compute the span's combined impact score.
Problem
Given a non-empty list of integer token scores and two valid positions, return the sum of all scores from start through end, including both endpoints. The positions are zero-based, start is no greater than end, and every position in the requested interval is valid. Count each position exactly once, including repeated values, zeros, and negative scores.
Examples
Example 1
Input:
end = 3scores = [4, 7, 2, 9]start = 1Output:
18Explanation: Example 1 returns 18 when the scores from positions 1 through 3 are processed. (fact_ids: )
Example 2
Input:
end = 3scores = [5, -3, 0, -3, 5]start = 1Output:
-6Explanation: Example 2 returns -6 when the scores from positions 1 through 3 are processed, including repeated negative values and zero. (fact_ids: )
Example 3
Input:
end = 0scores = [8, -2, 6]start = 0Output:
8Explanation: Example 3 returns 8 when the interval contains only position 0. (fact_ids: )
Constraints
1 <= len(scores) <= 100000-1000000 <= scores[i] <= 1000000 for every i0 <= start <= len(scores) - 10 <= end <= len(scores) - 1- Types:
scoresis int[],startis int,endis int; result is int
Function signature
def sum_token_span(scores: list[int], start: int, end: int) -> int
scoreslist[int]- Integer impact score for each document token, in document order.
startint- Zero-based position of the first token in the inclusive span.
endint- Zero-based position of the last token in the inclusive span.
- returns int
- The total of all token scores at positions from start through end, inclusive.
Adapted from MBPP problem task_170 (CC BY 4.0). Rewritten, extended and verified by Iksha.
Notes
- Inputs guarantee start is no greater than end.
- The interval is guaranteed to contain valid positions.
Code
Saved