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. 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.
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.