In this problem a string is given, our task is to check the string is binary string or not.
Examples:
Input : '01010101010' Output : Accepted Input : 'w3colleges101' Output : Not Accepted
# 1st method :
This approach used in function: we firstly create set of the characters present in the given string using set() function and declare set s which contain ‘0’ and ‘1’.
that we check for following conditions:
1) set p is same as set s or 2) set p conatins only '0' or 3) set p conatins only '1'.
Because we are using or short cicrcuit operator so if any one condition is true from these 3 conditions then result is true otherwise not . if result is true then string is accepted otherwise string is not accepted. In this problem we are using concept of f-strings also, for understanding the f-strings you can go through f-strings.
Note –
f-strings is applicable only for python 3.6 and python 3.6+
# function for checking the
# string is accepted or not
def check(string) :
# set function convert string
# into set of characters .
p = set(string)
# declare set of '0','1' .
s = {'0','1'}
# check set p is same as set s
# or set p contains only '0'
# or set p contains only '1'
# or not , if any one conditon
# is true then string is accepted
# otherwise not .
if s == p or p == {'0'} or p == {'1'}:
print( f"String : {string} is Accepted" )
else :
print( f"String : {string} is not Accepted" )
# driver code
if __name__ == "__main__" :
string = "101010000111"
# function calling
check(string)
Output :
String : 101010000111 is Accepted
# 2nd method :
This approach used in function: we firstly assign string ’01’ to the variable t and assign 0 to the count variable after that we have to iterate over each charcater of the given string and check for each character. It is present in string t i.e., ’01’ or not if not present then we set 1 to the count varibale and break out of the for loop otherwise iterate. After coming out of the for loop we check the value of count variable, if value of count is 1 then string is not accepted otherwise string is accepted.
# function for checking the
# string is accepted or not
def check2(string) :
# initialize the variable t
# with '01' string
t = '01'
# initialize the variable count
# with 0 value
count = 0
# looping through each character
# of the string .
for char in string :
# check the character is present in
# string t or not .
# if this condition is true
# assign 1 to the count variable
# and break out of the for loop
# otherwise pass .
if char not in t :
count = 1
break
else :
pass
# after coming out of the loop
# check value of count is non-zero or not
# if value is non-zero then condition is true
# and string is not accepted
# otherwise string is accepted
if count :
print( f"String : {string} is not Accepted" )
else :
print( f"String : {string} is Accepted" )
# driver code
if __name__ == "__main__" :
string = "00101010001010"
# function calling
check2(string)
Output :
String : 00101010001010 is Accepted
