[英]How to find the symmetrical portion of a python list of integers and get the sum of that symmetrical portion?
[英]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
:
i
個元素相等,則獲取表示條件的布爾值列表True
的索引以下代碼應適用於您發布的輸入和 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.