簡體   English   中英

如何獲得一個對稱的子列表,然后得到該子列表的總和?

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

代碼的作用:將 Python 整數列表作為輸入並搜索列表的“對稱”內部部分,然后獲取該內部部分並獲得其總和。

如果列表開頭的第 i 個元素的值等於列表末尾的第 i 個元素的值,則對稱發生。

我想要的例子:

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) 

是否有任何短編碼解決方案來獲得上面給出的示例中的輸出? 我有一個正確的編碼版本,但它有 30 多行代碼,想知道是否有更短的方法。

嘗試使用numpy

  1. 如果開始和結束的第i個元素相等,則獲取表示條件的布爾值列表
  2. 查找 boolean 值為True的索引
  3. 最小值表示對稱開始的位置,最大值表示結束的位置,因此對列表數組進行切片以獲得“對稱”子列表
  4. 將新列表及其總和作為元組返回

以下代碼應適用於您發布的輸入和 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))

如果您需要實際對稱 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))

在這里,我們遞歸調用 function 直到不對稱部分完全條紋。

在純 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

您可以使用遞歸 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