![](/img/trans.png)
[英]How to get a symmetrical sub list and then get the sum of that sub list?
[英]How to find the symmetrical portion of a python list of integers and get the sum of that symmetrical portion?
代码的作用:将 Python 整数列表作为输入并搜索列表的“对称”内部。
我想要的例子:
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)
如果列表开头的第 i 个元素的值等于列表末尾的第 i 个元素的值,则对称发生。
我的代码:
def symmetrical_sum(a):
#extract duplicate value
dupe = [x for n, x in enumerate(a) if x in a[:n]]
#if no duplicate values found, do the following:
if dupe == []:
middle = float(len(a))/2
if middle % 2 != 0:
sym = a[int(middle - .5):int(middle + .5)]
ans = a[int(middle - .5)]
tuple1 = (sym,ans)
elif middle % 2 == 0:
sym = a[int(middle - 1):int(middle + 1)]
ans = sum(a[int(middle - 1):int(middle + 1)])//2
tuple1 = (sym,ans)
return tuple1
else:
d_to_i = int("".join(map(str, dupe))) #convert duplicate value to integer
p1 = a.index(d_to_i) #get index of first duplicate
p2 = a.index(d_to_i, p1+1) #get index of second duplicate
sym = a[p1:p2+1] #[symmetrical-portion]
ans = sum(sym) #sum-of-symmetrical-portion
tuple2 = (sym, ans)
return tuple2
我的代码有效,但如果有人可以出于效率目的发布更短的解决方案,那就太好了。
x = [10,11,12,11,12]
output = [(x[n:-n],sum(x[n:-n])) for n in range(len(x)) if x[n] == x[-n-1]]
#this will output 3 cases: Symmetry regardless of even/odd elements. OR no symmetry for odd. (middle index)
if output == []:#even number of elements with no symmetry at all
pass
if len(output[0][0]) == 1: #odd number of elements with no symmetry at all
pass
print(output[0])
我希望这有帮助。 当没有检测到对称性时,我真的不明白你会做什么。 output 将返回所有对称列表及其总和,包括是否存在对称但奇数个元素。 不确定这是否是做你想做的事情的最佳方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.