简体   繁体   中英

summing the first and last elements of list

I'd like to sum the first element and last elements of a list, and then exclude those two numbers and repeat that process again until there is only one element in the list. Like this:

[5,4,3,2,1,6]
[11,5,5]
[16,5]
[21]

I used some methods but didn't work. I am just a computer science student starting to python so help me out please guys. Thank you.

Main logic of this answer is revolve around len of last list print . Lets break it in few points:

LOGIC:
1. Basically we need sum of first-ith and last-ith value for that we used this code:

l_u[-1][i] + l_u[-1][-i - 1]

2. Above point is only valid when lenght of last append list is even for odd-length we have to append this only at even poistion:

l_u[-1][i]  

3. Among above two statement which is going to true this is done by this condition:

len(l_u[-1])%2 != 0 and i%2 != 0

CODE:

l = [5, 4, 3, 2, 1, 6]
l_u = [l]

condn = True
j = 0

while condn:
    l_u.append([
        l_u[-1][i] if len(l_u[-1]) % 2 != 0 and i % 2 != 0 else l_u[-1][i] +
        l_u[-1][-i - 1] for i in range(
            len(l_u[-1]) // 2 if len(l_u[-1]) % 2 == 0 else len(l_u[-1]) // 2 +
            1)
    ])

    if len(l_u[-1]) <= 1:
        break

print(l_u)

OUTPUT:

[[5, 4, 3, 2, 1, 6], [11, 5, 5], [16, 5], [21]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM