[Python] Given a list of numbers, find all matrices such that each column and row sum up to 264

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    Let's say I have a list of 16 numbers. With these 16 numbers I can create different 4x4 matrices. I'd like to find all 4x4 matrices where each element in the list is used once, and where the sum of each row and each colum is equal to 264.

    First I find all combination of elements within the list that sum up to 264

    numbers = [11, 16, 18, 19, 61, 66, 68, 69, 81, 86, 88, 89, 91, 96, 98, 99]

    candidates = []
    result = [x for x in itertools.combinations(numbers, 4) if sum(x) == 264]


    result becomes a list where each element is a list with 4 elements, where the sum of the 4 elements = 264. I think of these as my rows. Then I'd like to take all permutations of my rows, since addition is commutative.

    for i in range(0, len(result)):
    candidates.append(list(itertools.permutations(result)))


    Now given all my possible rows where the sum is 264. I'd like to choose all combinations of 4 rows, such that every column's sum is 264.

    test = []
    for i in range(0, len(candidates)):
    test = test + candidates
    result2 = [x for x in itertools.combinations(test, 4) if list(map(add, x[0], list(map(add, x[1], list( map(add, x[2], x[3])))))) == [264, 264, 264, 264]]


    Is there a faster/better way? The last part, finding all combinations of 4 rows, takes a lot of time and computer power.

    Continue reading...

Compartilhe esta Página