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

Python: หาแถวที่มีเลข 1 มากที่สุดใน Matrix ด้วย map()

โจทย์: กำหนด Matrix (List of Lists) ที่ประกอบด้วย 0 และ 1 ให้หา Index ของแถวที่มีจำนวนเลข 1 มากที่สุด โดยใช้ฟังก์ชัน map()

ตัวอย่าง

matrix = [
    [0, 0, 1],
    [1, 1, 1],
    [1, 1, 0]
]
# Row 0: 1 one
# Row 1: 3 ones <- มากที่สุด (Index 1)
# Row 2: 2 ones

วิธีที่ 1: ใช้ map() + Function (ตามโจทย์)

def count_ones(row):
    """นับจำนวน 1 ในแถว"""
    count = 0
    for val in row:
        if val == 1:
            count += 1
    return count

matrix = [
    [0, 0, 1],
    [1, 1, 1],
    [1, 1, 0]
]

# map คืนค่า Iterator -> แปลงเป็น List
ones_count = list(map(count_ones, matrix))
print(f"Count per row: {ones_count}")  # [1, 3, 2]

# หา Index ของค่าสูงสุด
max_index = ones_count.index(max(ones_count))
print(f"Row with most 1's: {max_index}")  # 1

วิธีที่ 2: ใช้ map() + Lambda (Concise)

ones_count = list(map(lambda row: row.count(1), matrix))
max_index = ones_count.index(max(ones_count))
print(max_index)  # 1

วิธีที่ 3: ใช้ sum() (Pythonic สำหรับ Binary)

เพราะ 0+1 = 1, ผลรวมของแถว = จำนวน 1

ones_count = list(map(sum, matrix))
max_index = ones_count.index(max(ones_count))
print(max_index)  # 1

วิธีที่ 4: ใช้ enumerate() + max() (Single Pass)

หา Index และ Max พร้อมกัน ไม่ต้องสร้าง List กลาง

# ใช้ key function ใน max()
max_index = max(enumerate(map(sum, matrix)), key=lambda x: x[1])[0]
print(max_index)  # 1

วิธีที่ 5: NumPy (สำหรับ Matrix ใหญ่/Production)

import numpy as np

matrix_np = np.array([
    [0, 0, 1],
    [1, 1, 1],
    [1, 1, 0]
])

# Sum ตาม Axis=1 (แถว)
row_sums = matrix_np.sum(axis=1)
max_index = row_sums.argmax()
print(max_index)  # 1

กรณีที่มีหลายแถวเท่ากัน (Tie Handling)

def find_all_max_rows(matrix):
    """คืน Index ทั้งหมดที่มี 1 มากที่สุด"""
    ones_count = list(map(sum, matrix))
    max_count = max(ones_count)
    return [i for i, count in enumerate(ones_count) if count == max_count]

# ทดสอบ Tie
matrix_tie = [
    [1, 1, 0],  # 2 ones
    [1, 0, 1],  # 2 ones
    [0, 1, 1],  # 2 ones
    [1, 1, 1],  # 3 ones - max
]
print(find_all_max_rows(matrix_tie))  # [3]

matrix_tie2 = [
    [1, 1, 0],  # 2
    [1, 0, 1],  # 2
    [0, 1, 1],  # 2
]
print(find_all_max_rows(matrix_tie2))  # [0, 1, 2] (ทั้ง 3 แถว)

การประยุกต์: Matrix ที่ไม่ใช่ Binary

# หาแถวที่ Sum มากที่สุด (General Case)
matrix = [
    [3, 5, 2],
    [10, 1, 1],
    [4, 4, 4]
]

max_index = max(enumerate(map(sum, matrix)), key=lambda x: x[1])[0]
print(max_index)  # 1 (Sum=12)

สรุป

วิธีCodeเหมาะสำหรับ
map + functionmap(count_ones, matrix)เข้าใจง่าย, ตามโจทย์ที่กำหนด
map + lambdamap(lambda r: r.count(1), m)สั้น, ใช้ได้กับ List ทั่วไป
map + summap(sum, matrix)Binary Matrix, Pythonic
enumerate + maxmax(enumerate(map(sum, m)), key=...)Single Pass, Memory Efficient
NumPynp.array(m).sum(1).argmax()Large Matrix, Data Science