First we create a list, the index of the starting address is 0 and the position of the first third element is 2 and need to traverse till the list becomes empty and another important work to do every time we have to find the index of the next third element and print the value and after that reduce the length of the list.
Example
A:[10,20,30,40]
OUTPUT:30 20 40 10
Explanation
The first third element is 30, then we count from 40 for next third element 20,then again start from 40 for the next third element is 40 itself and finally 10 is printed.
Algorithm
Step 1: The index of the list starts from 0 and the first third element will be at position 2.
variable p=2,starting index id=0.
Step 2: find the length of the list.
listlen=len (LST) // length of the list(LST)
Step 3: Traverse till the list becomes empty and each time find the index of the next third element.
While(listlen>0)
Id=(p+id)%listlen
A=LST.pop(id)// removes and prints the required element
Listlen-=1
End while
Example Code
# 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
Output
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