
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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']