Home > Blockchain >  search aggregation result in main list
search aggregation result in main list

Time:12-09

I want to check if the sum of the elements is in df=[200,107,25,30] by navigating through catch_list_7=[100,7], but when I enter 200, which is a larger value than the sum, my loop stays at 200 and does not continue. When I delete the 200 value, it works.

                is_match =False
                for i in catch_list_7 :
                    if is_match ==False:
                           for d in df: 
                            if abs(d-(i[0] i[1]))<=0.2:
                                catch_list.append([i[0] i[1],i[0],i[1]])
                                print("Total Gross", catch_list)
                                is_match = True
                                break
                            else: 
                                break

CodePudding user response:

I suggest encapsulating your code into functions; each logical block that does one precise thing should be one function.

This will make it much much easier for everyone to understand your code. By "everyone" I mean: StackOverflow users who read your questions; your colleagues; and more importantly, yourself now; and yourself in one month when you look at your own code with fresh eyes.

So, make a small function that takes a list of values, and a list of target sums, and checks if two values add to a target:

from itertools import combinations

def catch_pairs_that_add_to_target(values, targets):
    targets_set = set(targets)
    caught_pairs = []
    for x,y in combinations(values, 2):
        if x   y in targets_set:
            caught_pairs.append((x,y))
    return caught_pairs

# TESTING
print( catch_pairs_that_add_to_target([100, 42, 7, 158], [200, 107, 25, 30]) )
# [(100, 7), (42, 158)]

If we're dealing with floats, we shouldn't test for exact equality; there is math.isclose for that case:

from itertools import combinations
from math import isclose

def catch_pairs_that_add_to_target(values, targets):
    caught_pairs = []
    for x,y in combinations(values, 2):
        if any(isclose(x   y, z, abs_tol=0.2) for z in targets):
            caught_pairs.append((x,y))
    return caught_pairs

# TESTING
print( catch_pairs_that_add_to_target([100.1, 42.05, 7.07, 158.1], [200.0, 107.0, 25.0, 30.0]) )
# [(100.1, 7.07), (42.05, 158.1)]

Relevant documentation:

  • itertools.combinations to iterate on all pairs of values;
  • set because x y in targets is much faster if targets is a set than if it is a list;
  • math.isclose to test for approximate equality of floating-points;
  • any to check whether at least one element satisfies a predicate.
  • Related