โจทย์: วนลูปแสดงสมาชิกในลิสต์แบบ Cyclic (วนรอบ) เริ่มจาก Index ที่กำหนด
Input/Output
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] start_index = 5 Output: f g h a b c d e
วิธีแก้: ใช้ Modulo Operator (%)
ใช้ index % length เพื่อให้ index วนกลับมาที่ 0 เมื่อถึงปลายลิสต์
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
start_index = 5
length = len(alphabets)
for i in range(length):
element_index = start_index % length
print(alphabets[element_index], end=' ')
start_index += 1
ผลลัพธ์
f g h a b c d e
การประยุกต์: เทคนิคนี้ใช้ได้กับ Circular buffer, Round-robin scheduling, และการวนลูปเมนู/ตัวเลือกแบบ Circular
วิธีสั้นกว่าด้วย itertools:
from itertools import cycle, islice
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
start_index = 5
result = list(islice(cycle(alphabets), start_index, start_index + len(alphabets)))
print(' '.join(result))