1

I have a dataframe with name of persons in the index and name of fruits in columns, and the values are the distance from person to fruit. Like this

(index)   apple  orange  lemon  grape
John      22.3   13.1    14.9   8.8
Mike      12.1   14.2    11.3   5.3
Kevin     9.13   14.9    3.3    22.3
Leon      11.9   13.2    7.14   21.1
Joe       1.15   23.12   11.11  3.18
Frank     4.13   4.13    3.12   29.3
Ralph     7.8    23.1    14.4   29.0

A person only can pick one fruit and I need to find the overall lowest distance (so i need to sum the total distance of all the combinations and fint the lowest) and the name of the person that is picking each fruit.

THe best way to solve this is using itertools.permutation?

0

Assuming that you need each fruit to be picked by a different person, you can use itertools皇冠hg0088代理网址 to evaluate all possible combinations of name and fruit, but this will be intractable for larger problems.

A typical solution is to use . Python has many libraries that can help you solving IP problems. For example, below is a solution to you problem using the library:

import numpy as np
import pandas as pd
import cvxpy as cp
from io import StringIO

data = """name   apple  orange  lemon  grape
John      22.3   13.1    14.9   8.8
Mike      12.1   14.2    11.3   5.3
Kevin     9.13   14.9    3.3    22.3
Leon      11.9   13.2    7.14   21.1
Joe       1.15   23.12   11.11  3.18
Frank     4.13   4.13    3.12   29.3
Ralph     7.8    23.1    14.4   29.0"""
df = pd.read_csv(StringIO(data), sep="\s+", index_col=0)

# Define the decision variable as a matrix of boolean values with 
# len(names) rows and len(fruits) columns
x = cp.Variable(shape=(len(df.index), len(df.columns)), boolean=True)

# Define the objective function as the sum distances
objective = cp.sum(cp.multiply(df.values, x))

# Constrain the problem so that each person picks a single fruit 
# and each fruit is picked by someone
constraint1 = cp.sum(x, axis=0) == 1
constraint2 = cp.sum(x, axis=1) <= 1

# Define the problem and fins solution
problem = cp.Problem(cp.Minimize(objective), [constraint1, constraint2])
problem.solve()

皇冠hg0088代理网址The result is:

>>> x.value.round()
array([[0., 0., 0., 0.],
       [0., 0., 0., 1.],
       [0., 0., 1., 0.],
       [0., 0., 0., 0.],
       [1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 0., 0.]])

Meaning that Joe picks the apple, Frank picks the orange, Kevin picks the lemon, and Mike picks the grape.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.