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

Time:10-07

    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

CodePudding user response:

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]

CodePudding user response:

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]
  • Related