In this problem a string is given, our task is to check the string contains even number of 1’s and odd number 0’s or not.
Examples:
Input : "101010100" Output : Accept Input : "111001010101" Output : Not Accept
Approach used in function: we firstly declare set s which contain ‘0’ and ‘1’ and create set of the characters present in the given string using set() function after that we check set p is same as the set s or not if both set are same then we go inside the if block and assign 0 to both one_count and zero_count variables.
Now we have to iterate over all the characters present in the given string and check each character is either equal to ‘1’ or not if it is equal to ‘1’ then incremented the one_count variable by one otherwise incremented zero_count variable by one. After coming out of the for loop we have to check one_count for even and zero_count. For odd together if both conditions are true then string is accepted otherwise not.
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+
Implementation:
# Function for checking if the string is accepted or not
def check(string):
# Declare set of '0' and '1'
s = {'0', '1'}
# Convert string into a set of characters
p = set(string)
# Check if set p is the same as set s
if p == s:
# Initialize the variables one_count and zero_count to 0
one_count = 0
zero_count = 0
# Loop through each character of the string
for char in string:
# Check if the character is '1'
if char == '1':
# Increment one_count by 1
one_count += 1
else:
# Increment zero_count by 1
zero_count += 1
# Check if one_count is even and zero_count is odd
if one_count % 2 == 0 and zero_count % 2 != 0:
# Using f-string
print(f"string : {string} is accepted.")
else:
# Using f-string
print(f"string : {string} is not accepted.")
else:
# If set p is not the same as set s
print(f"string : {string} is not accepted.")
# Driver code
if __name__ == "__main__":
string = "1110001010100"
# Function calling
check(string)
Output:
string : 1110001010100 is accepted.
