简体   繁体   中英

How to sum first and last element in list to get 2 digit number in the end?

    x = "jankometka"
    freq = {}
    for c in x:
        freq[c] = x.count(c)
    #print(freq)
    
    empty_list = []
    
    my_list = list(freq.values())
    
    
    
    givenIndices = [0, -1]
    indicesList = sorted(givenIndices, reverse=True)
    sum = my_list[0] + my_list[1]
    for i in my_list:
    
        for indx in indicesList:       
            if indx < len(my_list):           
                my_list.pop(indx)
                empty_list.append(my_list)
    
            print(my_list)
"jankometka" - after counting letter occurrence i got list
    
    [1, 2, 1, 2, 1, 1, 1, 1] - here I want to sum firs and last number in list and should get this
    [2, 3, 2, 3] and than
    [5, 5]
    
    and also i have to remove index 0 and -1 from original list
    [1, 2, 1, 2, 1, 1, 1, 1]
    [2, 1, 2, 1, 1, 1]
    [1, 2, 1, 1]
    [2, 1]

I don't know how to loop through list, sum first and last element in list and than remove first and last element till i get two digit number. thank you

In [32]: L = [1, 2, 1, 2, 1, 1, 1, 1]

In [33]: answer = []

In [34]: while len(answer) != 1:
    ...:     while L:
    ...:         answer.append(L[0]+L[-1])
    ...:         L = L[1:-1]
    ...:     if len(answer) == 1: break
    ...:     print(answer)
    ...:     L = answer
    ...:     answer = []
    ...:
[2, 3, 2, 3]
[5, 5]

If your lists are not too long, a recursive solution probably -

def rec_sum_ends(lst):
    if len(lst) <= 2:
        return lst
    midpoint = len(lst) // 2
    front_half = lst[:midpoint]
    reversed_back_half = lst[:-midpoint-1:-1]
    combined = [sum(el) for el in zip(front_half, reversed_back_half)]
    return rec_sum_ends(combined)
rec_sum_ends([1, 2, 1, 2, 1, 1, 1, 1])

Output

[5, 5]
def rec_remove_ends(lst):
    if len(lst) <= 2:
        return lst
    return rec_remove_ends(lst[1:-1])
rec_remove_ends([1, 2, 1, 2, 1, 1, 1, 1])

Output

[2, 1]

EDIT: Dealing with odd number length lists

The above solutions work for a list that has an even number of items. Based on your comment on how you want to treat odd sized lists - you can do a little re-work to isolate the "middle" element from odd sized lists and add it back -

def both_odd_even_lists(lst):
    if len(lst) % 2 == 0:
        return rec_sum_ends(lst)
    else:
        midpoint = len(lst) // 2
        new_lst = lst[:midpoint] + lst[midpoint+1:]
        mid_item = lst[midpoint]
        reduced_new_lst = rec_sum_ends(new_lst)
        return [reduced_new_lst[0] + mid_item, reduced_new_lst[1]]

Output

# both_odd_even_lists([1, 1, 1, 1, 1, 1, 2, 1, 1])
[5, 5]

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