แนวคิด
จากลิสต์ของ tuples ให้คืนเฉพาะ tuple ที่สมาชิกเป็นตัวเลขเรียงติดกัน (consecutive integers) เช่น (23,24,25,26) diff=1
ตัวอย่างโค้ด
def check_consec_tuple_elem(tup):
for i in range(len(tup) - 1):
if tup[i+1] != tup[i] + 1:
return False
return True
my_tuples = [(23, 24, 25, 26), (65, 66, 78, 29), (11, 28, 39), (60, 61, 62, 63)]
print("ลิสต์ Tuple:", my_tuples)
result = [t for t in my_tuples if check_consec_tuple_elem(t)]
print("Tuple consecutive:", result)
ผลลัพธ์
ลิสต์ Tuple: [(23, 24, 25, 26), (65, 66, 78, 29), (11, 28, 39), (60, 61, 62, 63)]
Tuple consecutive: [(23, 24, 25, 26), (60, 61, 62, 63)]
คำอธิบาย
- (23,24,25,26): 24=23+1, 25=24+1, 26=25+1 ✓
- (65,66,78,29): 66=65+1 ✓, 78≠66+1 ✗
- (11,28,39): 28≠11+1 ✗
- (60,61,62,63): ตรงกันทั้งหมด ✓
รองรับ Descending (เรียงลด)
def check_consec(tup, ascending=True):
if len(tup) < 2:
return True
step = 1 if ascending else -1
return all(tup[i+1] == tup[i] + step for i in range(len(tup)-1))