

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Segregate 0’s and 1’s in an array list using Python?
List Comprehension is a popular technique in Python. Here we use this technique. We create a user input array and array element should be 0’s and 1’s in random order. Then segregate 0’s on left side and 1’s on right side. We traverse the array and separate two different list, one contains 0’s and another contains 1’s, then concatenate two list.
Example
Input:: a=[0,1,1,0,0,1] Output::[0,0,0,1,1,1]
Algorithm
seg0s1s(A) /* A is the user input Array and the element of A should be the combination of 0’s and 1’s */ Step 1: First traverse the array. Step 2: Then check every element of the Array. If the element is 0, then its position is left side and if 1 then it is on the right side of the array. Step 3: Then concatenate two list.
Example Code
# Segregate 0's and 1's in an array list def seg0s1s(A): n = ([i for i in A if i==0] + [i for i in A if i==1]) print(n) # Driver program if __name__ == "__main__": A=list() n=int(input("Enter the size of the array ::")) print("Enter the number ::") for i in range(int(n)): k=int(input("")) A.append(int(k)) print("The New ArrayList ::") seg0s1s(A)
Output
Enter the size of the array ::6 Enter the number :: 1 0 0 1 1 0 The New ArrayList :: [0, 0, 0, 1, 1, 1]
- Related Questions & Answers
- Sort an arrays of 0’s, 1’s and 2’s using C++
- Sort an arrays of 0’s, 1’s and 2’s using Java
- Construct DFA of alternate 0’s and 1’s
- Count the number of 1’s and 0’s in a binary array using STL in C++
- Find the Pattern of 1’s inside 0’s using C++
- Find the index of first 1 in a sorted array of 0's and 1's in C++
- Maximum length of segments of 0’s and 1’s in C++
- C++ Largest Subtree having Equal No of 1's and 0's
- Largest number with binary representation is m 1’s and m-1 0’s in C++
- Count subarrays with equal number of 1’s and 0’s in C++
- Count subarrays consisting of only 0’s and only 1’s in a binary array in C++
- Given a sorted array of 0’s and 1’s, find the transition point of the array in C++
- Maximum 0’s between two immediate 1’s in binary representation in C++
- Find the number of integers from 1 to n which contains digits 0’s and 1’s only in C++
- Count number of binary strings of length N having only 0’s and 1’s in C++
Advertisements