Home > Blockchain >  Getting the value of List and sum in python
Getting the value of List and sum in python

Time:10-24

I newbie in python and I have a trouble how can I make my loop with that shape below and getting the total number of each line, I tried the code below but it seems it doesn't right I should use list in loop like the declaration below, I appreciate who can help me.

data = [1, 2, 3, 4, 5]

Expected output:

[1, 2, 3, 4, 5, 15]
[2, 3, 4, 5, 14]
[3, 4, 5, 12]
[4, 5, 9]
[5, 5]

This is what I tried but it doesn't use list ,I think it's wrong

data = 5
for i in range(data):
    for j in range(i 1):
        print("[",j 1, end=" " " ]")
    print("[  ]")

CodePudding user response:

Usually in these kind of exercises you shouldn't build the string yourself(talking about brackets). Those brackets are part of the representation of the lists in Python. So build your list object and the final result is gonna be printed as you expected. So don't attempt to put individual numbers, spaces, brackets together yourself.

You can use:

data = [1, 2, 3, 4, 5]
for i in range(len(data)):
    slice_ = data[i:]
    print(slice_   [sum(slice_)])

Explanation:

Basically in every iteration, you create a slice of the list by specifying the start point to the end. Start point comes from the range(len(data)) range object.

first iteration : From index 0 to end.
second iteration: From index 1 to end.
...

Then you concatenate the slice with the sum of the slice. But you have to put the sum inside a list because a list can't be concatenated with an int. Of course other option is to .append() it before printing:

for i in range(len(data)):
    slice_ = data[i:]
    slice_.append(sum(slice_))
    print(slice_)
  • Related