จากรายการที่มีหมายเลขเรียง เราต้องการค้นหาว่าหมายเลขใดหายไปจากช่วงตัวเลขที่กำหนด
มีช่วง
เราสามารถออกแบบ for loop เพื่อตรวจสอบช่วงของตัวเลขและใช้เงื่อนไข if กับโอเปอเรเตอร์ not in เพื่อตรวจสอบองค์ประกอบที่ขาดหายไป
ตัวอย่าง
listA = [1,5,6, 7,11,14]
# Original list
print("Given list : ",listA)
# using range
res = [x for x in range(listA[0], listA[-1]+1)
if x not in listA]
# Result
print("Missing elements from the list : \n" ,res) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given list : [1, 5, 6, 7, 11, 14] Missing elements from the list : [2, 3, 4, 8, 9, 10, 12, 13]
ด้วยรหัสไปรษณีย์
ฟังก์ชัน ZIP
ตัวอย่าง
listA = [1,5,6, 7,11,14]
# printing original list
print("Given list : ",listA)
# using zip
res = []
for m,n in zip(listA,listA[1:]):
if n - m > 1:
for i in range(m+1,n):
res.append(i)
# Result
print("Missing elements from the list : \n" ,res) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given list : [1, 5, 6, 7, 11, 14] Missing elements from the list : [2, 3, 4, 8, 9, 10, 12, 13]