Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/
- Every time I see the handling of sets, I realize that much of set theory is not applied.
- The given example is used to check if a string consists only of 1 or 0. Very easy.
- To give an easy answer: {'0', '1'} is a superset of a binary_string.
- # Python program to check
- # if a string is binary or not
- # function for checking the
- # string is accepted or not
- '''
- def check(string):
- '''
- This function returns True if the string is binary.
- Otherwise False is returned
- * white space is not allowed
- '''
- if not string:
- return False
- alphabet = {'0', '1'}
- # alternative
- # alphabet = set('01')
- return alphabet.issuperset(string)
- # def check_general(iterable, alphabet):
- # '''
- # This function returns True if the alphabet is a superset of an iterable.
- # alphabet can be any iterable
- # '''
- # return set(alphabet).issuperset(iterable)
- # alternative check
- # def check_try(string):
- # '''
- # don't ask for permission, ask for forgiveness
- # '''
- # try:
- # int(string, 2)
- # except ValueError:
- # return False
- # else:
- # return True
- if __name__ == '__main__' :
- strings = [
- '101010000111',
- 'iii010000111',
- '000000000000',
- '111111111111',
- '',
- ]
- for string in strings:
- result = check(string)
- if result:
- fill_text = 'is'
- else:
- fill_text = 'is not'
- print(f'{string:>20} {fill_text} a binary string')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement