Home > Software design >  I need to see if the sum of an internal list (list in a list) is between 2 values using iteration
I need to see if the sum of an internal list (list in a list) is between 2 values using iteration

Time:10-05

if any of the internal lists' has a sum between the lower and upper bound, that list returns. If not it comes back False

for example:

sum([[1,2,3], [4,5,6] [7,8,9], [1000], (10000, 10001)], 900, 11000)

[1000]

CodePudding user response:

Are you using a tuple (10000, 10001) on purpose? If that is in your data, you need to use isinstance()

Example:

data = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1000], (500, 600)]
min_val = 900
max_val = 11000

You can either use a function or a list comprehension (since an empty list evaluates to False.

output = [elem for elem in data if isinstance(elem, list) and min_val <= sum(elem) <= max_val] or False  # [[1000]]

as a function:

def your_function(data, min_val, max_val):
    return [elem for elem in data if isinstance(elem, list) and min_val <= sum(elem) <= max_val] or False

CodePudding user response:

Iterate through, check if the sum of the subarray is within the bounds and return. At the end of the function, just return False since if we get here, there was no valid sum in the array.

def my_sum(arr, low, up):
    for sub in arr:
        if low < sum(sub) < up:
            return sub
    return False
  • Related