ขั้นแรก เราสร้างรายการ ดัชนีของที่อยู่เริ่มต้นคือ 0 และตำแหน่งขององค์ประกอบที่สามแรกคือ 2 และต้องสำรวจจนกว่ารายการจะว่างเปล่า และงานสำคัญอีกอย่างที่ต้องทำทุกครั้งที่ต้องหาดัชนีถัดไป องค์ประกอบที่สามและพิมพ์ค่าแล้วลดความยาวของรายการ
ตัวอย่าง
A:[10,20,30,40] OUTPUT:30 20 40 10
คำอธิบาย
องค์ประกอบที่สามแรกคือ 30 จากนั้นเรานับจาก 40 สำหรับองค์ประกอบที่สามถัดไป 20 จากนั้นให้เริ่มจาก 40 อีกครั้งสำหรับองค์ประกอบที่สามถัดไปคือ 40 และสุดท้ายจะพิมพ์ 10 รายการ
อัลกอริทึม
ขั้นตอนที่ 1:ดัชนีของรายการเริ่มจาก 0 และองค์ประกอบที่สามแรกจะอยู่ที่ตำแหน่ง 2
variable p=2,starting index id=0.
ขั้นตอนที่ 2:หาความยาวของรายการ
listlen=len (LST) // length of the list(LST)
ขั้นตอนที่ 3:สำรวจจนกว่ารายการจะว่างเปล่าและค้นหาดัชนีขององค์ประกอบที่สามถัดไปในแต่ละครั้ง
While(listlen>0)
Id=(p+id)%listlen
A=LST.pop(id)// removes and prints the required element
Listlen-=1
End while
โค้ดตัวอย่าง
# To remove to every third element until list becomes empty
def removenumber(no):
# list starts with
# 0 index
p = 3 - 1
id = 0
lenoflist = (len(no))
# breaks out once the
# list becomes empty
while lenoflist > 0:
id = (p + id) % lenoflist
# removes and prints the required
# element
print(no.pop(id))
lenoflist -= 1
# Driver code
A=list()
n=int(input("Enter the size of the array ::"))
print("Enter the INTEGER number")
for i in range(int(n)):
p=int(input("n="))
A.append(int(p))
print("After remove third element, The List is")
removenumber(A) # call function
ผลลัพธ์
Enter the size of the array ::9 Enter the number n=10 n=20 n=30 n=40 n=50 n=60 n=70 n=80 n=90 After remove third element, The List is 30 60 90 40 80 50 20 70 10