Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมหา transpose ของเมทริกซ์ใน Python

Transpose เมทริกซ์ n x n: สลับแถวและคอลัมน์ (matrix[r][c] ↔ matrix[c][r])

ตัวอย่าง: [[7,2,6], [[7,3,5], [3,7,2], → [2,7,3], [5,3,7]] [6,2,7]]

อัลกอริธึม

  • สร้างเมทริกซ์ใหม่: คอลัมน์เก่า → แถวใหม่
  • ใช้ nested loop หรือ list comprehension

การนำไปใช้

class Solution:
    def solve(self, matrix):
        M = []
        tracker = 0
        while tracker < len(matrix):
            temp = []
            for row in matrix:
                temp += [row[tracker]]
            M += [temp]
            tracker += 1
        return M

ob = Solution()
matrix = [[7,2,6], [3,7,2], [5,3,7]]
print(ob.solve(matrix))
# [[7,3,5], [2,7,3], [6,2,7]]