[英]Is there a faster way to sum up an arithmetic sequence of numbers in Python?
[英]Sum of lowest numbers that are part of an arithmetic sequence
我想遍历一个整数列表,计算属于具有公差 1 的算术序列的最小数字的总和 + 不属于序列的数字:
mylist = [2,3,4,10,12,13]
因此,从 mylist 将是 2(来自 2,3,4)+ 10(不是序列的一部分)+ 12(来自 12,13)
我已经设法使某些事情起作用,但是如果列表颠倒,我只能弄清楚如何去做。 而且我确信我有一个更好/更清洁的解决方案:
mylist = [13,12,10,4,3,2]
result = mylist[-1] #if I don't do this, I don't know how to grab the last item in the list
for i in range(len(mylist)-1):
if mylist[i] - mylist[i+1] == 1:
continue
else:
result += mylist[i]
希望有人能帮助我,让我在编码过程中变得更聪明。 谢谢。
@KennethRasch - 较早的帖子会起作用。 或者,您也可以这样做:
尝试找到每个可能的子序列的起始数字作为starts
,然后将它们相加得到答案。
L = [13,12,10,4,3,2]
L.sort()
starts = [x for x in L if x-1 not in L]
print(starts)
result = sum(starts)
print(result) # 24
或者,您可以将其放入 function 以供将来重复使用:
def sum_lowests(L):
'''L is a numbers sequence '''
L.sort()
starts = [x for x in L if x-1 not in L]
ans = sum(starts)
return ans
if __name__ == '__main__':
L = [13,12,10,4,3,2]
A = [1, 2, 3, 5,6, 9,10,11, 16]
print(sum_lowests(L))
print(sum_lowests(A))
保持一个运行总和,一个运行索引,并在它仍然是一个序列时进行迭代:
mylist = [13,12,10,4,3,2]
mylist.sort() # this way sequences will be contiguous in the list
cur_index = 0
cur_sum = 0
while cur_index < len(mylist):
# add the current element to the sum
cur_sum += mylist[cur_index]
# now iterate through while it's a contiguous sequence
cur_index += 1
while cur_index < len(mylist) and mylist[cur_index] == mylist[cur_index - 1] + 1:
cur_index += 1
print(cur_sum)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.