Swapping with for loop in Python don't work well

118 Views Asked by At

I have a list with unknown length and values. I want to swap only when I see 'G' after 'B' one time for each round. for example: I have a list ["B", "G", "G", "B", "G"] I waited ["G", "B", "G", "G", "B"] But the result is => ['G', 'G', 'B', 'G', 'B'] This is a problem on Codeforces site: https://codeforces.com/problemset/problem/266/B If there is something that is not clear, please give me some advice to promote my skills.

I tried:

item1, item2 = item2, item1

It swapped first 3 strings from the last example not what I want 'only two strings' ['G', 'G', 'B'...] but I waited ['G', 'B', 'G'...] Could you understand? This is my code:

# If you find 'G' after 'B' swap them and go through the loop without accessing the last items. 
queue_time = list(map(int, input().split()))
queue = queue_time[0]
time = queue_time[-1]
persons = ["B", "G", "G"]

while time > 0:
  for i in range(len(persons)-1):
    if persons[i] == "B" and persons[i + 1] == "G":
      persons[i], persons[i +1] = persons[i +1], persons[i]
    if persons[i + 1]:
      continue
  time -= 1
print(persons)
2

There are 2 best solutions below

3
Mad Physicist On

You want to mark swapped elements once you've swapped them, so as not to process them again. You don't need a separate sequence for that, since you can just step forward by an extra step after you swap:

ppl = list('BGGBG')
just_swapped = False
for i in range(len(ppl) - 1):
    if just_swapped:
        just_swapped = False
        continue
    if ppl[i : i + 2] == ['B', 'G']:
        ppl[i : i+2] = ppl[i+1 : i-1 if i else None : -1]
        just_swapped = True

If you had a while loop instead of a for loop, you could remove just_swapped and simply increment the index one extra time.

In either case, the result is

>>> ppl
['G', 'B', 'G', 'G', 'B']
0
Kelly Bundy On

You could remember in a variable whether you swapped the previous pair and check that among your checks. Or you could loop with while i < n - 1: (instead of the for loop) and increase i by 1 or 2 as needed. But it's much simpler to keep the input a string instead of a list, and to use its replace method.

n, t = map(int, input().split())
S = input()
for _ in range(t):
    S = S.replace('BG', 'GB')
print(S)