Reputation: 71
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?
Upvotes: 0
Views: 451
Reputation: 1245
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']
Upvotes: 2
Reputation: 1145
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.
Upvotes: 0
Reputation: 73498
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'])
Upvotes: 0