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)
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:
If you had a
whileloop instead of aforloop, you could removejust_swappedand simply increment the index one extra time.In either case, the result is