Search code examples
pythonarraysdictionarymatrixsum

Python: How to sum values from a 3d array, where the last array is a dictionary using functional map and sum



(This is Advent Of Code day 4, I already have my stars, but I'd like to do it more efficiently)
I have a 3d matrix like this one:

[
    [
        [{22: 0}, {13: 0}, {17: 1}, {11: 1}, {0 : 1}],
        [{8 : 0}, {2 : 1}, {23: 1}, {4 : 1}, {24: 1}],
        [{21: 1}, {9 : 1}, {14: 1}, {16: 0}, {7 : 1}],
        [{6 : 0}, {10: 0}, {3 : 0}, {18: 0}, {5 : 1}],
        [{1 : 0}, {12: 0}, {20: 0}, {15: 0}, {19: 0}]
    ],

    [
        [{3 : 0}, {15: 0}, {0 : 1}, {2 : 1}, {22: 0}],
        [{9 : 1}, {18: 0}, {13: 0}, {17: 1}, {5 : 1}],
        [{19: 0}, {8 : 0}, {7 : 1}, {25: 0}, {23: 1}],
        [{20: 0}, {11: 1}, {10: 0}, {24: 1}, {4 : 1}],
        [{14: 1}, {21: 1}, {16: 0}, {12: 0}, {6 : 0}]
    ], 
    
    [
        [{14: 1}, {21: 1}, {17: 1}, {24: 1}, {4 : 1}],
        [{10: 0}, {16: 0}, {15: 0}, {9 : 1}, {19: 0}],
        [{18: 0}, {8 : 0}, {23: 1}, {26: 0}, {20: 0}], 
        [{22: 0}, {11: 1}, {13: 0}, {6 : 0}, {5 : 1}], 
        [{2 : 1}, {0 : 1}, {12: 0}, {3 : 0}, {7 : 1}]
    ]
]

And I want to sum all values from one of those matrices using map/sum functions. This is what I have now and works:

# z is one of those matrices, 0, 1 or 2
soma = 0
for line in matrices[z]:  # line is a list of dictionaries
    for dic in line:      # dic is a dictionary from the list
        valor = list(dic.values())[0]
        if valor == 0:
            soma += list(dic.keys())[0]

What I've tried to do:

print("soma = ", sum(map(sum, ( (value.values())[0] for value in matrizes[z]))))

which doesnt work, and I get this error: Traceback (most recent call last):

File "day4.py", line 75, in <module>
print("part 1 = ", sum(map(sum, ((value.values())[0] for value in matrizes[z]))))
File "day4.py", line 75, in <genexpr>
print("part 1 = ", sum(map(sum, ((value.values())[0] for value in matrizes[z]))))
AttributeError: 'list' object has no attribute 'values'

I've found a post with 2d arrays, but couldnt understand how to make it for 3d arrays.
I've also found posts using "numpy", but I want to do with map and sum functions.


Solution

  • You can do:

    z = 0
    soma = sum(map(lambda line: sum(k for d in line for k, v in d.items() if v == 0), matrices[z]))
    print(soma) # 163