Created
July 21, 2018 20:37
-
-
Save frydaykg/fe14cfd4d52946d9fbd7dbcce4d7953f to your computer and use it in GitHub Desktop.
PlusMinus
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Echo client program | |
| import socket | |
| import math | |
| import numexpr | |
| x = ['+','-','/', '*'] | |
| e = 0.00001 | |
| def evaluate(stringexpr, listexpr=0, n=0, f_operation='+'): | |
| if stringexpr: | |
| listexpr = ([c for c in stringexpr+')' ]) | |
| listexpr.reverse() | |
| while f_operation != ')': | |
| m_next = listexpr.pop() | |
| if m_next == '(': | |
| m_next = evaluate(None, listexpr) | |
| else: | |
| while listexpr[-1] not in '+-*/)': | |
| m_next += listexpr.pop() | |
| m = float(m_next) | |
| if f_operation == '+': | |
| n = n+m | |
| elif f_operation == '-': | |
| n = n-m | |
| elif f_operation == '*': | |
| n = n*m | |
| else: | |
| n= n/(m or 1) | |
| f_operation = listexpr.pop() | |
| return n | |
| def f(q, a, p, n, openb, b): | |
| if p == n: | |
| qq = q + openb * ')' | |
| ans = evaluate(qq) | |
| if math.fabs(ans - b) < e: | |
| return qq | |
| qq = '-' + qq | |
| ans = evaluate(qq) | |
| if math.fabs(ans - b) < e: | |
| return qq | |
| return None | |
| if p == 0: | |
| for k in range(n-p): | |
| qq = '(' * k + a[p] | |
| ans = f(q + qq, a, p+1, n, openb + k, b) | |
| if ans is not None: | |
| return ans | |
| elif p == n - 1: | |
| for i in range(openb+1): | |
| for j in x: | |
| qq = ')' * i + j + a[p] | |
| ans = f(q + qq, a, p+1, n, openb - i, b) | |
| if ans is not None: | |
| return ans | |
| else: | |
| for i in range(openb+1): | |
| for j in x: | |
| for k in range(n-p): | |
| qq = ')' * i + j + '(' * k + a[p] | |
| ans = f(q + qq, a, p+1, n, openb - i + k, b) | |
| if ans is not None: | |
| return ans | |
| def solve(s): | |
| print(s) | |
| a = s.split() | |
| b = float(a[-1]) | |
| a = a[:-1] | |
| ans = f('', a,0, len(a), 0, b) | |
| print(ans) | |
| return ans + '\n' | |
| HOST = 'ppc-01.v7frkwrfyhsjtbpfcppnu.ctfz.one' # The remote host | |
| PORT = 2445 # The same port as used by the server | |
| with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | |
| s.connect((HOST, PORT)) | |
| while True: | |
| data = s.recv(1024).decode('utf8') | |
| data = data.split('\n') | |
| print('Data: ', data) | |
| if data[-2] == 'Success': | |
| continue | |
| answer = solve(data[-2]) | |
| s.sendall(answer.encode()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment