# Python program to sort a sequence containing only 0, 1 and 2 in a single pass.
red = 0 # The first color of the flag.
white = 1 # The second color of the flag.
blue = 2 # The third color of the flag.
colors = (red, white, blue)
def dutch_national_flag_sort(sequence: list) -> list:
if not sequence:
return []
if len(sequence) == 1:
return list(sequence)
low = 0
high = len(sequence) - 1
mid = 0
while mid <= high:
if sequence[mid] == colors[0]:
sequence[low], sequence[mid] = sequence[mid], sequence[low]
low += 1
mid += 1
elif sequence[mid] == colors[1]:
mid += 1
elif sequence[mid] == colors[2]:
sequence[mid], sequence[high] = sequence[high], sequence[mid]
high -= 1
else:
raise ValueError(
f"The elements inside the sequence must contains only {
colors} values"
)
return sequence
if __name__ == "__main__":
import doctest
doctest.testmod()
user_input = input("Enter numbers separated by commas:\n").strip()
unsorted = [int(item.strip()) for item in user_input.split(",")]
print(f"{
dutch_national_flag_sort(unsorted)}")