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

ตรวจสอบว่ารายการมีตัวเลขต่อเนื่องกันใน Python . หรือไม่


ขึ้นอยู่กับความต้องการของการวิเคราะห์ข้อมูลของเรา เราอาจต้องตรวจสอบการมีอยู่ของหมายเลขลำดับในที่เก็บข้อมูลหลาม ในโปรแกรมด้านล่าง เราจะพบว่าในองค์ประกอบของ Alist มีตัวเลขต่อเนื่องกันหรือไม่

มีช่วงและเรียงลำดับ

ฟังก์ชัน sorted จะจัดเรียงองค์ประกอบของรายการใหม่ตามลำดับการจัดเรียง จากนั้นเราใช้ฟังก์ชันช่วงโดยใช้ตัวเลขต่ำสุดและสูงสุดจากรายการโดยใช้ฟังก์ชัน min และ max เราเก็บผลลัพธ์ของการดำเนินการข้างต้นไว้ในสองรายการและเปรียบเทียบเพื่อความเท่าเทียมกัน

ตัวอย่าง

listA = [23,20,22,21,24]
sorted_list = sorted(listA)
#sorted(l) ==
range_list=list(range(min(listA), max(listA)+1))
if sorted_list == range_list:
   print("listA has consecutive numbers")
else:
   print("listA has no consecutive numbers")

# Checking again
listB = [23,20,13,21,24]
sorted_list = sorted(listB)
#sorted(l) ==
range_list=list(range(min(listB), max(listB)+1))
if sorted_list == range_list:
   print("ListB has consecutive numbers")
else:
   print("ListB has no consecutive numbers")

ผลลัพธ์

การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -

listA has consecutive numbers
ListB has no consecutive numbers

ด้วยความแตกต่างและเรียงตามลำดับ

ฟังก์ชัน diff ใน numpy สามารถค้นหาความแตกต่างระหว่างตัวเลขแต่ละตัวหลังจากที่จัดเรียงแล้ว เราใช้ผลรวมของความแตกต่างนี้ ซึ่งจะตรงกับความยาวของรายการหากตัวเลขทั้งหมดอยู่ติดกัน

ตัวอย่าง

import numpy as np
listA = [23,20,22,21,24]

sorted_list_diffs = sum(np.diff(sorted(listA)))
if sorted_list_diffs == (len(listA) - 1):
   print("listA has consecutive numbers")
else:
   print("listA has no consecutive numbers")

# Checking again
listB = [23,20,13,21,24]
sorted_list_diffs = sum(np.diff(sorted(listB)))
if sorted_list_diffs == (len(listB) - 1):
   print("ListB has consecutive numbers")
else:
   print("ListB has no consecutive numbers")

ผลลัพธ์

การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -

listA has consecutive numbers
ListB has no consecutive numbers