Advertisement
BanyRule

Ege16

Jan 26th, 2016
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. # http://pythontutor.ru/visualizer/
  2. OPERATORS = {'+': (1, lambda x, y: x + y), '-': (1, lambda x, y: x - y),
  3.              '*': (2, lambda x, y: x * y), '/': (2, lambda x, y: x / y)}
  4.  
  5.  
  6. def eval_(formula):
  7.     def parse(formula_string):
  8.         number = ''
  9.         for s in formula_string:
  10.             if s in '1234567890.':
  11.                 number += s
  12.             elif number:
  13.                 yield float(number)
  14.                 number = ''
  15.             if s in OPERATORS or s in "()":
  16.                 yield s
  17.         if number:
  18.             yield float(number)
  19.  
  20.     def shunting_yard(parsed_formula):
  21.         stack = []
  22.         for token in parsed_formula:
  23.             if token in OPERATORS:
  24.                 while stack and stack[-1] != "(" and OPERATORS[token][0] <= OPERATORS[stack[-1]][0]:
  25.                     yield stack.pop()
  26.                 stack.append(token)
  27.             elif token == ")":
  28.                 while stack:
  29.                     x = stack.pop()
  30.                     if x == "(":
  31.                         break
  32.                     yield x
  33.             elif token == "(":
  34.                 stack.append(token)
  35.             else:
  36.                 yield token
  37.         while stack:
  38.             yield stack.pop()
  39.  
  40.     def calc(polish):
  41.         stack = []
  42.         for token in polish:
  43.             if token in OPERATORS:
  44.                 y, x = stack.pop(), stack.pop()
  45.                 stack.append(OPERATORS[token][1](x, y))
  46.             else:
  47.                 stack.append(token)
  48.         return stack[0]
  49.  
  50.     return calc(shunting_yard(parse(formula)))
  51.  
  52.  
  53. def splitting( s ):
  54.     string_out = ''
  55.     bof_char = s[0]
  56.     count = 1
  57.     for i in s[1:]:
  58.         if i == bof_char:
  59.             count += 1
  60.         else:
  61.             if count == 1:
  62.                 string_out += str(bof_char)
  63.             else:
  64.                 string_out += ( '[' + str(bof_char) + ':' +str(count) + ']')
  65.             count = 1
  66.         bof_char = i
  67.     string_out += ( '[' + str(bof_char) + ':' +str(count) + ']')
  68.     return string_out
  69.  
  70.  
  71. x = bin(eval(input()))
  72.  
  73. print( splitting(x[2:]) )
  74. print('0 => ' + str(x.count('0')-1))
  75. print('1 => ' + str(x.count('1')))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement