How to conveniently solve the task of optimizing the destination

I am working on a script that takes elements from companiesand associates them with elements people. The goal is to optimize pairing in such a way that the sum of all values ​​of the pair is maximized (the value of each individual pairing is pre-computed and stored in the dictionary ctrPairs).

All of them are paired in 1: 1, each company has only one person, and each person belongs to only one company, and the number of companies is equal to the number of people. I used a top-down approach with a notes table ( memDict) to avoid reprocessing areas that have already been resolved.

I believe that I can significantly improve the speed of what is happening here, but I'm not quite sure how to do it. The areas that concern me are marked #slow?, any advice will be appreciated (the script works for list entries n <15, but it gets incredibly slow when n> ~ 15)

def getMaxCTR(companies, people):
    if(memDict.has_key((companies,people))):
        return memDict[(companies,people)] #here where we return the memoized version if it exists
    if(not len(companies) or not len(people)):
        return 0

    maxCTR = None
    remainingCompanies = companies[1:len(companies)] #slow?

    for p in people:
        remainingPeople = list(people) #slow?
        remainingPeople.remove(p) #slow?
        ctr = ctrPairs[(companies[0],p)] + getMaxCTR(remainingCompanies,tuple(remainingPeople)) #recurse
        if(ctr > maxCTR):
            maxCTR = ctr
    memDict[(companies,people)] = maxCTR
    return maxCTR
+3
source share
4 answers

For anyone who asks about using learning theory, this question is a good illustration. The right question is not about the “quick way to bounce between lists and tuples in python” - the reason for slowness is something deeper.

, , : n n & times; n ( ), , "" (, , ). , ( Python), , LP. O (n 3).

, . ( , .) Ω (n 2 2 2n). n = 16 n 3 4096, n 2 2 2n - 1099511627776. , , . ?:-) ( , O (n!), .) O (n ^ 3), , n = 10000 , n = 15.

" - ", , / : , , , , .:-) Python , ""? (, C).

+19

:

  • : remainingPeople . remainingPeople remainingCompanies , .

  • memoization: , dict memoization; . IOW: (1,2) != (2,1) set frozenset : frozenset((1,2)) == frozenset((2,1))

+1

:

Other companies = companies [1: len (companies)]

You can replace it with this line:

remainingCompanies = companies[1:]

For a very small increase in speed. This is the only improvement I see.

0
source

If you want to get a copy of the tuple as a list, you can do mylist = list (mytuple)

0
source

Source: https://habr.com/ru/post/1710260/


All Articles