Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete elements of a circular list until there is only one element left using python? [closed]

How would I go about iterating through a list from 1-100, where I delete every other element starting with the first element, and repeat that step until there in only one element left in the list. Would I have to use a circular linked list, or can it be done just using loops and conditional statements?

like image 351
stochasticcrap Avatar asked Dec 26 '22 13:12

stochasticcrap


2 Answers

This deletes every other element over and over until just one is left

>>> L = range(100)       # for Python3, use L = list(range(100))
>>> while len(L) > 1:
...     del L[::2]
... 
>>> L
[63]

I'm not sure what the "circular list" means, but maybe this modification is needed

>>> L = range(100)
>>> while len(L) > 1:
...     del L[len(L)%2::2]
... 
>>> L
[99]

The len(L)%2 means to del L[1::2] if the length of L is odd

Or if you like to see what's going on:

>>> L = range(100)
>>> while len(L) > 1:
...     del L[len(L)%2::2]
...     L
... 
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
[3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47, 51, 55, 59, 63, 67, 71, 75, 79, 83, 87, 91, 95, 99]
[3, 11, 19, 27, 35, 43, 51, 59, 67, 75, 83, 91, 99]
[3, 19, 35, 51, 67, 83, 99]
[3, 35, 67, 99]
[35, 99]
[99]
like image 84
John La Rooy Avatar answered Jan 11 '23 23:01

John La Rooy


How about using Python's handy slice syntax:

while len(best_list_ever) > 1:
    best_list_ever = best_list_ever[1::2]

The expression best_list_ever[1::2] is a list of every other element in the original list.

Edit: I'm actually pretty confused about the circular constraint thing, but if it's accurately documented by ysakamoto then maybe look to gnibbler's answer.

like image 34
jayelm Avatar answered Jan 11 '23 23:01

jayelm