Home > Back-end >  Sum up numbers close to a specific number in a list
Sum up numbers close to a specific number in a list

Time:11-15

Example 1

List = [12,40,30,53,82,31,100]

I want to produce a list which includes so many numbers close to 80 and not larger than 80 . If the number originally larger than 80 just pass.

The result like [52,30, ,53,82, 31,100] Because of [12 40,30,53,82,31 ,100]

Example 2

List =[45,102,31,25,2,99]
Result = [45,102,58,99]

Please help me figure out how to code with this question, really appreciate it.

I have tried

For i in range(len(List)):

CodePudding user response:

Try this:

start = -1
sum_ = 0
List = [45,102,31,25,2,99]
result = []
i = 0

while i < len(List):
    if start == -1:
        start = i

    new_sum = sum_   List[i]
    if new_sum > 80:
        result.append(sum_)
        start = -1
        sum_ = 0
        new_sum = 0
        if List[i] > 80:
            result.append(List[i])
            i  = 1
        continue
    else:
        sum_ = new_sum
        i  = 1

print(result)
# [45, 102, 58, 99]

CodePudding user response:

List =[45,102,31,25,2,99]
# List = [12,40,30,53,82,31,100]
result = []

for i in range(0,len(List)):
    if List[i]>=80 or len(result)==0:
        result.append(List[i])
    elif result[-1]   List[i] <=80 :
        result[-1]  = List[i] 
    else :
        result.append(List[i])
    
print(result)

CodePudding user response:

You can define simple generator function which will yield sum of values if they reached limit:

def sum_up_to(source, limit):
    summ = 0
    for i in source:
        if summ   i > limit:
            if summ:
                yield summ
                summ = i
            else:
                yield i
                summ = 0
        else:
            summ  = i
    if summ:
        yield summ

Then just call it with any limit:

src1 = [12, 40, 30, 53, 82, 31, 100]
dst1 = list(sum_up_to(src1, 80))  # [52, 30, 53, 82, 31, 100]
src2 = [45, 102, 31, 25, 2, 99]
dst2 = list(sum_up_to(src2, 80))  # [45, 102, 58, 99]

Upd. I've made some tests (code) to compare solutions from all answers. Here is results (lower is better):

olvin_roght: 0.32001448499999996
chandrapal_singh: 0.53703229
captain_trojan: 0.9307081629999998

Tests shown that solution from this answer demonstrates best performance.

  • Related