Home > Mobile >  deleting every nth element from a list until 1 element remains
deleting every nth element from a list until 1 element remains

Time:10-02

I have a numlist 1 to x and I should delete every nth element until 1 remains similar to the Josephus problem but instead of going in a circle, you start iterating from the beginning. If you had a list [1,2,3,4,5,6,7,8,9,10] and n = 3, first iteration removes 3,6,9. Second iteration removes 4 (would be 2 if it were in a circle) and then 8. Third iteration removes 5 and so on until n > len(players) then it could go in a circle.

players = list(range(1, int(input())   1))
n = (int(input()) - 1)
innocent = (n) % len(players)

while len(players) > 1:
    loser = players.pop(innocent)
    innocent = (innocent   n) % len(players)

print(*players)

This code deletes every nth element until 1 is left but it goes in a circle and doesn't iterate from the beginning when it reaches the end of the list each time. How would I change it to do as I explained above?

CodePudding user response:

This would solve your problem use a while loop if len(A) >= n delete nth elements ```if len(A) < n and len(A) >1`` delete the last element.

A = [h for h in range(1,11)]
n = 3
potentials = [i-1 for i in range(len(A)) if i%n == 0][1:]
B = {}
k = 0

while len(A) > 1: 
    if len(A) >= n:
        A = [A[j] for j in range(len(A)) if j not in potentials]
        B[k] = A
        k  =1
    else :  
        A = A[:-1]
        B[k] = A
        k  =1

print(B)
Out: 
{0: [1, 2, 4, 5, 7, 8, 10],
 1: [1, 2, 5, 7, 10],
 2: [1, 2, 7, 10],
 3: [1, 2, 10],
 4: [1, 2],
 5: [1]}

To adjust to your problem


players = list(range(1, int(input())   1))
n = (int(input()) - 1)

potentials = [i-1 for i in range(len(players)) if i%n == 0][1:] # position of elements that will be deleted in each iteration

while len(players ) > 1:
    if  len(players ) >= n: 
        losers =  [players[j] for j in range(len(players)) if j in potentials] #I assume losers are the ones being deleted
        players = [players[j] for j in range(len(players)) if j not in potentials]
    else: 
        losers =  players[-1]
        players = players[:-1]

  • Related