1

AI have multiple arrays I'm putting into the itertools.product().

Array lengths:

A - 108
B - 126
C - 5
D - 8
E  -8

It takes me a good few minutes to process the arrays and I was wondering if there's another way to speed it up.

total = 0
maxPoints = 0

for combination in itertools.product(A, B, C, D, E):
currentTotal  = int(combination[0][1]) + int(combination[1][0][1]) + int(combination[1][1][1]) + int(combination[1][2][1]) +int(combination[2][0][1]) + int(combination[2][1][1])  + int(combination[2][2][1])  + int(combination[1][0][1])  + int(combination[1][1][1])
if currentTotal < 50000:
    pointTotal  = float(combination[0][2]) + float(combination[1][0][2]) + float(combination[1][1][2]) + float(combination[1][2][2]) + float(combination[2][0][2]) + float(combination[2][1][2])  + float(combination[2][2][2]) +  float(combination[1][0][2]) + float(combination[1][1][2])
    if currentTotal >= total:
        if pointTotal > maxPoints:
            total = currentTotal
            maxPoints = currentPoints
6
  • 2
    Have you tried running your code under PyPy? Commented Sep 10, 2015 at 23:27
  • 2
    Just as a side note. If you're solving task from Project Euler or similar website - the best way is to find good algorithm and not to optimize brute forcing code. Commented Sep 10, 2015 at 23:29
  • @Alex technically just installed Pypy after you mentioned it and it looks like I need to find a solution for mysql.connector. Pypy might be a last resort if I have to modify my code to adapt to it.
    – Marquisk2
    Commented Sep 10, 2015 at 23:34
  • @Yaroslav Project Euler looks interesting. I'll bookmark it for later.
    – Marquisk2
    Commented Sep 10, 2015 at 23:36
  • 1
    The code you show never uses the values from the D or E lists, so you can probably leave them out of your product call to reduce the amount of work by a 64 times.
    – Blckknght
    Commented Sep 11, 2015 at 0:10

1 Answer 1

2

You probably won't be able to optimize that any further using just pure python code.

For any serious number crunching I would suggest using numpy.

Here is a cartersian product implementation in numpy that you can use:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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