Home > Software engineering >  how to solve a matrix issue
how to solve a matrix issue

Time:02-27

Hello I have a problem I dont know how to solve.

I have a list like:

list=[(House, Dog, 7), (House, Cat, 5), (Garden, Dog, 4), (Garden, Cat, 3), (Park,Mouse,2)]

The solution must be:

result = [
          ['' ,  Dog,  Cat, Mouse],
          [House,  7,    5,    ''],
          [Garden, 4,    3,    ''],
          [Park,  '',   '',    2 ]
         ]  

I tried to seperate die lists like below and started with some super complicated code that is not working .

A = [House, House, Garden, Garden, Park]
B = [Dog, Cat, Dog, Cat, Mouse] 
C = [ 7,5,4,3,2]

the first positions in the sets is awlays the first column, the second the first row and the third are the numbers in the matrix but the names only appears once.

Would be good if someone coud show me a solution. Thanks.

CodePudding user response:

This will maintain the order of column/row names and produce the requested solution:

from collections import OrderedDict

input = [('House', 'Dog', 7), ('House', 'Cat', 5), ('Garden', 'Dog', 4), ('Garden', 'Cat', 3), ('Park', 'Mouse', 2)]

column_names = list(OrderedDict.fromkeys(item[1] for item in input))
row_names = list(OrderedDict.fromkeys(item[0] for item in input))

result = [[''] * (len(column_names)   1) for i in range(len(row_names)   1)]

for i in range(len(column_names)):
    result[0][i 1] = column_names[i]

for i in range(len(row_names)):
    result[i 1][0] = row_names[i]

for item in input:
    result[row_names.index(item[0])   1][column_names.index(item[1])   1] = item[2]

print(result)

CodePudding user response:

from collections import Counter

data = [("House", "Dog", 7), ("House", "Cat", 5), ("Garden", "Dog", 4), ("Garden", "Cat", 3), ("Park", "Mouse", 2)]

header = [""]
column = [""]
counts = Counter();

for place, animal, count in data:
    if animal not in header:
        header.append(animal)
    if place not in column:
        column.append(place)

    counts[(place, animal)]  = count

result = [header]
for (place, animal), count in counts.items():
    col = header.index(animal)
    row = column.index(place)
    if row >= len(result):
        result.append([place]   [""] * (len(header) - 1))

    result[row][col] = count
  • Related