python – Get a new list that contains the sum of all numbers to the right of the given number

Question:

Please help me to implement the receipt of a new list in which, instead of the original digits, the sum of all the digits to the right of the given number will be

Answer:

Using additional memory

xs = [1, 2, 3, 4]
n = len(xs)
sums = [0] * n

for i in range(n - 1, 0, -1):
    sums[i - 1] = sums[i] + xs[i]

print(sums)

And in place

xs = [1, 2, 3, 4]
n = len(xs)

last = xs[n - 1]
xs[n - 1] = 0

for i in range(n - 1, 0, -1):
    tmp = xs[i - 1]
    xs[i - 1] = xs[i] + last
    last = tmp

print(xs)
Scroll to Top