Wednesday, July 3, 2024
HomeLanguagesPythonPython List Comprehension | Segregate 0’s and 1’s in an array list

Python List Comprehension | Segregate 0’s and 1’s in an array list

You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. 

Examples:

Input  :  arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] 
Output :  [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] 

We have existing solution for this problem please refer Segregate 0s and 1s in an array link. We can solve this problem quickly in Python using List Comprehension. Traverse given list and separate out two different lists, one contains all 0’s and another one contains all 1’s. Now concatenate both lists together. 

Python3




# Function to Segregate 0's and 1's in an array list
 
 
def segregate(arr):
    res = ([x for x in arr if x == 0] + [x for x in arr if x == 1])
    print(res)
 
 
# Driver program
if __name__ == "__main__":
    arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0]
    segregate(arr)


Output

[0, 0, 0, 0, 0, 1, 1, 1, 1, 1]

Time complexity: O(n), where n is the length of the input array, as the code needs to traverse the entire input array to segregate 0’s and 1’s.
Auxiliary space: O(n), as the code creates a new result array of the same length as the input array.

Method : Using count() method

Python3




# Function to Segregate 0's and 1's in an array list
 
def segregate(arr):
    res = ([0]*arr.count(0) + [1]*arr.count(1))
    print(res)
 
# Driver program
if __name__ == "__main__":
    arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0]
    segregate(arr)


Output

[0, 0, 0, 0, 0, 1, 1, 1, 1, 1]

Time complexity: O(n), where n is the length of the input array.
Auxiliary space: O(n), as we are creating a new list with the segregated elements.

Shaida Kate Naidoo
am passionate about learning the latest technologies available to developers in either a Front End or Back End capacity. I enjoy creating applications that are well designed and responsive, in addition to being user friendly. I thrive in fast paced environments. With a diverse educational and work experience background, I excel at collaborating with teams both local and international. A versatile developer with interests in Software Development and Software Engineering. I consider myself to be adaptable and a self motivated learner. I am interested in new programming technologies, and continuous self improvement.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments