![]() |
We are given a binary string and we have to check whether it is possible to rearrange the string with alternate 0s and 1s. Below are a few examples to understand the problem statement clearly. Examples:Input: "1011" Possibility to Rearrange a Binary String with Alternate 0s and 1sNow let us see different approaches to check if it is possible to rearrange a binary string with alternate 0s and 1s in Python. Using Count FunctionPython string count() function is used to count the occurrence of a character in a string. It take one argument and returns an integer value. Using the count() function to count the number of s and 1s, compute the absolute difference between them. If the absolute difference is less than or equal to 1, that means the 0s and 1s can be rearranged alternatively. Example: In this example, we first count number of 0s and 1s and then find the absolute difference using the abs() function.
Output: True Using collection.CounterIn this method, the Python collection module‘s Counter class is used to count the number of characters in the string. The get() function is then used to count the occurrence of the character that is passed to it as an argument in the string. Lastly the absolute difference. using abs() function, between the 0s and 1s determines if the binary string can be rearranged with alternative 0s and 1s or not. Example: In this example, we first import the Counter class from collections module. Then use counter class’s get() function to calculate the number of 0s and 1s and then find the absolute difference using the abs() function.
Output: False |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |