DeaD_EyE

check-if-a-given-string-is-binary-string-or-not

Dec 3rd, 2018
283
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. '''
  2. https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/
  3.  
  4. Every time I see the handling of sets, I realize that much of set theory is not applied.
  5. The given example is used to check if a string consists only of 1 or 0. Very easy.
  6. To give an easy answer: {'0', '1'} is a superset of a binary_string.
  7.  
  8.  
  9. # Python program to check
  10. # if a string is binary or not
  11.  
  12. # function for checking the
  13. # string is accepted or not
  14. '''
  15.  
  16.  
  17. def check(string):
  18.     '''
  19.    This function returns True if the string is binary.
  20.    Otherwise False is returned
  21.    * white space is not allowed
  22.    '''
  23.     if not string:
  24.         return False
  25.     alphabet = {'0', '1'}
  26.     # alternative
  27.     # alphabet = set('01')
  28.     return alphabet.issuperset(string)
  29.  
  30.  
  31. # def check_general(iterable, alphabet):
  32. #     '''
  33. #     This function returns True if the alphabet is a superset of an iterable.
  34. #     alphabet can be any iterable
  35. #     '''
  36. #     return set(alphabet).issuperset(iterable)
  37.  
  38.  
  39. # alternative check
  40. # def check_try(string):
  41. #     '''
  42. #     don't ask for permission, ask for forgiveness
  43. #     '''
  44. #     try:
  45. #         int(string, 2)
  46. #     except ValueError:
  47. #         return False
  48. #     else:
  49. #         return True
  50.  
  51.  
  52. if __name__ == '__main__' :
  53.     strings = [
  54.         '101010000111',
  55.         'iii010000111',
  56.         '000000000000',
  57.         '111111111111',
  58.         '',
  59.         ]
  60.     for string in strings:
  61.         result = check(string)
  62.         if result:
  63.             fill_text = 'is'
  64.         else:
  65.             fill_text = 'is not'
  66.         print(f'{string:>20} {fill_text} a binary string')
RAW Paste Data