Souljacker
Souljacker

Reputation: 774

Subset sum for a list with dict

Given aList as:

[
  {'name': 'Hailey', 'age': 20, 'id': 48479},
  {'name': 'John', 'age': 40, 'id': 18021},
  {'name': 'Asger', 'age': 18, 'id': 22281},
]

and a given target sum as targetSum = 50.

The problem is to look through aList with the key age, then remove elements from aList who's value for age cannot be combined to equal (approximately) targetSum. The elements that can be combined to equal to (approximately) targetSum should be retrievable by their id in a list.

Alternatively to avoid removing the elements, the problem is simply to find all possible combinations of the given elements which have an age attribute that sums up (approximately) to targetSum.

I have the function for finding a subset in a list to give sum. However the limitation is that it only takes a list of numbers so [1, 2, 3, 4, ...] instead of dictionaries.

def subsetInListForSum(numbers, target):
    results = []
    for x in range(len(numbers)):
        results.extend(
            [   
                combo for combo in combinations(numbers ,x)  
                    if sum(combo) == target
            ]   
        )   

    print(results)

Any help would be very much appreciated :)

Upvotes: 0

Views: 883

Answers (2)

mng
mng

Reputation: 393

Your code will work as is, since aList is still a list. You just need to change the if condition to

   if sum(val['age'] for val in combo) == target:

This way your 'results' variable will consist of all combinations of the dictionary elements from aList for which age sums up to the target value.

Upvotes: 2

SparkAndShine
SparkAndShine

Reputation: 18027

As your function works for a list, so just extract a list of ages from the list of dicts aList, and then use your function.

list_dicts = [{'name': 'Hailey', 'age': 20, 'id': 48479},
              {'name': 'John', 'age': 40, 'id': 18021},
              {'name': 'Asger', 'age': 18, 'id': 22281}]

list_ages = [d['age'] for d in list_dicts]

print(list_ages)
# Output
[20, 40, 18]

Upvotes: 0

Related Questions