
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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']
- Related Articles
- Program to partition two strings such that each partition forms anagram in Python
- Partition List in C++
- Program to find number of sublists we can partition so given list is sorted finally in python
- Program to find partition array into disjoint intervals in Python
- Program to find size of each partition of a list where each letter appears at most one piece in Python
- Array Partition I in Python
- Program to check whether we can partition a list with k-partitions of equal sum in C++
- Program to fill with color using floodfill operation in Python
- Partition Array for Maximum Sum in Python
- Program to count number of walls required to partition top-left and bottom-right cells in Python
- Program to reverse a list by list slicing in Python
- Python program to Flatten Nested List to Tuple List
- Program to find largest color value in a directed graph in Python
- Python program to create 3D list.
- Program to reverse a linked list in Python
