Program to partition color list in Python


Suppose we have a a list of color strings, these may contain "red", "green" and "blue", we have to partition the list so that the red come before green, and green come before blue.

So, if the input is like colors = ["blue","green", "blue", "red", "red"], then the output will be ['red', 'red', 'green', 'blue', 'blue']

To solve this, we will follow these steps −

  • green := 0, blue := 0, red := 0

  • for each string in strs, do

    • if string is same as "red", then

      • strs[blue] := "blue"

      • blue := blue + 1

      • strs[green] := "green"

      • green := green + 1

      • strs[red] := "red"

      • red := red + 1

    • otherwise when string is same as "green", then

      • strs[blue] := "blue"

      • blue := blue + 1

      • strs[green] := "green"

      • green := green + 1

    • otherwise when string is same as "blue", then

      • strs[blue] := "blue"

      • blue := blue + 1

  • return strs

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, strs):
      green = 0
      blue = 0
      red = 0
      for string in strs:
         if string == "red":
            strs[blue] = "blue"
            blue += 1
            strs[green] = "green"
            green += 1
            strs[red] = "red"
            red += 1
         elif string == "green":
            strs[blue] = "blue"
            blue += 1
            strs[green] = "green"
            green += 1
         elif string == "blue":
            strs[blue] = "blue"
            blue += 1
      return strs
ob = Solution()
colors = ["blue","green", "blue", "red", "red"]
print(ob.solve(colors))

Input

["blue","green", "blue", "red", "red"]

Output

['red', 'red', 'green', 'blue', 'blue']

Updated on: 10-Oct-2020

492 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements