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

หาค่าสูงสุดและต่ำสุด K ค่าในทัพเพิลด้วย Python


เมื่อต้องการหา K ค่าที่มากที่สุดและ K ค่าที่น้อยที่สุดในทัพเพิล สามารถเรียงลำดับแล้วหยิบ K ตัวแรกและ K ตัวสุดท้าย

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

my_tuple = (7, 25, 36, 9, 6, 8)
print("The tuple is:", my_tuple)

K = 2
print("The value of K is:", K)

temp = sorted(my_tuple)
result = []

for idx, val in enumerate(temp):
    if idx < K or idx >= len(temp) - K:
        result.append(val)

result = tuple(result)
print("The result is:")
print(result)

ผลลัพธ์

The tuple is: (7, 25, 36, 9, 6, 8)
The value of K is: 2
The result is: (6, 7, 25, 36)

คำอธิบาย

  • แปลงทัพเพิลเป็นลิสต์ แล้วเรียงด้วย sorted() → [6, 7, 8, 9, 25, 36]

  • K = 2: หยิบ 2 ตัวแรก (6, 7) และ 2 ตัวสุดท้าย (25, 36)

  • ใช้ enumerate ตรวจสอบ index: idx < K หรือ idx >= len - K

  • รวมเป็นทัพเพิลผลลัพธ์