-1

Question:

Suppose you have a list:

  1. Delete every nth element.
  2. If the next nth element exceeds the list's length, modulate it.
  3. Do it till one element left.

Example:

a = [1, 2, 3, 4, 5, 6, 7, 8]
period = 3

for each iteration a must be:

a = [1, 2, 3, 4, 5, 6, 7, 8]
a = [1, 2, 4, 5, 6, 7, 8]
a = [1, 2, 4, 5, 7, 8]
a = [2, 4, 5, 7, 8]
a = [2, 4, 7, 8]
a = [4, 7, 8]
a = [4, 7]
a = [7]

I must know.

I'm editing this because I forgot to add what I did and not succeed.

Here my attempt:

a = [1, 2, 3, 4, 5, 6, 7, 8]
periyot = 3


for it, i in enumerate(range(periyot, periyot * len(a), periyot), start=1):
    index = (i - it) % len(a)
    del a[index % len(a)]
    print(a)

Which returns:

[1, 2, 4, 5, 6, 7, 8]
[1, 2, 4, 5, 7, 8]
[2, 4, 5, 7, 8]
[2, 4, 5, 8] # I'm off from here
[2, 4, 8]
[4, 8]
[8]
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
MSH
  • 1,743
  • 2
  • 14
  • 22
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). “Show me how to solve this coding problem” is not a Stack Overflow issue. We expect you to make an honest attempt, and *then* ask a *specific* question about your algorithm or technique. Stack Overflow is not intended to replace existing documentation and tutorials. – Prune Dec 03 '20 at 20:11
  • Also see Stack Overflow guidance on [homework](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions). Simply dumping your assignment here is unacceptable. – Prune Dec 03 '20 at 20:11
  • I forgot to add the code I wrote. Edited the question. – MSH Dec 03 '20 at 20:17
  • I've already voted to close for lack of focus; otherwise I'd close for [this duplicate](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating). You also should trace your code to explain just *how* it's getting the wrong answer. You point to an error in the `print` output -- trace the data flow back to the source. – Prune Dec 03 '20 at 20:21
  • What does "modulate it" mean? – martineau Dec 03 '20 at 20:27
  • @Prune I appreciate you teaching me what should I do. You're most probably right to say to trace my code. However, I can't. And the problem is here. I can't find a way to find my mistake. – MSH Dec 03 '20 at 20:40
  • @martineau with modulate I meant Modular arithmetic. Index%len(list) – MSH Dec 03 '20 at 20:56

1 Answers1

1

This is one way to do it.

a = [1, 2, 3, 4, 5, 6, 7, 8]
period = 3

idx = (period - 1)
while len(a) > 1:
  idx = idx % len(a)
  del a[idx]
  idx += (period - 1)
  print(a)