Im a newbie to python , and I came across this particular code snippet to calculate the greatest slice in an sequence, however I simply cant seem to understand the following code
best = A[0]
for size in range(1,n+1):
cur = sum(A[:size])
for i in range(n-size):
cur += A[i+size] -= A[i] # <- what happens here?
best = max(best, cur)
Any idea on how the code functions and with that line in particular would be helpful!
First off, the error in your code is an extra
=. Working code:The outer for loop creates larger and larger slices, starting with
sizeset to 1. Thencuris set to the sum of the firstsizeitems ofA.In the inner loop, this slice is “moved” to the right by adding the value just to the right of the slice (
A[i+size]) and subtracting the first value of the slice (A[i]).Finally
bestis set to whichever is larger of the newly computed sum and the largest value found so far.In the end,
bestcontains the largest sum. UnlessAcontains negative values, the answer is trivial:sum(A).EDIT: I just noticed that there’s a bug: The leftmost slice is not counted, except for slice size 1 (
best = A[0]). So ifA = [4, 3, 2]it outputs5instead of9. Fix by adding abest = max(best, cur)line above the inner for loop.