[英]Return remaining items in list, if last n elements in list greater than a number
Given a list of numbers: 给定数字列表:
ar =[1,2,3,4,5,6,7,8,9,10]
I need to find the remaining part of the list if the last n numbers summed are greater than a given number. 如果最后的n个数字之和大于给定的数字,我需要找到列表的其余部分。 For example if the given number was 25, the returned\\"remainder" list would be
[1,2,3,4,5,6,7]
, since that the last 3 elements add up to 27. 例如,如果给定数字为25,则返回的“剩余”列表将为
[1,2,3,4,5,6,7]
,因为最后3个元素的总和为27。
I have some code, but I get the overbearing suspicion that it is quite inefficient, failing that, overly verbose given the simple nature of the task. 我有一些代码,但是我很霸道地怀疑它效率很低,否则,鉴于任务的简单性质,它过于冗长。
def kp_find(ar, level):
kp1=[]
for k in range(len(ar)): #this is required as in reality there is some
kp1.append(k) #work to be done within this loop
kp_fin = sorted(kp1,reverse = True)
kp2=[]
for k in kp_fin:
kp2.append(k)
sm_it = sum([i for i in kp2])
if sm_it>level:
place = [i for i, j in enumerate(kp_fin) if j == k]
break
else:
place = []
if place:
return kp_fin[place[0]:len(kp1)]
print kp_find(ar,24)
As you see it's quite a lot of code for something so insignificant; 如您所见,对于如此微不足道的东西,有很多代码。 any help welcome.
任何帮助欢迎。
It does seem like a lot of code for a simple task. 对于一个简单的任务,似乎确实有很多代码。 You could just pop off elements from the right end of the list until the condition is met.
您可以从列表的右端弹出元素,直到满足条件为止。 Something like this:
像这样:
>>> def kp_find(ar, level):
... result = ar[:]
... sum_ = 0
... while sum_ < level:
... sum_ += result.pop()
... return result
...
>>> kp_find([1,2,3,4,5,6,7,8,9,10], 25)
[1, 2, 3, 4, 5, 6, 7]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.