0
name1 = input("name2: ") name2 = input("name1: ") def popcommonchar(name1, name2): str1 = '' for s in (name1): if s not in name2: str1 += s str2 = '' for s in (name2): if s not in n1: str2 += s list = ["A", "B", "C", "D", "E", "F"] while True: if len(list) == 1: break e = (len(str1)) + (len(str2)) sum =+ e list.pop(e) print(list) popcommonchar(name1, name2) 

after removing the 5th item in the list, I want the program keep counting and poping/removing the 5th element. When N is the sum from length of str and str2, I want to remove the Nth item from the list ["A", "B", "C", "D", "E", "F"].

after removing F, it prompts an error, how to I fix this?

3 Answers 3

2

You need to maintain the index at which the player is removed and your k to it (5 in this case), when the length of list becomes smaller that the number, take mod of the number with the length of the list, so that it gives you the next index which needs to be removed.

l1 = ["A1", "B2", "C3", "D4", "E5", "F6"] k = 5 currentIndex = 0 while len(l1) != 1: currentIndex = (currentIndex + k - 1) % len(l1) l1.pop(currentIndex) print(l1) Output: ['A1', 'B2', 'C3', 'D4', 'F6'] ['A1', 'B2', 'C3', 'F6'] ['A1', 'B2', 'C3'] ['A1', 'C3'] ['A1'] 
Sign up to request clarification or add additional context in comments.

2 Comments

I just need to print the last element remaining, how do i do that? Btw, thank you for your suggestion!
Remove the print statement out of the while loop and print(l1[0]) or I would return the value, and let the main function do the printing job.
0

The naive fix is to keep rotating your index within the current length. Instead of

sum =+ e 

do

sum = (sum + e) % len(l1) 

However, the easiest and probably most performant approach would use deque.rotate:

from collections import deque q = deque(["A1", "B2", "C3", "D4", "E5", "F6"]) e = 5 while len(q) > 1: q.rotate(1-e) print(q.popleft()) print(q) E5 D4 F6 B2 C3 deque(['A1']) 

4 Comments

i would like to consider your suggestion but we are not allowed to import from the libraries in python :((( but thank you! Appreciated!
After applying your "naive fix", it gets UnboundLocalError: local variable 'sum' referenced before assignment.
YOu should then put the line sum = 0 at the beginning of the function.
Done that, gets IndexError: pop index out of range then.
0

Keep in mind that pop() removes the item, and the list changes length after the pop. So, you can just use pop() with no arguments for the end item. I mean you have to change l1.pop(e) to l1.pop() in your code.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.