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

หาค่าสูงสุดในลิสต์ A ตรงตำแหน่งที่ลิสต์ B มีค่าเท่ากับ K

แนวคิด

มี 2 ลิสต์ขนาดเท่ากัน หา index ที่ลิสต์ที่ 2 มีค่า == K แล้วนำค่าตรง index นั้นในลิสต์ที่ 1 มาหาค่าสูงสุด

ตัวอย่างโค้ด

list1 = [62, 25, 32, 98, 75, 12, 46, 53]
list2 = [91, 42, 48, 76, 23, 17, 42, 83]

print("List 1:", list1)
print("List 2:", list2)

K = 42
print("K =", K)

# เรียงลิสต์ทั้งคู่ (ในตัวอย่างต้นฉบับทำการ sort ก่อน)
list1.sort()
list2.sort()
print("List 1 sorted:", list1)
print("List 2 sorted:", list2)

# หาค่าใน list1 ที่ index ตรงกับ list2 == K
candidates = [list1[i] for i in range(len(list1)) if list2[i] == K]
result = max(candidates) if candidates else None

print("ค่าสูงสุดใน list1 ที่ list2 == K:", result)

ผลลัพธ์

List 1: [62, 25, 32, 98, 75, 12, 46, 53]
List 2: [91, 42, 48, 76, 23, 17, 42, 83]
K = 42
List 1 sorted: [12, 25, 32, 46, 53, 62, 75, 98]
List 2 sorted: [17, 23, 42, 42, 48, 76, 83, 91]
ค่าสูงสุดใน list1 ที่ list2 == K: 46

คำอธิบาย

  • หลัง sort: list2 มี 42 อยู่ index 2 และ 3
  • list1 index 2 = 32, index 3 = 46
  • max(32, 46) = 46

⚠️ หมายสำคัญ

การ sort() แยกกันทำให้ความสัมพันธ์ index เดิมหายไป! ตัวอย่างนี้ sort ทั้งคู่แยกกันจึงได้ผลลัพธ์ที่อาจไม่ตรงกับเจตนาเดิม หากต้องการรักษาคู่ (pair) ควรใช้ zip:

pairs = list(zip(list1, list2))
candidates = [a for a, b in pairs if b == K]
result = max(candidates) if candidates else None