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

Python - ทดสอบว่าสมาชิกในลิสต์อยู่ในช่วง Min/Max ของอีกลิสต์หนึ่ง

ตรวจสอบว่าทุกค่าใน range_list อยู่ในช่วง Min-Max ของ my_list หรือไม่ (Logic ในโค้ดตัวอย่างมีข้อบกพร่อง)

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

my_list = [5, 6, 4, 7, 8, 13, 15]
print("The list is : ")
print(my_list)

range_list = [4, 7, 10, 6]
my_result = True

for elem in range_list:
    if elem != max(my_list):
        my_result = False
        break

if my_result == True:
    print("All the elements are in the min/max range")
else:
    print("All the elements are not in the min/max range")

ผลลัพธ์

The list is : [5, 6, 4, 7, 8, 13, 15]
All the elements are not in the min/max range

คำอธิบาย

  • โค้ดตัวอย่าง Logic ผิด: เช็ค elem != max(my_list) (เท่ากับ Max หรือไม่) ไม่ใช่เช็คช่วง Min-Max
  • ถ้าต้องการเช็คช่วง: if not (min(my_list) <= elem <= max(my_list)):
  • my_list: Min=4, Max=15 -> ช่วง 4-15
  • range_list: 4,7,10,6 -> ทุกตัวอยู่ในช่วง 4-15 -> ควรเป็น True
  • โค้ดเดิม: 4 != 15 -> False -> Break -> ผลลัพธ์ผิด