Write a Python program to remove and print every third number from a list of numbers until the list becomes empty
Input : [1, 2, 3, 4]
Output : 3 2 4 1
Explanation:
The first third element encountered is 3, after 3 we start the count from 4 for the next third element which is 2. Then again the count starts from 4 for the next third element which is 4 itself and finally the last element 1 is printed.
example 1:-
def remove_nums(int_list):
#list starts with 0 index
position = 3 - 1
idx = 0
len_list = (len(int_list))
while len_list>0:
idx = (position+idx)%len_list
print(int_list.pop(idx))
len_list -= 1
nums = [10,20,30,40,50,60,70,80,90]
remove_nums(nums)
output:-
30
60
90
40
80
50
20
70
10
>>>
example 2:-
# Python program to remove to every third
# element until list becomes empty
def removeThirdNumber(int_list):
# list starts with
# 0 index
pos = 3 - 1
index = 0
len_list = (len(int_list))
# breaks out once the
# list becomes empty
while len_list > 0:
index = (pos + index) % len_list
# removes and prints the required
# element
print(int_list.pop(index))
len_list -= 1
# Driver code
nums = [1, 2, 3, 4]
removeThirdNumber(nums)
output:-3
2
4
1
>>>
Post a Comment
If you have any doubts, Please let me know
Thanks!