简体   繁体   中英

How to get a symmetrical sub list and then get the sum of that sub list?

What the code does: Takes a Python list of integers as input and searches for a 'symmetrical' inner-portion of the list then it takes that inner portion and gets the sum of it.

Symmetry occurs if the value of the ith element from the start of the list is equal to the value of the ith element from the end of the list.

Examples of what i want:

symmetrical_sum([10,11,12,11,12]) == ([11, 12, 11], 34)
symmetrical_sum([9,99,88,8,77,7,77,8,88,10,100]) == ([88, 8, 77, 7, 77, 8, 88], 353)
symmetrical_sum([10,8,7,5,9,8,15]) == ([8, 7, 5, 9, 8], 37) 

Is there any short-coded solution to get the outputs in the examples given above? I have a correct coded version but it is more than 30 lines of code and would like to know if there is shorter way.

Try using numpy :

  1. get a list of booleans representing the condition if i th element from beginning and end are equal
  2. find indices where the boolean values are True
  3. The min value represent where symmetry starts and max value is where it ends, so slice the list array to get the "symmetrical" sub-list
  4. return the new list and its sum as a tuple

Following code should work for the input and output you posted:

import numpy as np

def sym_sum(arr):
    l = len(arr)-1
    bool_arr = np.array([x==arr[l-i] for i,x in enumerate(arr)])
    idx_arr = np.where(bool_arr==True)[0]
    if len(idx_arr):
        res = arr[min(idx_arr):max(idx_arr)+1]
    else:
        res = []
    return (res, sum(res))

If you need actual symmetrical output use:

import numpy as np

def get_sym(arr):
    l = len(arr) - 1
    bool_arr = np.array([x == arr[l - i] for i, x in enumerate(arr)])
    idx_arr = np.where(bool_arr == False)[0]
    if len(idx_arr):
        return get_sym(arr[min(idx_arr)+1:max(idx_arr)])
    else:
        return (arr, sum(arr))

Here we recursively call the function until the unsymmetrical portions are completely striped.

In pure python this can be achieved like this:

def symmetrical_sum(a):


inner_portion = []
  sum = 0;
  start = 0;
  for i in a:
    end = len(a) - (start + 1);
    if a[start] == a[end]:
      inner_portion = a[start:(end+1)];
      for i in inner_portion:
        sum+= i
      break
    start+= 1
  return (inner_portion, sum)

print(symmetrical_sum([10,11,12,11,12])) #([11, 12, 11], 34)
def symmetrical_sum(a): dup=[x for n, x in enumerate(a) if x in a[:n]] #to get the duplicate to_int = int(''.join(map(str,dup))) #change duplicate into int dup1_index=a.index(to_int) #index the first duplicate dup2_index=a.index(to_int,dup1_index+1) #index the second duplicate portion=a[dup1_index:dup2_index+1] #get the symetric portion total = sum(portion) #sum the elements in portion tuple1 = (portion,total) #create tuple return tuple1

You can do this with a recursive function as follows:

def sym(L):
    if L[0] == L[-1]:
        lis, sum_list = L, sum(L)
        answer = f'inner-portion: {lis}, sum: {sum_list}'
        return answer
    else:
        return sym(L[1:-1])

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