Home > database >  Itertools combinations: How to get the ids of the first fitting value combination
Itertools combinations: How to get the ids of the first fitting value combination

Time:06-10

I have a record with a unique ID and an associated value in EURO. Now I want to get the first combination of values ​​that matches a value I defined. So far I only get the combination of the values, but I would like to have the IDs of the respective values ​​also in the output.

  • Actual result:
List->  20.5 10.0 12.0 
  • Desired result:
List-> 1:20.5 3:10.0 5:12.0

Two separated list would also be fine

Here is my first approach:

from itertools import combinations
import numpy as np
import pandas as pd

# initialize list of lists
data = [[1 , 20.5], [2 , 32.0], [3 , 10.0], [4 , 5.0], [5 , 12.0], [6 , 10.0], [7, 2.0], [8 , 1.0], [9 , 6.0], [10 , 3.0], [11, 2.0]]
 
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['ID', 'EUR'])
summed_amount = 42.5

# Get All Possible Combinations Of Numbers In List
for value in range(1, len(df)  1):
    possible_combination = list(combinations(df['EUR'], value))
    #get the first values which equals the desired amount (summed_amount)
    li =[each for each in possible_combination if sum(each) == summed_amount]
    if li:
        print("List-> ", *li[0])
        break

RESULT:

List->  20.5 10.0 12.0

Thanks and kind regards :)

CodePudding user response:

There are some ways you can do that. You need to somehow store the values with their ids. You can do workarounds in pandas for that, or do a more elegant solution with your own custom class. Take a look:

class MyAmount(object):
  def __init__(self, id, value):
    self.id = id
    self.value = value

  def __radd__(self, other):
    return self.value   (other.value if isinstance(other, MyAmount) else other)
    
  def __repr__(self):
    return "{}: {}".format(self.id, self.value)

Here we create our own class, MyAmount, with our own custom logic. Then, we can just create MyAmount objects for each row.

amounts = df.apply(lambda s: MyAmount(s.ID, s.EUR), axis=1)

Now, just keep your code, but make sure to use amounts to find the combinations.

possible_combination = list(amounts, value))

Since we overrode the __radd__ magic function, sum(each) will sum over the value property of MyAmount. And since we overrode __repr__, when you print a MyAmount object, you'll display a string with format id: value.

You can customize this however you want.

  • Related