Home > Back-end >  how to loop through each element in list and increment by one
how to loop through each element in list and increment by one

Time:05-22

Hello i want to ask how to loop through each element and increment every time by one this is what i want first i want to sum 0 , 1, 3 ,6 , 10 and after that sum can somebody help me about that i don't know how to tell if it is loop through each element or iterate.It should look like these examples.I am sorry!

ls = [0, 1, 3, 6, 10]

ls = [1, 3, 6, 10]

ls = [3, 6, 10]

ls = [6, 10]

ls = [10]

ls = []

Here's the problem who i want to solve it : https://www.codewars.com/kata/5ce399e0047a45001c853c2b/train/python

I tried this but it doesn't work

 def parts_sums(ls):
    length_list = len(ls)
    for i in range(0,length_list 1):
        return length_list
    

CodePudding user response:

Note that there is a built-in function sum() in Python that does that job probably better than any code you can write in Python.

sum([0, 1, 3, 6, 10])

However, if you want to practice writing your sum function by iterating through a list and summing all the elements, this is how you do it.

def my_sum(ls):
    result = 0
    for i in range(len(ls)):
        result  = ls[i]
    return result

First of all, you need to initialize a variable to hold your result. The range() function generates all values from 0 to x. The for-loop assigns all values generated by the range function to i in order and executes the indented block below. The = assignment increments the left-hand side variable by the right-hand side expression value. At last, we return the result.

And if you prefer using a while-loop,

def my_sum(ls):
    result = 0
    i = 0
    while i < len(ls):
        result  = ls[i]
        i  = 1
    return result

It's always good to consult Python documentation when you are not sure how to use its built-in function.

If you want the accumulated sum of all items reversed, you can take a look at the accumulate function in itertools.

from itertools import accumulate
def parts_sums(ls):
    return list(accumulate(ls[::-1]))[::-1]   [0]

Or if you want to implement with a loop,

def parts_sums(ls):
    result = []
    part_sum = 0
    for item in ls[::-1]:
        result.append(part_sum)
        part_sum  = item
    result.append(part_sum)
    
    return result[::-1]

Or if you want to do it without reversing the list (say if you want to yield the results)

def parts_sums(ls):
    result = []
    part_sum = sum(ls)
    for item in ls:
        result.append(part_sum)
        part_sum -= item
    result.append(part_sum)
    
    return result

Note the algorithm is still O(n), not that time complexity matters in this case.

CodePudding user response:

For the question you have mentioned in codewars, you need to loop it thro 2 loops and keep reducing the first element in the inner loop for sum.

def parts_sums(ls):
    # your code
    sum = []
    for i in range(len(ls)):
        sum_temp =0
        for j in range(i,len(ls)):
            sum_temp  = ls[j]
        sum.append(sum_temp)
    sum.append(0)   # for the final empty list
    return sum
print(parts_sums([0, 1, 3, 6, 10]))

CodePudding user response:

This test will check the execution time too. So you need to be fast.

Naive approach

You can use sum or create your own sum.

def parts_sums(ls):
    return [
        sum(ls[i:])
        for i in range(len(ls)   1)
    ]

But i means you'll need to loop in a list twice. So it will be slow.

Sneaky approach

In a list like [a, b, c, d, e] you are calculating:

[a b c d e, a b c d, a b c, a b, a, 0]. So let's start from last to first element. [0, a, a b, a b c, a b c d, a b c d e]. Now we see a cumulative iteration: So get loop in the list, get the element, sum it with last element of the result ([0]) list and add it as the last element to the result list. Lastly reverse the result.

def parts_sums(ls):
    res = [0]
    for i in range(len(ls)-1, -1, -1):
        res.append(res[-1]   ls[i])
        
    return res[::-1]
  • Related