简体   繁体   English

如何获得一个对称的子列表,然后得到该子列表的总和?

[英]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.代码的作用:将 Python 整数列表作为输入并搜索列表的“对称”内部部分,然后获取该内部部分并获得其总和。

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.如果列表开头的第 i 个元素的值等于列表末尾的第 i 个元素的值,则对称发生。

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.我有一个正确的编码版本,但它有 30 多行代码,想知道是否有更短的方法。

Try using numpy :尝试使用numpy

  1. get a list of booleans representing the condition if i th element from beginning and end are equal如果开始和结束的第i个元素相等,则获取表示条件的布尔值列表
  2. find indices where the boolean values are True查找 boolean 值为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:以下代码应适用于您发布的输入和 output:

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:如果您需要实际对称 output 使用:

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.在这里,我们递归调用 function 直到不对称部分完全条纹。

In pure python this can be achieved like this:在纯 python 中,可以这样实现:

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:您可以使用递归 function 执行此操作,如下所示:

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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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