Home > Back-end >  Addition of numbers in list and printing statements with different conditions
Addition of numbers in list and printing statements with different conditions

Time:10-27

I am given following list, where I have to add them up until a limit is reached and the process repeats until end of list.

I tried following code but I get one last digit by itself and not append to newlist as it is not more than 10 to execute the code, if count is more than limit. How can I do it better?

limit= 10
count= 0
findex= 0
lindex=0
newlist=[]
mylist= [5,2,4,5,1,2,6,5]

for i in mylist:
    if count <limit:
        count =i
        lindex =1

    if count >= limit:
        lindex-=1
        newlist.append(mylist[findex:lindex])
        count=i
        findex=lindex
        lindex =1

print (newlist)

Also, how can I display them in the following way?

enter image description here

CodePudding user response:

What you need is a final condition check which is findex is less than length of mylist I think. If you add the following condition block to end of your code, It should give the result you desired.

 if findex < len(mylist):
    newlist.append(mylist[findex:])

CodePudding user response:

In order to append the last element of mylist into the newlist just add the following command after the for loop :

newlist.append(mylist[findex:lindex])

This command will append all the numbers that did not manage to get appended during the loop

The print you want can be achieved by the following loop :

index = 0
for l in newlist:
    if index == 0:
        print("Firstly, ", l)
    elif index == len(newlist) - 1:
        print("lastly, ", l)
    else:
        print("then, ", l)

    index =1
  • Related