From 60fc0e1b918066cee2a482dd3ff2524730403107 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 12 Apr 2019 06:32:05 -0400 Subject: [PATCH 001/159] first commit --- pycalc.py | 292 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 292 insertions(+) create mode 100644 pycalc.py diff --git a/pycalc.py b/pycalc.py new file mode 100644 index 00000000..1521a01a --- /dev/null +++ b/pycalc.py @@ -0,0 +1,292 @@ +import argparse +from math import pi,e,cos,sin,acos,asin,tan,atan,log,log10,sqrt,exp,factorial + +ap = argparse.ArgumentParser(description = 'Pure-python command-line calculator.') +ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') +ap.add_argument('-p', '--PRINT', default='n', choices=['y', 'n'], type = str, help = 'print evaluation process') +ap.add_argument('-m', '--MODULE', type = str, help = 'use modules MODULE [MODULE...] additional modules to use') +args = ap.parse_args() +##print(args.EXPRESSION) +##print(args.PRINT) +##print(args.MODULE) +xpr = args.EXPRESSION +show = args.PRINT + +##modstr=args.MODULE +## +##mod = __import__(modstr) +##print (modstr,'=',mod.myfunc(3)) + + +#xpr = 'sin(-cos(-sin(3.0)-cos(-sin(-3.0*5.0)-sin(cos(log10(43.0))))+cos(sin(sin(34.0-2.0^2.0))))--cos(1.0)--cos(0.0)^3.0)' +#xpr='++++6' +#xpr='abs(-(6^2)//(-sin(-4-4)))' + +#print(xpr) + +oper = ('!','^','//','/','*','%','-','+','(',')','==','<=','>=','<','>','!=','=') +digit = ('1','2','3','4','5','6','7','8','9','0','.') +func = ('sin','cos','tan','log10','log','exp','abs','round','sqrt') +stroka = '' +slovo = '' +operator = '' +spisok = [] +a = 0. +b = 0. +result = 0. + + +#разбор строки на элементы списка +def parse(stroka): + slovo='' + #исправление неверно введенных знаков + stroka = stroka.replace(' ','') + stroka = stroka.replace(',','.') + stroka = stroka.replace('--','+') + stroka = stroka.replace('++','+') + stroka = stroka.replace('+-','-') + stroka = stroka.replace('-+','-') + stroka = stroka.replace('<+','<') + stroka = stroka.replace('>+','>') + stroka = stroka.replace('=<','<=') + stroka = stroka.replace('=>','>=') + stroka = stroka.replace('==+','+') + if stroka[0] == '+': stroka=stroka[1:] + #print('parse:',stroka) + + #разбор строки + for i,sym in enumerate(stroka + ' '): #добавлен дополнительный пробел + if sym in oper or i == len(stroka): + #print(i,slovo,sym) + if slovo == 'pi': + spisok.append(pi) + elif slovo == 'e': + spisok.append(e) + elif slovo in func: + spisok.append(slovo) + elif slovo.replace('.','').isdigit() and slovo.count('.')<2: + spisok.append(float(slovo)) + elif slovo != '': + print('ERROR: wrong symbol "',slovo,sym,'"') + exit(0) + spisok.append(sym) + slovo = '' + #print(sym) + + else: + slovo = slovo + sym + #print(i,sym,spisok) + spisok.pop() #удаляется добавленный пробел + + for i,data in enumerate(spisok): + if spisok[i] == '/' and spisok[i + 1] == '/': + spisok[i] = '//' + spisok.pop(i + 1) + if spisok[i] == '>' and spisok[i + 1] == '=': + spisok[i] = '>=' + spisok.pop(i + 1) + if spisok[i] == '<' and spisok[i + 1] == '=': + spisok[i] = '<=' + spisok.pop(i + 1) + if spisok[i] == '=' and spisok[i + 1] == '=' or spisok[i] =='=': + spisok[i] = '==' + spisok.pop(i + 1) + if spisok[i] == '!' and spisok[i + 1] == '=': + spisok[i] = '!=' + spisok.pop(i + 1) + if spisok[i] == '-' and spisok[i - 1] in oper and type(spisok[i + 1]) == float: + spisok[i + 1] = spisok[i + 1]* - 1 + spisok.pop(i) + if (spisok[i] == '-' and i == 0) or(spisok[i] == '-' and spisok[i - 1] in('*','^','+','-','(','<','>','=') ): + spisok[i] = -1 + spisok.insert(i + 1,'*') + if spisok[i] == '-' and spisok[i - 1] == '/': + spisok[i - 1] = '*' + spisok[i] = -1 + spisok.insert(i + 1,'/') + #print(spisok) + return(spisok) + + +def operate(operator,a,b): + if operator == "+": + result = a + b + elif operator == "-": + result = a - b + elif operator == "*": + result = a * b + + elif operator == "//": + if b != 0: + result = a // b + else: + print('ERROR: division by zero') + exit(0) + elif operator == "/": + if b != 0: + result = a / b + else: + print('ERROR: division by zero') + exit(0) + elif operator == "%": + result = a % b + elif operator == "^": + result = a**b + elif operator == "<=": + result = a <= b + elif operator == ">=": + result = a >= b + elif operator == "<": + result = a < b + elif operator == ">": + result = a > b + elif operator == "==": + result = a == b + elif operator == "!=": + result = a != b + elif operator == "abs": + result = abs(a) + elif operator == "round": + result = round(a) + elif operator == "cos": + result = cos(a) + elif operator == "sin": + result = sin(a) + elif operator == "tan": + result = tan(a) + elif operator == "log": + result = log(a) + elif operator == "log10": + result = log10(a) + elif operator == "sqrt": + result = sqrt(a) + elif operator == "cos": + result = cos(a) + elif operator == "exp": + result = exp(a) + elif operator == "!": + result = factorial(a) + else: + print('ERROR: unknown math operator',operator) + result = 0 + if show == 'y': + if operator in oper: + print('Operate:',a,operator,b,'=',result) + elif operator in func: + print('Operate:',operator,a,'=',result) + return result + +#вычисление выражения без скобок +def calculate(spisok): + if show == 'y': print('Calculate:',spisok) + # перебор списка функций + for f in func: + for i in range(spisok.count(f)): + #print(f,spisok.count(f)) + s = spisok.index(f) + spisok[s] = (operate(f,spisok[s + 1],0)) + spisok[s + 1] = '' + wipe(spisok) + #print(*spisok,sep='') + + #вычисление возведение в степень с реверсом списка + #print('^ count:',spisok.count('^')) + if '^' in spisok: + spisok.reverse() + #print('reverse: ',spisok) + while '^' in spisok: + i = spisok.index('^') + #print('i = ',i) + spisok[i] = spisok[i + 1]**spisok[i - 1] + #print(spisok[i + 1],'^',spisok[i - 1],'=',spisok[i]) + spisok[i - 1] = '' + spisok[i + 1] = '' + #print(spisok) + wipe(spisok) + #print(spisok) + spisok.reverse() + + #перебор списка математических операций + for j in oper: + #print('operation = ',j) + #print(spisok) + i = 1 + while i < len(spisok): + if spisok[i] == j: + #print('calculate: ',*spisok,sep='') + spisok[i] = operate(spisok[i],spisok[i - 1],spisok[i + 1]) + spisok[i - 1] = '' + spisok[i + 1] = '' + #print(spisok) + wipe(spisok) + i = i - 1 + i = i + 1 + #print('Stop calculate:',float(spisok[0])) + wipe(spisok) + #print(spisok) + result = spisok[0] + if len(spisok) > 1: + print('ERROR: missed operator') + exit(0) + return(result) + +#очистка списка от пустых значений '' +def wipe(spisok): + #print('WIPE:\n',spisok) + while '' in spisok: + i = spisok.index('') + spisok.pop(i) + #print('WIPED:\n',spisok) + return(spisok) + +#поиск начала и конца выражения в скобках() +def brktindx(spisok): + bl = spisok.index('(') + br = spisok.index(')') + s = spisok[bl + 1:br] + #print('BL BR ',bl + 1,' ',br,' ',*s,sep='') + while '(' in s: + if s.count('(') == s.count(')'): + bl = spisok.index('(',bl + 1) + br = spisok.index(')',bl + 1) + s = spisok[bl + 1:br] + #print('BL BR ',bl + 1,' ',br,' ', *s,sep='') + else: + br = spisok.index(')',br + 1) + s = spisok[bl:br + 1] + return(bl + 1,br) + + +#начало основной программы + +#проверка скобок в строке +if xpr.count('(') != xpr.count(')'): + print('ERROR: brackets are not balanced') + exit(0) + +#разбор строики в список +spisok = parse(xpr) +#print(*spisok,sep=',') + + + + + +#поиск скобок и вычисление в скобках +while '(' in spisok: + a,b = brktindx(spisok) + #print('in brackets: ',*spisok[a:b],sep='') + spisok[a - 1] = calculate(spisok[a:b]) + while a < b + 1: + spisok[a] = '' + a = a + 1 + wipe(spisok) + #print(*spisok,sep='') + +#вычисление без скобок +result = calculate(spisok) +print(result) + + + + From 15c800087931d2009b0326ce99ee7cc7eff0ee1b Mon Sep 17 00:00:00 2001 From: novash-k <49132079+novash-k@users.noreply.github.com> Date: Fri, 12 Apr 2019 15:55:19 +0300 Subject: [PATCH 002/159] Add files via upload --- pycalc.py | 651 ++++++++++++++++++++++++++++++------------------------ 1 file changed, 359 insertions(+), 292 deletions(-) diff --git a/pycalc.py b/pycalc.py index 1521a01a..72143a38 100644 --- a/pycalc.py +++ b/pycalc.py @@ -1,292 +1,359 @@ -import argparse -from math import pi,e,cos,sin,acos,asin,tan,atan,log,log10,sqrt,exp,factorial - -ap = argparse.ArgumentParser(description = 'Pure-python command-line calculator.') -ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') -ap.add_argument('-p', '--PRINT', default='n', choices=['y', 'n'], type = str, help = 'print evaluation process') -ap.add_argument('-m', '--MODULE', type = str, help = 'use modules MODULE [MODULE...] additional modules to use') -args = ap.parse_args() -##print(args.EXPRESSION) -##print(args.PRINT) -##print(args.MODULE) -xpr = args.EXPRESSION -show = args.PRINT - -##modstr=args.MODULE -## -##mod = __import__(modstr) -##print (modstr,'=',mod.myfunc(3)) - - -#xpr = 'sin(-cos(-sin(3.0)-cos(-sin(-3.0*5.0)-sin(cos(log10(43.0))))+cos(sin(sin(34.0-2.0^2.0))))--cos(1.0)--cos(0.0)^3.0)' -#xpr='++++6' -#xpr='abs(-(6^2)//(-sin(-4-4)))' - -#print(xpr) - -oper = ('!','^','//','/','*','%','-','+','(',')','==','<=','>=','<','>','!=','=') -digit = ('1','2','3','4','5','6','7','8','9','0','.') -func = ('sin','cos','tan','log10','log','exp','abs','round','sqrt') -stroka = '' -slovo = '' -operator = '' -spisok = [] -a = 0. -b = 0. -result = 0. - - -#разбор строки на элементы списка -def parse(stroka): - slovo='' - #исправление неверно введенных знаков - stroka = stroka.replace(' ','') - stroka = stroka.replace(',','.') - stroka = stroka.replace('--','+') - stroka = stroka.replace('++','+') - stroka = stroka.replace('+-','-') - stroka = stroka.replace('-+','-') - stroka = stroka.replace('<+','<') - stroka = stroka.replace('>+','>') - stroka = stroka.replace('=<','<=') - stroka = stroka.replace('=>','>=') - stroka = stroka.replace('==+','+') - if stroka[0] == '+': stroka=stroka[1:] - #print('parse:',stroka) - - #разбор строки - for i,sym in enumerate(stroka + ' '): #добавлен дополнительный пробел - if sym in oper or i == len(stroka): - #print(i,slovo,sym) - if slovo == 'pi': - spisok.append(pi) - elif slovo == 'e': - spisok.append(e) - elif slovo in func: - spisok.append(slovo) - elif slovo.replace('.','').isdigit() and slovo.count('.')<2: - spisok.append(float(slovo)) - elif slovo != '': - print('ERROR: wrong symbol "',slovo,sym,'"') - exit(0) - spisok.append(sym) - slovo = '' - #print(sym) - - else: - slovo = slovo + sym - #print(i,sym,spisok) - spisok.pop() #удаляется добавленный пробел - - for i,data in enumerate(spisok): - if spisok[i] == '/' and spisok[i + 1] == '/': - spisok[i] = '//' - spisok.pop(i + 1) - if spisok[i] == '>' and spisok[i + 1] == '=': - spisok[i] = '>=' - spisok.pop(i + 1) - if spisok[i] == '<' and spisok[i + 1] == '=': - spisok[i] = '<=' - spisok.pop(i + 1) - if spisok[i] == '=' and spisok[i + 1] == '=' or spisok[i] =='=': - spisok[i] = '==' - spisok.pop(i + 1) - if spisok[i] == '!' and spisok[i + 1] == '=': - spisok[i] = '!=' - spisok.pop(i + 1) - if spisok[i] == '-' and spisok[i - 1] in oper and type(spisok[i + 1]) == float: - spisok[i + 1] = spisok[i + 1]* - 1 - spisok.pop(i) - if (spisok[i] == '-' and i == 0) or(spisok[i] == '-' and spisok[i - 1] in('*','^','+','-','(','<','>','=') ): - spisok[i] = -1 - spisok.insert(i + 1,'*') - if spisok[i] == '-' and spisok[i - 1] == '/': - spisok[i - 1] = '*' - spisok[i] = -1 - spisok.insert(i + 1,'/') - #print(spisok) - return(spisok) - - -def operate(operator,a,b): - if operator == "+": - result = a + b - elif operator == "-": - result = a - b - elif operator == "*": - result = a * b - - elif operator == "//": - if b != 0: - result = a // b - else: - print('ERROR: division by zero') - exit(0) - elif operator == "/": - if b != 0: - result = a / b - else: - print('ERROR: division by zero') - exit(0) - elif operator == "%": - result = a % b - elif operator == "^": - result = a**b - elif operator == "<=": - result = a <= b - elif operator == ">=": - result = a >= b - elif operator == "<": - result = a < b - elif operator == ">": - result = a > b - elif operator == "==": - result = a == b - elif operator == "!=": - result = a != b - elif operator == "abs": - result = abs(a) - elif operator == "round": - result = round(a) - elif operator == "cos": - result = cos(a) - elif operator == "sin": - result = sin(a) - elif operator == "tan": - result = tan(a) - elif operator == "log": - result = log(a) - elif operator == "log10": - result = log10(a) - elif operator == "sqrt": - result = sqrt(a) - elif operator == "cos": - result = cos(a) - elif operator == "exp": - result = exp(a) - elif operator == "!": - result = factorial(a) - else: - print('ERROR: unknown math operator',operator) - result = 0 - if show == 'y': - if operator in oper: - print('Operate:',a,operator,b,'=',result) - elif operator in func: - print('Operate:',operator,a,'=',result) - return result - -#вычисление выражения без скобок -def calculate(spisok): - if show == 'y': print('Calculate:',spisok) - # перебор списка функций - for f in func: - for i in range(spisok.count(f)): - #print(f,spisok.count(f)) - s = spisok.index(f) - spisok[s] = (operate(f,spisok[s + 1],0)) - spisok[s + 1] = '' - wipe(spisok) - #print(*spisok,sep='') - - #вычисление возведение в степень с реверсом списка - #print('^ count:',spisok.count('^')) - if '^' in spisok: - spisok.reverse() - #print('reverse: ',spisok) - while '^' in spisok: - i = spisok.index('^') - #print('i = ',i) - spisok[i] = spisok[i + 1]**spisok[i - 1] - #print(spisok[i + 1],'^',spisok[i - 1],'=',spisok[i]) - spisok[i - 1] = '' - spisok[i + 1] = '' - #print(spisok) - wipe(spisok) - #print(spisok) - spisok.reverse() - - #перебор списка математических операций - for j in oper: - #print('operation = ',j) - #print(spisok) - i = 1 - while i < len(spisok): - if spisok[i] == j: - #print('calculate: ',*spisok,sep='') - spisok[i] = operate(spisok[i],spisok[i - 1],spisok[i + 1]) - spisok[i - 1] = '' - spisok[i + 1] = '' - #print(spisok) - wipe(spisok) - i = i - 1 - i = i + 1 - #print('Stop calculate:',float(spisok[0])) - wipe(spisok) - #print(spisok) - result = spisok[0] - if len(spisok) > 1: - print('ERROR: missed operator') - exit(0) - return(result) - -#очистка списка от пустых значений '' -def wipe(spisok): - #print('WIPE:\n',spisok) - while '' in spisok: - i = spisok.index('') - spisok.pop(i) - #print('WIPED:\n',spisok) - return(spisok) - -#поиск начала и конца выражения в скобках() -def brktindx(spisok): - bl = spisok.index('(') - br = spisok.index(')') - s = spisok[bl + 1:br] - #print('BL BR ',bl + 1,' ',br,' ',*s,sep='') - while '(' in s: - if s.count('(') == s.count(')'): - bl = spisok.index('(',bl + 1) - br = spisok.index(')',bl + 1) - s = spisok[bl + 1:br] - #print('BL BR ',bl + 1,' ',br,' ', *s,sep='') - else: - br = spisok.index(')',br + 1) - s = spisok[bl:br + 1] - return(bl + 1,br) - - -#начало основной программы - -#проверка скобок в строке -if xpr.count('(') != xpr.count(')'): - print('ERROR: brackets are not balanced') - exit(0) - -#разбор строики в список -spisok = parse(xpr) -#print(*spisok,sep=',') - - - - - -#поиск скобок и вычисление в скобках -while '(' in spisok: - a,b = brktindx(spisok) - #print('in brackets: ',*spisok[a:b],sep='') - spisok[a - 1] = calculate(spisok[a:b]) - while a < b + 1: - spisok[a] = '' - a = a + 1 - wipe(spisok) - #print(*spisok,sep='') - -#вычисление без скобок -result = calculate(spisok) -print(result) - - - - +import argparse +from math import pi,e,cos,sin,acos,asin,tan,atan,log,log10,sqrt,exp,factorial + +ap = argparse.ArgumentParser(description = 'Pure-python command-line calculator.') +ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') +ap.add_argument('-p', '--PRINT', default='n', choices=['y', 'n'], type = str, help = 'print evaluation process') +ap.add_argument('-m', '--MODULE', type = str, help = 'use modules MODULE [MODULE...] additional modules to use') +args = ap.parse_args() +##print(args.EXPRESSION) +##print(args.PRINT) +##print(args.MODULE) +xpr = args.EXPRESSION +show = args.PRINT +#show = 'y' + +##xpr = modstr=args.MODULE +##xpr = +##xpr = mod = __import__(modstr) +##xpr = print (modstr,'=',mod.myfunc(3)) + + +## Unary operators +##xpr = "-13" +##xpr = "6-(-13)" +##xpr = "1---1" +##xpr = "-+---+-1" +## Operation priority +##xpr = "1+2*2" +##xpr = "1+(2+3*2)*3" +##xpr = "10*(2+1)" +##xpr = "10^(2+1)" +##xpr = "100/3^2" +##xpr = "100/3%2^2" +## Functions and constants +##xpr = "pi+e" +##xpr = "log(e)" +##xpr = "sin(pi/2)" +##xpr = "log10(100)" +##xpr = "sin(pi/2)*111*6" +##xpr = "2*sin(pi/2)" +##xpr = "abs(-5)" +##xpr = "round(123.456789)" +##xpr = Associative +##xpr = "102%12%7" +##xpr = "100/4/3" +##xpr = "2^3^4" +## Comparison operators +##xpr = "1+2*3==1+2*3" +##xpr = "e^5>=e^5+1" +##xpr = "1+2*4/3+1!=1+2*4/3+2" +## Common tests +##xpr = "(100)" +##xpr = "666" +##xpr = "-.1" +##xpr = "1/3" +##xpr = "1.0/3.0" +##xpr = ".1 * 2.0^56.0" +##xpr = "e^34" +##xpr = "(2.0^(pi/pi+e/e+2.0^0.0))" +##xpr = "(2.0^(pi/pi+e/e+2.0^0.0))^(1.0/3.0)" +##xpr = "sin(pi/2^1) + log(1*4+2^2+1, 3^2)" +##xpr = "10*e^0*log10(.4 -5/ -0.1-10) - -abs(-53/10) + -5" +##xpr = "sin(-cos(-sin(3.0)-cos(-sin(-3.0*5.0)-sin(cos(log10(43.0))))+cos(sin(sin(34.0-2.0^2.0))))--cos(1.0)--cos(0.0)^3.0)" +##xpr = "2.0^(2.0^2.0*2.0^2.0)" +## ошибка ? "sin(e^log(e^e^sin(23.0),45.0) + cos(3.0+log10(e^-e)))" +##xpr = "sin(e^log(e^e^sin(23.0)*45.0) + cos(3.0+log10(e^-e)))" +##xpr = Error cases +##xpr = "" +##xpr = "+" +##xpr = "1-" +##xpr = "1 2" +##xpr = "ee" +##xpr = "==7" +##xpr = "1 + 2(3 * 4))" +##xpr = "((1+2)" +##xpr = "1 + 1 2 3 4 5 6 " +##xpr = "log100(100)" +##xpr = "------" +##xpr = "5 > = 6" +##xpr = "5 / / 6" +##xpr = "6 < = 6" +##xpr = "6 * * 6" +##xpr = "(((((" +##xpr = “pow(2, 3, 4)” + +## EVAL TEST +##test=xpr +##test=test.replace('^','**') +##test=test.replace(' ','') +##test=test.replace(',','.') +##print ('EVAL:',test,'=',eval(test)) +##print(xpr) + +oper = ('!','^','//','/','*','%','-','+','(',')','==','<=','>=','<','>','!=','=') +digit = ('1','2','3','4','5','6','7','8','9','0','.') +func = ('sin','cos','tan','log10','log','exp','abs','round','sqrt') +stroka = '' +slovo = '' +operator = '' +spisok = [] +a = 0. +b = 0. +result = 0. + + +#разбор строки на элементы списка +def parse(stroka): + slovo='' + #исправление неверно введенных знаков + stroka = stroka.replace(' ','') + stroka = stroka.replace(',','.') + stroka = stroka.replace('--','+') + stroka = stroka.replace('++','+') + stroka = stroka.replace('+-','-') + stroka = stroka.replace('-+','-') + stroka = stroka.replace('<+','<') + stroka = stroka.replace('>+','>') + stroka = stroka.replace('=<','<=') + stroka = stroka.replace('=>','>=') + stroka = stroka.replace('==+','+') + if stroka[0] == '+': stroka=stroka[1:] + #print('parse:',stroka) + + #разбор строки + for i,sym in enumerate(stroka + ' '): #добавлен дополнительный пробел + if sym in oper or i == len(stroka): + #print(i,slovo,sym) + if slovo == 'pi': + spisok.append(pi) + elif slovo == 'e': + spisok.append(e) + elif slovo in func: + spisok.append(slovo) + elif slovo.replace('.','').isdigit() and slovo.count('.')<2: + spisok.append(float(slovo)) + elif slovo != '': + print('ERROR: wrong symbol "',slovo,sym,'"') + exit(0) + spisok.append(sym) + slovo = '' + #print(sym) + + else: + slovo = slovo + sym + #print(i,sym,spisok) + spisok.pop() #удаляется добавленный пробел + + for i,data in enumerate(spisok): + if spisok[i] == '/' and spisok[i + 1] == '/': + spisok[i] = '//' + spisok.pop(i + 1) + if spisok[i] == '>' and spisok[i + 1] == '=': + spisok[i] = '>=' + spisok.pop(i + 1) + if spisok[i] == '<' and spisok[i + 1] == '=': + spisok[i] = '<=' + spisok.pop(i + 1) + if spisok[i] == '=' and spisok[i + 1] == '=' or spisok[i] =='=': + spisok[i] = '==' + spisok.pop(i + 1) + if spisok[i] == '!' and spisok[i + 1] == '=': + spisok[i] = '!=' + spisok.pop(i + 1) + if spisok[i] == '-' and spisok[i - 1] in ('^','//','/','*','%','-','+','==','<=','>=','<','>','!=','=') and type(spisok[i + 1]) == float: + spisok[i + 1] = spisok[i + 1]* - 1 + spisok.pop(i) + if (spisok[i] == '-' and i == 0) or(spisok[i] == '-' and spisok[i - 1] in('*','^','+','-','(','<','>','=') ): + spisok[i] = -1 + spisok.insert(i + 1,'*') + if spisok[i] == '-' and spisok[i - 1] == '/': + spisok[i - 1] = '*' + spisok[i] = -1 + spisok.insert(i + 1,'/') + #print(spisok) + return(spisok) + + +def operate(operator,a,b): + if operator == "+": + result = a + b + elif operator == "-": + result = a - b + elif operator == "*": + result = a * b + + elif operator == "//": + if b != 0: + result = a // b + else: + print('ERROR: division by zero') + exit(0) + elif operator == "/": + if b != 0: + result = a / b + else: + print('ERROR: division by zero') + exit(0) + elif operator == "%": + result = a % b + elif operator == "^": + result = a**b + elif operator == "<=": + result = a <= b + elif operator == ">=": + result = a >= b + elif operator == "<": + result = a < b + elif operator == ">": + result = a > b + elif operator == "==": + result = a == b + elif operator == "!=": + result = a != b + elif operator == "abs": + result = abs(a) + elif operator == "round": + result = round(a) + elif operator == "cos": + result = cos(a) + elif operator == "sin": + result = sin(a) + elif operator == "tan": + result = tan(a) + elif operator == "log": + result = log(a) + elif operator == "log10": + result = log10(a) + elif operator == "sqrt": + result = sqrt(a) + elif operator == "cos": + result = cos(a) + elif operator == "exp": + result = exp(a) + elif operator == "!": + result = factorial(a) + else: + print('ERROR: unknown math operator',operator) + result = 0 + if show == 'y': + if operator in oper: + print('Operate:',a,operator,b,'=',result) + elif operator in func: + print('Operate:',operator,a,'=',result) + return result + +#вычисление выражения без скобок +def calculate(spisok): + if show == 'y': print('Calculate:',spisok) + # перебор списка функций + for f in func: + for i in range(spisok.count(f)): + #print(f,spisok.count(f)) + s = spisok.index(f) + spisok[s] = (operate(f,spisok[s + 1],0)) + spisok[s + 1] = '' + wipe(spisok) + #print(*spisok,sep='') + + #вычисление возведение в степень с реверсом списка + #print('^ count:',spisok.count('^')) + if '^' in spisok: + spisok.reverse() + #print('reverse: ',spisok) + while '^' in spisok: + i = spisok.index('^') + #print('i = ',i) + spisok[i] = spisok[i + 1]**spisok[i - 1] + #print(spisok[i + 1],'^',spisok[i - 1],'=',spisok[i]) + spisok[i - 1] = '' + spisok[i + 1] = '' + #print(spisok) + wipe(spisok) + #print(spisok) + spisok.reverse() + + #перебор списка математических операций + for j in oper: + #print('operation = ',j) + #print(spisok) + i = 1 + while i < len(spisok): + if spisok[i] == j: + #print('calculate: ',*spisok,sep='') + spisok[i] = operate(spisok[i],spisok[i - 1],spisok[i + 1]) + spisok[i - 1] = '' + spisok[i + 1] = '' + #print(spisok) + wipe(spisok) + i = i - 1 + i = i + 1 + #print('Stop calculate:',float(spisok[0])) + wipe(spisok) + #print(spisok) + result = spisok[0] + if len(spisok) > 1: + print('ERROR: missed operator') + #exit(0) + return(result) + +#очистка списка от пустых значений '' +def wipe(spisok): + #print('WIPE:\n',spisok) + while '' in spisok: + i = spisok.index('') + spisok.pop(i) + #print('WIPED:\n',spisok) + return(spisok) + +#поиск начала и конца выражения в скобках() +def brktindx(spisok): + bl = spisok.index('(') + br = spisok.index(')') + s = spisok[bl + 1:br] + #print('BL BR ',bl + 1,' ',br,' ',*s,sep='') + while '(' in s: + if s.count('(') == s.count(')'): + bl = spisok.index('(',bl + 1) + br = spisok.index(')',bl + 1) + s = spisok[bl + 1:br] + #print('BL BR ',bl + 1,' ',br,' ', *s,sep='') + else: + br = spisok.index(')',br + 1) + s = spisok[bl:br + 1] + return(bl + 1,br) + + +#начало основной программы + +#проверка скобок в строке +if xpr.count('(') != xpr.count(')'): + print('ERROR: brackets are not balanced') + exit(0) + +#разбор строики в список +spisok = parse(xpr) +#print(*spisok,sep=',') + + + + + +#поиск скобок и вычисление в скобках +while '(' in spisok: + a,b = brktindx(spisok) + #print('in brackets: ',*spisok[a:b],sep='') + spisok[a - 1] = calculate(spisok[a:b]) + while a < b + 1: + spisok[a] = '' + a = a + 1 + wipe(spisok) + #print(*spisok,sep='') + +#вычисление без скобок +result = calculate(spisok) +print(result) + + + + From 75ca140272b6e4c542fe704356a9005fad889d50 Mon Sep 17 00:00:00 2001 From: novash-k <49132079+novash-k@users.noreply.github.com> Date: Fri, 12 Apr 2019 16:26:02 +0300 Subject: [PATCH 003/159] Add files via upload --- pycalc.py | 47 ++++++++++++++++++++++++----------------------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/pycalc.py b/pycalc.py index 72143a38..bf696c7e 100644 --- a/pycalc.py +++ b/pycalc.py @@ -324,36 +324,37 @@ def brktindx(spisok): return(bl + 1,br) -#начало основной программы +# основная функция +def calc(xpr): + #проверка скобок в строке + if xpr.count('(') != xpr.count(')'): + print('ERROR: brackets are not balanced') + exit(0) -#проверка скобок в строке -if xpr.count('(') != xpr.count(')'): - print('ERROR: brackets are not balanced') - exit(0) + #разбор строики в список + spisok = parse(xpr) + #print(*spisok,sep=',') -#разбор строики в список -spisok = parse(xpr) -#print(*spisok,sep=',') + #поиск скобок и вычисление в скобках + while '(' in spisok: + a,b = brktindx(spisok) + #print('in brackets: ',*spisok[a:b],sep='') + spisok[a - 1] = calculate(spisok[a:b]) + while a < b + 1: + spisok[a] = '' + a = a + 1 + wipe(spisok) + #print(*spisok,sep='') -#поиск скобок и вычисление в скобках -while '(' in spisok: - a,b = brktindx(spisok) - #print('in brackets: ',*spisok[a:b],sep='') - spisok[a - 1] = calculate(spisok[a:b]) - while a < b + 1: - spisok[a] = '' - a = a + 1 - wipe(spisok) - #print(*spisok,sep='') - -#вычисление без скобок -result = calculate(spisok) -print(result) - + #вычисление без скобок + result = calculate(spisok) + #print(result) + return (result) +print (calc(xpr)) From cda6b0d19138141a01842fe9e4474f640197d2bf Mon Sep 17 00:00:00 2001 From: novash-k <49132079+novash-k@users.noreply.github.com> Date: Sun, 14 Apr 2019 16:55:23 +0300 Subject: [PATCH 004/159] Add files via upload --- pycalc-1.0.tar.gz | Bin 0 -> 3872 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 pycalc-1.0.tar.gz diff --git a/pycalc-1.0.tar.gz b/pycalc-1.0.tar.gz new file mode 100644 index 0000000000000000000000000000000000000000..771197294c9bdc9a1a037433230f363eec658bfc GIT binary patch literal 3872 zcmV+*58v<~iwFo&JF{E@|72-%bT4puV_|G#Eio=IE_7jX0PP&@a@)pHzcJ%?I7#CH zKmsHHekkDxYMn%BJ#l1>94DPoMGZ(EB}62E0HAI4m*X^TXOfOzpnV6&6F16-74zS$*Nf-B-ptJZhSt(b1vp^xXp?w2lrtBYV&zCSeafE2MC* z3Bt72VhZ4jY4Xn`hE5aY$ApluN zK5pIp((QlCtrbAA47--a^(xGJ! zT7=_QPVC?$}-G1i$Y!mwA^b-CpRfPk>DBmuv)KPPnp6L;H=9lL|Ba2>(*LjH==<)Fu$d2C zcMuSJ=(&E#TW$z91a>3c5C|L&Ld)|A)Zo4KMXUM7BU zB6k^vHQ+=>{=gJ3A58K{SS*T|;#_EaQ&JgnfJ@lh! zW{R^gCUOY*hEU-D{Pqe0z~c4as5cw4`mY}4{~N~A|F7eS{N3`8Jj)NLz~aHs3XkJR z;ModQx^AEZwxd{hW8obPg<|2yz&*lK*OcHhKUC-=Pw87-@Lt;*2!iE70TC0g-13h` zL+XUP_~c88cmPnBiwH81tXRF?p%u}R#O*)r?rq<@cl+)RI7fKuQ8NgAg&fm?XNn*X z_yL9`08P7T!ur=@WZ?B-M_Of<`WzRltclAa6q!pua!#WfB;3C zho31FXbDKj&_4=r4q#=+QAf^!Bn#{7Oh^eIE3*;Ibg)s#v~j+&00YbCHi<6;$L_

PFJeQ zvVi;ux$i*2N?ecnXhOjheNEMCYqO`ODnWysXwg+w)f3NZ85+vGi9p0hf_!#uF!%5@ zfmt?6Mv_ulGRn1*A(xUIb*%)=dWxmio^R5swYHIMxoPk=Lf!{;QI3Fs$AIVXIF-=T zv&%Gr4&Ex!BnR+k$+N45oCeZ02{`2fmULY&H4{BXDUXQN2_&_VZ1LTZ)01?gR;f3d z8*jax=(`mJZr6qpeL$0{8aH+0=0-;QdNnzYM!VLo^Ral>9fFzL0nAFygyXc-Op{#_ z__W>FGU21FuccvuO<7+x<6C3OV+i!wDm;VFjuj-bNzRdiL?WTFz4Pkyb6k7el1uu)+tkyN}x8D>u^JeC^RgiqMaIn)sh zjxsi37elRAG!<1cc&Ezf=!nhkP}6osM>Zf4PASG^Gdn(?{9}AJ{$~8c_!;>f7n8P` zyR>N=pA4j>)KNUp2{}MRnF~nUDwXBzXy)LTE{VVG`>qd*UqBOPmLOkFg{tHONk$8r z^nKGzxe^FrNHs9FdfI3tFnKux2vkXp)JcOhNj6Z-MGBQ2iG~K*f=e^iQiZ={OOtG7 zV45IWDb*t3F?;^`@xMIxp=5w{Dxk#AkN?eL{`SYW?vRhR@4@P`j(%zabbN~+6`y(o zt4k%ZEh=KEB+B`{1bU156!@!%)5VcMA_81nqJm&-HNpfy!Y6sQgn}TjE@5l}=_PR$ zh@c47Dt@3WaNdMdg|iGN@{!>*fu6XDA6x7WZ{S?T2NR^|*-#5Hk~*{)aMs|g!`Xnd z3Fii!Z^8LCoLVG1u9OT3j1!u`AmI~M5BOyB%CGPVX%u{dOT#CN;c&%#4`{&J>z-J+ zz>7jKa38q*HV(g0hX*nF1n&0_1ccQpLWf@`mzXKmUpFAd$&nHiy z;T#LQNi%Rp_GnGIe5wN++TdI6NV$u0XLuq|%;7lE0{!La)g zz`k}sOt8eV*os=rs6%fZM3p%6Pm$RVcyVMw0`Dv|OV-^7Gq;uCbVzK6PzN%5F#XsF zA#{R4$SuOH?_0q8W@dYYHN1lJM>NFA6KMQ#@->>=_7VQyHl0~Q=5ndQeErVBAFLg+q=8h zA`g8R3Q(AUjyoW0;%q_`aZQxxkm)0kT1&TQ1|mC`i2$5q0(0QPOcOBrTuS^}MyZ8) zivrQPM3Gx^={(ni(Pn=01=#m9u;`}{S)YL8JSABV$T9VVa0&my*Ay8CqV7|Ewt8b+A>YFoEGYnN^2(~CK&fYG_+89mT?~ziP$jFjKoqS~?b<@u!l&Mg? zlxkA0Zfp^Oy2SOROX)5#ZQGHiYLu(SDx!9B@m#36qS{VC{g6)v4(97l$Rfv%APA8C zMN(BGsp62zLr^N9`ZOH*PTU1qE#{>>AEr{A7b}+1i3Z5-lUcUR3cINa)9e`2h>kE_ zbW-qYF1%U@U&@6q0ek^MwYrvyu^n9QwDdS9C{?Qw>-?1^y(aeT2R7TD?VOUoP~Xk0 zgUK~8N3hqE>$=3cnLEHY3n!$V2VW``fp3}#wG#|B%|Z@a1t?p^D4PXLig^^UC`2#| zgffeTS}j0XEk=Q&H5aE7NLJAVvJy8Bi|=0+;z0qOhlLwGg*Z@p=i%UXQ6UbL=y^EM zT#N&Sd>#&NPc6dHwE`?%TcFcteweEiwEw!JM<024IM7^-vzmu7eQ7nrOGb!vbQn1& zj{DHzFUn%tq7vW9^W?Q@J<8sOu-74}*fo_fs_Sxt6MyG`<*7AgrgYe56XzrgsoEq- zbiS~fBbr#7vLyMM7U?4h>*ME>uO@$Idnt)M6l}yw`9Hh~vwckHzawme2D5u8n%Qy~ zzthVk@tFaNMSM4g#=<;NZ>&Svz_x5&OiT0Gb`Y8T70Qp7;~yq}1L?k>l@k5=;b0X8 zHv5)y6w4GRI{s<=jM)>vo`D&@U|nap_j(?oKI6_j_2p0J<7GTS?(_vMPSmG!c9NAH zCsfZ^iVgV=+gQu)G~^W}pU&_9#Ij7o9UA2#H_RGQ92ur<8KX!Sj)kNO4C4~Uae;v> zG?I8!?YY{Nx0a*Uc$Dsit~Xm5AT~r>Z(Ks{APNn0{Bq=*r5rJG990t23Aw3Ww8RhX zAfUb3;+`;{Wbz-?dht>T3*$MDpJ2jl4N95#`Q!<1bbY~gkZ11{(9~I2{T@djm&c@v zt<)HOa(j2X^=Bs?+M=+Q8`b6`nmFgLi9LcOpZDe%WlP(2wsp<)BatT0VC4W+&j?%b zUxL3r%S{ZP&yoTdo5`0DEKu`~e-eV6kJ8$A26I|Sks2L;u1k*J63pfw2!OS>(FjX?h|@cc@!AE9F$_$fL5y@n$kig^o%WnurE(#Q zb3(^Td*c{)uP+1t}r zyp*v0V*bW1^0aA+8D}TaTbdWK?*o2vvY={Aw4|mh9Sl0Y)jgqMKrEjU#|=rx8dy%3 z_L2h@MTJE#jL!I*%;&SPfcfyu5%Eh+?ENKsO~H{u{NRlp|I+@yk@0_HqqhA0*EP=nG72pHf6o8!-Mzo}?)JT3>irk{ zzo8ph|JRyJ|G&ohuXv|I{PSNSYX|ZF1rQb(h;W(YQMj@dW_etJ|Nm Date: Sun, 14 Apr 2019 17:28:04 +0300 Subject: [PATCH 005/159] setup 2 --- pycalc-1.0.tar.gz | Bin 3872 -> 3994 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/pycalc-1.0.tar.gz b/pycalc-1.0.tar.gz index 771197294c9bdc9a1a037433230f363eec658bfc..814a4f6608be1e47d296c427bd245e5ef8589793 100644 GIT binary patch literal 3994 zcmV;L4`uKliwFn~L$h20|72-%bT4puV_|G#Eio=IE_7jX0PP&@ZreuEe@h_mu#ORs zlt_uBzFNWbUD~>LMO(*k`f)(cGAL}i4_2YVXKzry5+`U5@G*|Z{?kh;I z&?mW>U6LXxQg+3%V>1gNNepHVCn~!N66ZVGl8c`U{CV#E^3bk5`F$gz+J5W-uCU+ z-`TE>hc9CN+s$V2`s;eM{+iL!Vg1`J%~&H^x&AL4HVD@MVXcJUBP8tKr@_>%4Gxd4 z-Ts^HjQ{UwZLPHb>wtUo=;*+n96I|#U>zOwr}k(_Ou`C7E1>YK38i!RJ=p*5TYpmD z+aS*tEw_ZQ8gX3wx1|;=~ zbKmlh)sy-z>jse@INphHdkRIbOWum7oa`{vutlX~%N}(Jr>~vZe>}np>{EE#9?*#o z{NCGnYv;}fJHqSKA9%JKun|O+yCC18?l>fInEwukm zyItD(T}FKM~A%q zK6ezR2-=j_K3tfhDPG2Z@J{Y93TwnWnR+8ryu35X>%wAQ#1xnO3nIVtQa<_tb2_G& z<8&BVmTJR2Js3N~>4^H~y__5%C{(SBKna+O<&1h=n`Oh``|IGRyz_!2+4i0{K zM7VJO7p=e6=@<>DH;hK3S^EE9cl~+sdE^7D*WYNiTao=YT1`X8_18L$a{aFZ!gz0a zN3P}hRABkQ*b0uLOu)4jstg=o@$HFX;e&-wFcpf0w~=#%m#!)PM_!=NhpuvH4Ip~k z)<_U6mzZ(qwcFm&bWA6~E|xqgkq-dYpx~y5l;ei$QC5hXA+1=Z|d-u&dI}nJ2 zQflIOYuBx%2vaZ*PnF9Zr2p z!eoMQL~@UR)@rqV0zKM1_lU7zlt6?Gy(1sj05W@=b>!?zvaqqigp{yYTg+glfz3ju zj`NiTm{`8HNqWIQb{<64j9Sswc{7 z6)LK{ia@%D9rD$+LEVGX1ZCBz7|EWhl2L6`47rlzsB0Cd)>ACC-g1>zZ}g08%`Jo1 z5%LBM7v=B?SPWPW_fv^+x^|T&$iZ4An&bfXEV*{wkkd%ICIP2h#EP!#m3E@VsN{8G z^?gZgC2KrqIvGm3(Wo_B?as@uB-(EKzB904M(@+)P>oxR$&RNIfo{q0aURHn;2=crl~k2gEy+IA04UL6OOc(86%sJkfsvRvXz~k z&;K<$n|(d|e)fp`fs09d%v^f3hb061Qkp0pj0rhFMU@Lkdn%RX>}=-HS1w7v?Rky| z!Oy1&HA{3~O}VOMfh4^JP1?R`rc4QhFr)@3TQjXR5~#eKL4;mOgEUEtv`N-cEO`o* zL878Xw&0_ks;R?YvZhToGdOJ!t&*yd5EkX1KmL#FJdg~~P6Y<>^T+>XK7afD+i#P1 zx9>vq*+4rr0XurcTg{{H$Qn>d?1_q4sfcoZD}mOcHU<7_VjLU^BqG4ID=LV_q7fzl z5|-pe2n9hPE}?G%=_PR;IzbWYb-bZ0aNUASg{uk|@{!>(p+9jGZ(HmMAK+TYf(cR# z?ISy2UFuL{z}0}O30DiQHe4OJUWV%xxU^7qjFgNBloP5zA>j_u1MX~H`6t{Vje&WVKqUKIS1bKl{Qk^2oBT=2;!@O*DyKwPaR^!W#5XOLgbRnGrC`(gHE_9I+Rq3sJmnf)|7gFD!)0LdC* zS&qbolDq6Ygh^$B6zu$jVgJPVJZ7Ce1)G0@-9LefC(!V8c23|C3bSum`_uUs^Un#0 z1tI{W^VwtGZ!~iLu%tFCaU%6uiKKEhxB#nKy%d(p)aoLR)yrUQR+$c7fVEX+T6zJN zxyd#ABD5{8`xl{^$;q$}Lxg+UJ~2TPt712-F~bJEyC0sbG5Zvm{(u#S8YJ+>LbYVg zhoI)R;-8L*Jt1@gnLVg}q=eu)K_TQW;oA2N(0#qoJ;Ew}g6juV#QCRC`NRB6RJqxA zgy|{bLnY%B4T`g3ZUlMb*hX}cR{IFTk%53{2PmeTYRCS#-Qw287Sq&hwwd+TEZ3!w zy}5Rpo{myI&teNS?EHInPJWLnRAq6mLGGR0r;>0G2~6-B5sEx z#|lE8g_5tMn_KQFRI2U0y*qnd^1yRo0}2b!cShu6`&-y7C&Q~OB z0XeFk5H4X~_?j|fV4QU~Wg4vRp3UvOF7ibWD>03U8oD|2%E$;tY-GTOXV&oCY?*EB;vvM@F{TlHAr3kzd^HzeEySmlp>$dZnUL;JqXj%WL)Ho2}#tXsJge5-IldU^PjN)h^|nHYA0 z!KPWrVXJ^-tC(c7fJrfr0v3e?W`R&HCsZw18}jn@7dZFAM2l z1D!{O2R(%}u=UQP!Q-Mr8rY)e(Li-E4Q%A|Xz+My6^*VHQ0dx=F@59(xr2iG=R14! zp_@ko)x|XHc@*(Ws|8)sL!`aKbaFCr9!&U)vZ!xSiJs);?zMP7%HD>s*C8q26-yZI z>vEkFf9HVPQ!8es^x0t(=OhcMy-Bju<&D)+r-|5kcY2v5J~Kg)h_6N1xG_)cH#T6~z>aL5#9Q;l zaS)mR9kw4&XW!5N0n&Z9*h(BOPY2s!V6|sWjv|@DUE-mfPGrK!f2d@!(#b=dpg{sL zqz?fhFYoX%?~tP8AnNm;&vH6Nlk-fAIa|S^Wrbz? zHgO)tE7>^+lz(D}abH4_u$5qkXwbp=?8o%+T=JNuN7%H*>ly9Hd!ig4-9Q1Cgd;4L zASCc8e&38ra&}uPhAmx^Ru(ox$M%R8bTq;sz5O=p&S<|$Vw%NX4PKWoATOfSR2jK-N11dkpX-|c=X04 z)b>Nyu*5G%zD3Fr5l3Dnv7C^b>O~=bZ2LYPE`obPeUiz4xYvt9B?QKE?mt0=Sqw_4 z`1$-(Jm~t2oggpXDWIw|xB4BB9)#3;M9-C#%8YpyFw`@`BK}jb*GIXD!Q(|z0CO|{9GnG?yziX^Am_vM z==-CkQApu1`rcBL9K9u2tUq)B+ScuR>C^sK-zKl_fl2aa1>fBCJ@!%YQ}!9ou*9c0 zec~9!E?|sqATEO#X^)UQija5Oa&iZii&;FztPd(4E6EHte}h~glXrnkU5>Gz)Spm< zzQ?|!gLd%=zIB7t0d?rBROUASDoz;L+tY3oO4xZZe`6O~TAX4=*-7}8=1FAxK%ZPJ z*fl0S(5=BCMPWP3aefio$)uBj~8wM^WlXd;+LA( z`%CtkxF~Z|M4UE3h+}GGf$1qYBL&%9#_)3VJL5tu1z*-?EpsX00%bH&i7h|}S z)GKO>0#kNBz^Jl$8#{eqI-Zx_SUJ(l3XjebaXl|s739aOa^jqQO?uaw-QXmbGiPVD z2qEFu31Wq3i+ye1|EYt8ce|G&!jzZdI2r1*}JP6nq3BYSe< z*Mf(^3;O=Qo>~8<(JKG{!?i&9)9&*3-v#y$o3VotY~)8*HvG%lzuw8%ztJgw|8t$| zAN}a3^aiE<$M%2s&U<^WZQuQ+)_<}68=ZF6{vls1?f*I;{-<9;^z(lqs|V5l1rb&# zh;W(YQCJyagyP?y3NP%ZiKYD)+y8U>e=yJd|6dH<=#=sQTA=*@FTd~q|58E;C6rJ? z2_=+JLJ1|5P(leMlu$wmC6rJ?2_=+JLJ1|5P(leMlu$wmCH!{b|2xWu#{hT$0Epo1 Ay8r+H literal 3872 zcmV+*58v<~iwFo&JF{E@|72-%bT4puV_|G#Eio=IE_7jX0PP&@a@)pHzcJ%?I7#CH zKmsHHekkDxYMn%BJ#l1>94DPoMGZ(EB}62E0HAI4m*X^TXOfOzpnV6&6F16-74zS$*Nf-B-ptJZhSt(b1vp^xXp?w2lrtBYV&zCSeafE2MC* z3Bt72VhZ4jY4Xn`hE5aY$ApluN zK5pIp((QlCtrbAA47--a^(xGJ! zT7=_QPVC?$}-G1i$Y!mwA^b-CpRfPk>DBmuv)KPPnp6L;H=9lL|Ba2>(*LjH==<)Fu$d2C zcMuSJ=(&E#TW$z91a>3c5C|L&Ld)|A)Zo4KMXUM7BU zB6k^vHQ+=>{=gJ3A58K{SS*T|;#_EaQ&JgnfJ@lh! zW{R^gCUOY*hEU-D{Pqe0z~c4as5cw4`mY}4{~N~A|F7eS{N3`8Jj)NLz~aHs3XkJR z;ModQx^AEZwxd{hW8obPg<|2yz&*lK*OcHhKUC-=Pw87-@Lt;*2!iE70TC0g-13h` zL+XUP_~c88cmPnBiwH81tXRF?p%u}R#O*)r?rq<@cl+)RI7fKuQ8NgAg&fm?XNn*X z_yL9`08P7T!ur=@WZ?B-M_Of<`WzRltclAa6q!pua!#WfB;3C zho31FXbDKj&_4=r4q#=+QAf^!Bn#{7Oh^eIE3*;Ibg)s#v~j+&00YbCHi<6;$L_

PFJeQ zvVi;ux$i*2N?ecnXhOjheNEMCYqO`ODnWysXwg+w)f3NZ85+vGi9p0hf_!#uF!%5@ zfmt?6Mv_ulGRn1*A(xUIb*%)=dWxmio^R5swYHIMxoPk=Lf!{;QI3Fs$AIVXIF-=T zv&%Gr4&Ex!BnR+k$+N45oCeZ02{`2fmULY&H4{BXDUXQN2_&_VZ1LTZ)01?gR;f3d z8*jax=(`mJZr6qpeL$0{8aH+0=0-;QdNnzYM!VLo^Ral>9fFzL0nAFygyXc-Op{#_ z__W>FGU21FuccvuO<7+x<6C3OV+i!wDm;VFjuj-bNzRdiL?WTFz4Pkyb6k7el1uu)+tkyN}x8D>u^JeC^RgiqMaIn)sh zjxsi37elRAG!<1cc&Ezf=!nhkP}6osM>Zf4PASG^Gdn(?{9}AJ{$~8c_!;>f7n8P` zyR>N=pA4j>)KNUp2{}MRnF~nUDwXBzXy)LTE{VVG`>qd*UqBOPmLOkFg{tHONk$8r z^nKGzxe^FrNHs9FdfI3tFnKux2vkXp)JcOhNj6Z-MGBQ2iG~K*f=e^iQiZ={OOtG7 zV45IWDb*t3F?;^`@xMIxp=5w{Dxk#AkN?eL{`SYW?vRhR@4@P`j(%zabbN~+6`y(o zt4k%ZEh=KEB+B`{1bU156!@!%)5VcMA_81nqJm&-HNpfy!Y6sQgn}TjE@5l}=_PR$ zh@c47Dt@3WaNdMdg|iGN@{!>*fu6XDA6x7WZ{S?T2NR^|*-#5Hk~*{)aMs|g!`Xnd z3Fii!Z^8LCoLVG1u9OT3j1!u`AmI~M5BOyB%CGPVX%u{dOT#CN;c&%#4`{&J>z-J+ zz>7jKa38q*HV(g0hX*nF1n&0_1ccQpLWf@`mzXKmUpFAd$&nHiy z;T#LQNi%Rp_GnGIe5wN++TdI6NV$u0XLuq|%;7lE0{!La)g zz`k}sOt8eV*os=rs6%fZM3p%6Pm$RVcyVMw0`Dv|OV-^7Gq;uCbVzK6PzN%5F#XsF zA#{R4$SuOH?_0q8W@dYYHN1lJM>NFA6KMQ#@->>=_7VQyHl0~Q=5ndQeErVBAFLg+q=8h zA`g8R3Q(AUjyoW0;%q_`aZQxxkm)0kT1&TQ1|mC`i2$5q0(0QPOcOBrTuS^}MyZ8) zivrQPM3Gx^={(ni(Pn=01=#m9u;`}{S)YL8JSABV$T9VVa0&my*Ay8CqV7|Ewt8b+A>YFoEGYnN^2(~CK&fYG_+89mT?~ziP$jFjKoqS~?b<@u!l&Mg? zlxkA0Zfp^Oy2SOROX)5#ZQGHiYLu(SDx!9B@m#36qS{VC{g6)v4(97l$Rfv%APA8C zMN(BGsp62zLr^N9`ZOH*PTU1qE#{>>AEr{A7b}+1i3Z5-lUcUR3cINa)9e`2h>kE_ zbW-qYF1%U@U&@6q0ek^MwYrvyu^n9QwDdS9C{?Qw>-?1^y(aeT2R7TD?VOUoP~Xk0 zgUK~8N3hqE>$=3cnLEHY3n!$V2VW``fp3}#wG#|B%|Z@a1t?p^D4PXLig^^UC`2#| zgffeTS}j0XEk=Q&H5aE7NLJAVvJy8Bi|=0+;z0qOhlLwGg*Z@p=i%UXQ6UbL=y^EM zT#N&Sd>#&NPc6dHwE`?%TcFcteweEiwEw!JM<024IM7^-vzmu7eQ7nrOGb!vbQn1& zj{DHzFUn%tq7vW9^W?Q@J<8sOu-74}*fo_fs_Sxt6MyG`<*7AgrgYe56XzrgsoEq- zbiS~fBbr#7vLyMM7U?4h>*ME>uO@$Idnt)M6l}yw`9Hh~vwckHzawme2D5u8n%Qy~ zzthVk@tFaNMSM4g#=<;NZ>&Svz_x5&OiT0Gb`Y8T70Qp7;~yq}1L?k>l@k5=;b0X8 zHv5)y6w4GRI{s<=jM)>vo`D&@U|nap_j(?oKI6_j_2p0J<7GTS?(_vMPSmG!c9NAH zCsfZ^iVgV=+gQu)G~^W}pU&_9#Ij7o9UA2#H_RGQ92ur<8KX!Sj)kNO4C4~Uae;v> zG?I8!?YY{Nx0a*Uc$Dsit~Xm5AT~r>Z(Ks{APNn0{Bq=*r5rJG990t23Aw3Ww8RhX zAfUb3;+`;{Wbz-?dht>T3*$MDpJ2jl4N95#`Q!<1bbY~gkZ11{(9~I2{T@djm&c@v zt<)HOa(j2X^=Bs?+M=+Q8`b6`nmFgLi9LcOpZDe%WlP(2wsp<)BatT0VC4W+&j?%b zUxL3r%S{ZP&yoTdo5`0DEKu`~e-eV6kJ8$A26I|Sks2L;u1k*J63pfw2!OS>(FjX?h|@cc@!AE9F$_$fL5y@n$kig^o%WnurE(#Q zb3(^Td*c{)uP+1t}r zyp*v0V*bW1^0aA+8D}TaTbdWK?*o2vvY={Aw4|mh9Sl0Y)jgqMKrEjU#|=rx8dy%3 z_L2h@MTJE#jL!I*%;&SPfcfyu5%Eh+?ENKsO~H{u{NRlp|I+@yk@0_HqqhA0*EP=nG72pHf6o8!-Mzo}?)JT3>irk{ zzo8ph|JRyJ|G&ohuXv|I{PSNSYX|ZF1rQb(h;W(YQMj@dW_etJ|Nm Date: Sun, 14 Apr 2019 17:42:34 +0300 Subject: [PATCH 006/159] 1 commit --- final_task/pycalc-1.0.tar.gz | Bin 0 -> 3994 bytes final_task/pycalc.py | 361 +++++++++++++++++++++++++++++++++++ 2 files changed, 361 insertions(+) create mode 100644 final_task/pycalc-1.0.tar.gz create mode 100644 final_task/pycalc.py diff --git a/final_task/pycalc-1.0.tar.gz b/final_task/pycalc-1.0.tar.gz new file mode 100644 index 0000000000000000000000000000000000000000..814a4f6608be1e47d296c427bd245e5ef8589793 GIT binary patch literal 3994 zcmV;L4`uKliwFn~L$h20|72-%bT4puV_|G#Eio=IE_7jX0PP&@ZreuEe@h_mu#ORs zlt_uBzFNWbUD~>LMO(*k`f)(cGAL}i4_2YVXKzry5+`U5@G*|Z{?kh;I z&?mW>U6LXxQg+3%V>1gNNepHVCn~!N66ZVGl8c`U{CV#E^3bk5`F$gz+J5W-uCU+ z-`TE>hc9CN+s$V2`s;eM{+iL!Vg1`J%~&H^x&AL4HVD@MVXcJUBP8tKr@_>%4Gxd4 z-Ts^HjQ{UwZLPHb>wtUo=;*+n96I|#U>zOwr}k(_Ou`C7E1>YK38i!RJ=p*5TYpmD z+aS*tEw_ZQ8gX3wx1|;=~ zbKmlh)sy-z>jse@INphHdkRIbOWum7oa`{vutlX~%N}(Jr>~vZe>}np>{EE#9?*#o z{NCGnYv;}fJHqSKA9%JKun|O+yCC18?l>fInEwukm zyItD(T}FKM~A%q zK6ezR2-=j_K3tfhDPG2Z@J{Y93TwnWnR+8ryu35X>%wAQ#1xnO3nIVtQa<_tb2_G& z<8&BVmTJR2Js3N~>4^H~y__5%C{(SBKna+O<&1h=n`Oh``|IGRyz_!2+4i0{K zM7VJO7p=e6=@<>DH;hK3S^EE9cl~+sdE^7D*WYNiTao=YT1`X8_18L$a{aFZ!gz0a zN3P}hRABkQ*b0uLOu)4jstg=o@$HFX;e&-wFcpf0w~=#%m#!)PM_!=NhpuvH4Ip~k z)<_U6mzZ(qwcFm&bWA6~E|xqgkq-dYpx~y5l;ei$QC5hXA+1=Z|d-u&dI}nJ2 zQflIOYuBx%2vaZ*PnF9Zr2p z!eoMQL~@UR)@rqV0zKM1_lU7zlt6?Gy(1sj05W@=b>!?zvaqqigp{yYTg+glfz3ju zj`NiTm{`8HNqWIQb{<64j9Sswc{7 z6)LK{ia@%D9rD$+LEVGX1ZCBz7|EWhl2L6`47rlzsB0Cd)>ACC-g1>zZ}g08%`Jo1 z5%LBM7v=B?SPWPW_fv^+x^|T&$iZ4An&bfXEV*{wkkd%ICIP2h#EP!#m3E@VsN{8G z^?gZgC2KrqIvGm3(Wo_B?as@uB-(EKzB904M(@+)P>oxR$&RNIfo{q0aURHn;2=crl~k2gEy+IA04UL6OOc(86%sJkfsvRvXz~k z&;K<$n|(d|e)fp`fs09d%v^f3hb061Qkp0pj0rhFMU@Lkdn%RX>}=-HS1w7v?Rky| z!Oy1&HA{3~O}VOMfh4^JP1?R`rc4QhFr)@3TQjXR5~#eKL4;mOgEUEtv`N-cEO`o* zL878Xw&0_ks;R?YvZhToGdOJ!t&*yd5EkX1KmL#FJdg~~P6Y<>^T+>XK7afD+i#P1 zx9>vq*+4rr0XurcTg{{H$Qn>d?1_q4sfcoZD}mOcHU<7_VjLU^BqG4ID=LV_q7fzl z5|-pe2n9hPE}?G%=_PR;IzbWYb-bZ0aNUASg{uk|@{!>(p+9jGZ(HmMAK+TYf(cR# z?ISy2UFuL{z}0}O30DiQHe4OJUWV%xxU^7qjFgNBloP5zA>j_u1MX~H`6t{Vje&WVKqUKIS1bKl{Qk^2oBT=2;!@O*DyKwPaR^!W#5XOLgbRnGrC`(gHE_9I+Rq3sJmnf)|7gFD!)0LdC* zS&qbolDq6Ygh^$B6zu$jVgJPVJZ7Ce1)G0@-9LefC(!V8c23|C3bSum`_uUs^Un#0 z1tI{W^VwtGZ!~iLu%tFCaU%6uiKKEhxB#nKy%d(p)aoLR)yrUQR+$c7fVEX+T6zJN zxyd#ABD5{8`xl{^$;q$}Lxg+UJ~2TPt712-F~bJEyC0sbG5Zvm{(u#S8YJ+>LbYVg zhoI)R;-8L*Jt1@gnLVg}q=eu)K_TQW;oA2N(0#qoJ;Ew}g6juV#QCRC`NRB6RJqxA zgy|{bLnY%B4T`g3ZUlMb*hX}cR{IFTk%53{2PmeTYRCS#-Qw287Sq&hwwd+TEZ3!w zy}5Rpo{myI&teNS?EHInPJWLnRAq6mLGGR0r;>0G2~6-B5sEx z#|lE8g_5tMn_KQFRI2U0y*qnd^1yRo0}2b!cShu6`&-y7C&Q~OB z0XeFk5H4X~_?j|fV4QU~Wg4vRp3UvOF7ibWD>03U8oD|2%E$;tY-GTOXV&oCY?*EB;vvM@F{TlHAr3kzd^HzeEySmlp>$dZnUL;JqXj%WL)Ho2}#tXsJge5-IldU^PjN)h^|nHYA0 z!KPWrVXJ^-tC(c7fJrfr0v3e?W`R&HCsZw18}jn@7dZFAM2l z1D!{O2R(%}u=UQP!Q-Mr8rY)e(Li-E4Q%A|Xz+My6^*VHQ0dx=F@59(xr2iG=R14! zp_@ko)x|XHc@*(Ws|8)sL!`aKbaFCr9!&U)vZ!xSiJs);?zMP7%HD>s*C8q26-yZI z>vEkFf9HVPQ!8es^x0t(=OhcMy-Bju<&D)+r-|5kcY2v5J~Kg)h_6N1xG_)cH#T6~z>aL5#9Q;l zaS)mR9kw4&XW!5N0n&Z9*h(BOPY2s!V6|sWjv|@DUE-mfPGrK!f2d@!(#b=dpg{sL zqz?fhFYoX%?~tP8AnNm;&vH6Nlk-fAIa|S^Wrbz? zHgO)tE7>^+lz(D}abH4_u$5qkXwbp=?8o%+T=JNuN7%H*>ly9Hd!ig4-9Q1Cgd;4L zASCc8e&38ra&}uPhAmx^Ru(ox$M%R8bTq;sz5O=p&S<|$Vw%NX4PKWoATOfSR2jK-N11dkpX-|c=X04 z)b>Nyu*5G%zD3Fr5l3Dnv7C^b>O~=bZ2LYPE`obPeUiz4xYvt9B?QKE?mt0=Sqw_4 z`1$-(Jm~t2oggpXDWIw|xB4BB9)#3;M9-C#%8YpyFw`@`BK}jb*GIXD!Q(|z0CO|{9GnG?yziX^Am_vM z==-CkQApu1`rcBL9K9u2tUq)B+ScuR>C^sK-zKl_fl2aa1>fBCJ@!%YQ}!9ou*9c0 zec~9!E?|sqATEO#X^)UQija5Oa&iZii&;FztPd(4E6EHte}h~glXrnkU5>Gz)Spm< zzQ?|!gLd%=zIB7t0d?rBROUASDoz;L+tY3oO4xZZe`6O~TAX4=*-7}8=1FAxK%ZPJ z*fl0S(5=BCMPWP3aefio$)uBj~8wM^WlXd;+LA( z`%CtkxF~Z|M4UE3h+}GGf$1qYBL&%9#_)3VJL5tu1z*-?EpsX00%bH&i7h|}S z)GKO>0#kNBz^Jl$8#{eqI-Zx_SUJ(l3XjebaXl|s739aOa^jqQO?uaw-QXmbGiPVD z2qEFu31Wq3i+ye1|EYt8ce|G&!jzZdI2r1*}JP6nq3BYSe< z*Mf(^3;O=Qo>~8<(JKG{!?i&9)9&*3-v#y$o3VotY~)8*HvG%lzuw8%ztJgw|8t$| zAN}a3^aiE<$M%2s&U<^WZQuQ+)_<}68=ZF6{vls1?f*I;{-<9;^z(lqs|V5l1rb&# zh;W(YQCJyagyP?y3NP%ZiKYD)+y8U>e=yJd|6dH<=#=sQTA=*@FTd~q|58E;C6rJ? z2_=+JLJ1|5P(leMlu$wmC6rJ?2_=+JLJ1|5P(leMlu$wmCH!{b|2xWu#{hT$0Epo1 Ay8r+H literal 0 HcmV?d00001 diff --git a/final_task/pycalc.py b/final_task/pycalc.py new file mode 100644 index 00000000..2a0d4ce2 --- /dev/null +++ b/final_task/pycalc.py @@ -0,0 +1,361 @@ +import argparse +from math import pi,e,cos,sin,acos,asin,tan,atan,log,log10,sqrt,exp,factorial + +ap = argparse.ArgumentParser(description = 'Pure-python command-line calculator.') +ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') +ap.add_argument('-p', '--PRINT', default='n', choices=['y', 'n'], type = str, help = 'print evaluation process') +ap.add_argument('-m', '--MODULE', type = str, help = 'use modules MODULE [MODULE...] additional modules to use') +args = ap.parse_args() +##print(args.EXPRESSION) +##print(args.PRINT) +##print(args.MODULE) +xpr = args.EXPRESSION +show = args.PRINT +#show = 'y' + +##xpr = modstr=args.MODULE +##xpr = +##xpr = mod = __import__(modstr) +##xpr = print (modstr,'=',mod.myfunc(3)) + + +## Unary operators +##xpr = "-13" +##xpr = "6-(-13)" +##xpr = "1---1" +##xpr = "-+---+-1" +## Operation priority +##xpr = "1+2*2" +##xpr = "1+(2+3*2)*3" +##xpr = "10*(2+1)" +##xpr = "10^(2+1)" +##xpr = "100/3^2" +##xpr = "100/3%2^2" +## Functions and constants +##xpr = "pi+e" +##xpr = "log(e)" +##xpr = "sin(pi/2)" +##xpr = "log10(100)" +##xpr = "sin(pi/2)*111*6" +##xpr = "2*sin(pi/2)" +##xpr = "abs(-5)" +##xpr = "round(123.456789)" +##xpr = Associative +##xpr = "102%12%7" +##xpr = "100/4/3" +##xpr = "2^3^4" +## Comparison operators +##xpr = "1+2*3==1+2*3" +##xpr = "e^5>=e^5+1" +##xpr = "1+2*4/3+1!=1+2*4/3+2" +## Common tests +##xpr = "(100)" +##xpr = "666" +##xpr = "-.1" +##xpr = "1/3" +##xpr = "1.0/3.0" +##xpr = ".1 * 2.0^56.0" +##xpr = "e^34" +##xpr = "(2.0^(pi/pi+e/e+2.0^0.0))" +##xpr = "(2.0^(pi/pi+e/e+2.0^0.0))^(1.0/3.0)" +##xpr = "sin(pi/2^1) + log(1*4+2^2+1, 3^2)" +##xpr = "10*e^0*log10(.4 -5/ -0.1-10) - -abs(-53/10) + -5" +##xpr = "sin(-cos(-sin(3.0)-cos(-sin(-3.0*5.0)-sin(cos(log10(43.0))))+cos(sin(sin(34.0-2.0^2.0))))--cos(1.0)--cos(0.0)^3.0)" +##xpr = "2.0^(2.0^2.0*2.0^2.0)" +## ошибка ? "sin(e^log(e^e^sin(23.0),45.0) + cos(3.0+log10(e^-e)))" +##xpr = "sin(e^log(e^e^sin(23.0)*45.0) + cos(3.0+log10(e^-e)))" +##xpr = Error cases +##xpr = "" +##xpr = "+" +##xpr = "1-" +##xpr = "1 2" +##xpr = "ee" +##xpr = "==7" +##xpr = "1 + 2(3 * 4))" +##xpr = "((1+2)" +##xpr = "1 + 1 2 3 4 5 6 " +##xpr = "log100(100)" +##xpr = "------" +##xpr = "5 > = 6" +##xpr = "5 / / 6" +##xpr = "6 < = 6" +##xpr = "6 * * 6" +##xpr = "(((((" +##xpr = “pow(2, 3, 4)” + +## EVAL TEST +##test=xpr +##test=test.replace('^','**') +##test=test.replace(' ','') +##test=test.replace(',','.') +##print ('EVAL:',test,'=',eval(test)) +##print(xpr) + +oper = ('!','^','//','/','*','%','-','+','(',')','==','<=','>=','<','>','!=','=') +digit = ('1','2','3','4','5','6','7','8','9','0','.') +func = ('sin','cos','tan','log10','log','exp','abs','round','sqrt') +stroka = '' +slovo = '' +operator = '' +spisok = [] +a = 0. +b = 0. +result = 0. + + +#разбор строки на элементы списка +def parse(stroka): + slovo='' + #исправление неверно введенных знаков + stroka = stroka.replace(' ','') + stroka = stroka.replace(',','.') + stroka = stroka.replace('--','+') + stroka = stroka.replace('++','+') + stroka = stroka.replace('+-','-') + stroka = stroka.replace('-+','-') + stroka = stroka.replace('<+','<') + stroka = stroka.replace('>+','>') + stroka = stroka.replace('=<','<=') + stroka = stroka.replace('=>','>=') + stroka = stroka.replace('==+','+') + if stroka[0] == '+': stroka=stroka[1:] + #print('parse:',stroka) + + #разбор строки + for i,sym in enumerate(stroka + ' '): #добавлен дополнительный пробел + if sym in oper or i == len(stroka): + #print(i,slovo,sym) + if slovo == 'pi': + spisok.append(pi) + elif slovo == 'e': + spisok.append(e) + elif slovo in func: + spisok.append(slovo) + elif slovo.replace('.','').isdigit() and slovo.count('.')<2: + spisok.append(float(slovo)) + elif slovo != '': + print('ERROR: wrong symbol "',slovo,sym,'"') + exit(0) + spisok.append(sym) + slovo = '' + #print(sym) + + else: + slovo = slovo + sym + #print(i,sym,spisok) + spisok.pop() #удаляется добавленный пробел + + for i,data in enumerate(spisok): + if spisok[i] == '/' and spisok[i + 1] == '/': + spisok[i] = '//' + spisok.pop(i + 1) + if spisok[i] == '>' and spisok[i + 1] == '=': + spisok[i] = '>=' + spisok.pop(i + 1) + if spisok[i] == '<' and spisok[i + 1] == '=': + spisok[i] = '<=' + spisok.pop(i + 1) + if spisok[i] == '=' and spisok[i + 1] == '=' or spisok[i] =='=': + spisok[i] = '==' + spisok.pop(i + 1) + if spisok[i] == '!' and spisok[i + 1] == '=': + spisok[i] = '!=' + spisok.pop(i + 1) + if spisok[i] == '-' and spisok[i - 1] in ('^','//','/','*','%','-','+','==','<=','>=','<','>','!=','=') and type(spisok[i + 1]) == float: + spisok[i + 1] = spisok[i + 1]* - 1 + spisok.pop(i) + if (spisok[i] == '-' and i == 0) or(spisok[i] == '-' and spisok[i - 1] in('*','^','+','-','(','<','>','=') ): + spisok[i] = -1 + spisok.insert(i + 1,'*') + if spisok[i] == '-' and spisok[i - 1] == '/': + spisok[i - 1] = '*' + spisok[i] = -1 + spisok.insert(i + 1,'/') + #print(spisok) + return(spisok) + + +def operate(operator,a,b): + if operator == "+": + result = a + b + elif operator == "-": + result = a - b + elif operator == "*": + result = a * b + + elif operator == "//": + if b != 0: + result = a // b + else: + print('ERROR: division by zero') + exit(0) + elif operator == "/": + if b != 0: + result = a / b + else: + print('ERROR: division by zero') + exit(0) + elif operator == "%": + result = a % b + elif operator == "^": + result = a**b + elif operator == "<=": + result = a <= b + elif operator == ">=": + result = a >= b + elif operator == "<": + result = a < b + elif operator == ">": + result = a > b + elif operator == "==": + result = a == b + elif operator == "!=": + result = a != b + elif operator == "abs": + result = abs(a) + elif operator == "round": + result = round(a) + elif operator == "cos": + result = cos(a) + elif operator == "sin": + result = sin(a) + elif operator == "tan": + result = tan(a) + elif operator == "log": + result = log(a) + elif operator == "log10": + result = log10(a) + elif operator == "sqrt": + result = sqrt(a) + elif operator == "cos": + result = cos(a) + elif operator == "exp": + result = exp(a) + elif operator == "!": + result = factorial(a) + else: + print('ERROR: unknown math operator',operator) + result = 0 + if show == 'y': + if operator in oper: + print('Operate:',a,operator,b,'=',result) + elif operator in func: + print('Operate:',operator,a,'=',result) + return result + +#вычисление выражения без скобок +def calculate(spisok): + if show == 'y': print('Calculate:',spisok) + # перебор списка функций + for f in func: + for i in range(spisok.count(f)): + #print(f,spisok.count(f)) + s = spisok.index(f) + spisok[s] = (operate(f,spisok[s + 1],0)) + spisok[s + 1] = '' + wipe(spisok) + #print(*spisok,sep='') + + #вычисление возведение в степень с реверсом списка + #print('^ count:',spisok.count('^')) + if '^' in spisok: + spisok.reverse() + #print('reverse: ',spisok) + while '^' in spisok: + i = spisok.index('^') + #print('i = ',i) + spisok[i] = spisok[i + 1]**spisok[i - 1] + #print(spisok[i + 1],'^',spisok[i - 1],'=',spisok[i]) + spisok[i - 1] = '' + spisok[i + 1] = '' + #print(spisok) + wipe(spisok) + #print(spisok) + spisok.reverse() + + #перебор списка математических операций + for j in oper: + #print('operation = ',j) + #print(spisok) + i = 1 + while i < len(spisok): + if spisok[i] == j: + #print('calculate: ',*spisok,sep='') + spisok[i] = operate(spisok[i],spisok[i - 1],spisok[i + 1]) + spisok[i - 1] = '' + spisok[i + 1] = '' + #print(spisok) + wipe(spisok) + i = i - 1 + i = i + 1 + #print('Stop calculate:',float(spisok[0])) + wipe(spisok) + #print(spisok) + result = spisok[0] + if len(spisok) > 1: + print('ERROR: missed operator') + #exit(0) + return(result) + +#очистка списка от пустых значений '' +def wipe(spisok): + #print('WIPE:\n',spisok) + while '' in spisok: + i = spisok.index('') + spisok.pop(i) + #print('WIPED:\n',spisok) + return(spisok) + +#поиск начала и конца выражения в скобках() +def brktindx(spisok): + bl = spisok.index('(') + br = spisok.index(')') + s = spisok[bl + 1:br] + #print('BL BR ',bl + 1,' ',br,' ',*s,sep='') + while '(' in s: + if s.count('(') == s.count(')'): + bl = spisok.index('(',bl + 1) + br = spisok.index(')',bl + 1) + s = spisok[bl + 1:br] + #print('BL BR ',bl + 1,' ',br,' ', *s,sep='') + else: + br = spisok.index(')',br + 1) + s = spisok[bl:br + 1] + return(bl + 1,br) + + +# основная функция +def calc(xpr): + #проверка скобок в строке + if xpr.count('(') != xpr.count(')'): + print('ERROR: brackets are not balanced') + exit(0) + + #разбор строики в список + spisok = parse(xpr) + #print(*spisok,sep=',') + + + + + + #поиск скобок и вычисление в скобках + while '(' in spisok: + a,b = brktindx(spisok) + #print('in brackets: ',*spisok[a:b],sep='') + spisok[a - 1] = calculate(spisok[a:b]) + while a < b + 1: + spisok[a] = '' + a = a + 1 + wipe(spisok) + #print(*spisok,sep='') + + #вычисление без скобок + result = calculate(spisok) + #print(result) + return (result) + +print (calc(xpr)) + + + From 168af06ea30f7fb6b79ecd1042cafd9b08e1d29a Mon Sep 17 00:00:00 2001 From: novash-k Date: Tue, 16 Apr 2019 05:53:44 -0400 Subject: [PATCH 007/159] my commit --- README.md | 1 + pycalc-1.0.tar.gz | Bin 3994 -> 0 bytes pycalc.py | 721 +++++++++++++++++++++++----------------------- setup.py | 13 + 4 files changed, 375 insertions(+), 360 deletions(-) create mode 100644 README.md delete mode 100644 pycalc-1.0.tar.gz create mode 100644 setup.py diff --git a/README.md b/README.md new file mode 100644 index 00000000..e5e8d9ac --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# pycalc diff --git a/pycalc-1.0.tar.gz b/pycalc-1.0.tar.gz deleted file mode 100644 index 814a4f6608be1e47d296c427bd245e5ef8589793..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3994 zcmV;L4`uKliwFn~L$h20|72-%bT4puV_|G#Eio=IE_7jX0PP&@ZreuEe@h_mu#ORs zlt_uBzFNWbUD~>LMO(*k`f)(cGAL}i4_2YVXKzry5+`U5@G*|Z{?kh;I z&?mW>U6LXxQg+3%V>1gNNepHVCn~!N66ZVGl8c`U{CV#E^3bk5`F$gz+J5W-uCU+ z-`TE>hc9CN+s$V2`s;eM{+iL!Vg1`J%~&H^x&AL4HVD@MVXcJUBP8tKr@_>%4Gxd4 z-Ts^HjQ{UwZLPHb>wtUo=;*+n96I|#U>zOwr}k(_Ou`C7E1>YK38i!RJ=p*5TYpmD z+aS*tEw_ZQ8gX3wx1|;=~ zbKmlh)sy-z>jse@INphHdkRIbOWum7oa`{vutlX~%N}(Jr>~vZe>}np>{EE#9?*#o z{NCGnYv;}fJHqSKA9%JKun|O+yCC18?l>fInEwukm zyItD(T}FKM~A%q zK6ezR2-=j_K3tfhDPG2Z@J{Y93TwnWnR+8ryu35X>%wAQ#1xnO3nIVtQa<_tb2_G& z<8&BVmTJR2Js3N~>4^H~y__5%C{(SBKna+O<&1h=n`Oh``|IGRyz_!2+4i0{K zM7VJO7p=e6=@<>DH;hK3S^EE9cl~+sdE^7D*WYNiTao=YT1`X8_18L$a{aFZ!gz0a zN3P}hRABkQ*b0uLOu)4jstg=o@$HFX;e&-wFcpf0w~=#%m#!)PM_!=NhpuvH4Ip~k z)<_U6mzZ(qwcFm&bWA6~E|xqgkq-dYpx~y5l;ei$QC5hXA+1=Z|d-u&dI}nJ2 zQflIOYuBx%2vaZ*PnF9Zr2p z!eoMQL~@UR)@rqV0zKM1_lU7zlt6?Gy(1sj05W@=b>!?zvaqqigp{yYTg+glfz3ju zj`NiTm{`8HNqWIQb{<64j9Sswc{7 z6)LK{ia@%D9rD$+LEVGX1ZCBz7|EWhl2L6`47rlzsB0Cd)>ACC-g1>zZ}g08%`Jo1 z5%LBM7v=B?SPWPW_fv^+x^|T&$iZ4An&bfXEV*{wkkd%ICIP2h#EP!#m3E@VsN{8G z^?gZgC2KrqIvGm3(Wo_B?as@uB-(EKzB904M(@+)P>oxR$&RNIfo{q0aURHn;2=crl~k2gEy+IA04UL6OOc(86%sJkfsvRvXz~k z&;K<$n|(d|e)fp`fs09d%v^f3hb061Qkp0pj0rhFMU@Lkdn%RX>}=-HS1w7v?Rky| z!Oy1&HA{3~O}VOMfh4^JP1?R`rc4QhFr)@3TQjXR5~#eKL4;mOgEUEtv`N-cEO`o* zL878Xw&0_ks;R?YvZhToGdOJ!t&*yd5EkX1KmL#FJdg~~P6Y<>^T+>XK7afD+i#P1 zx9>vq*+4rr0XurcTg{{H$Qn>d?1_q4sfcoZD}mOcHU<7_VjLU^BqG4ID=LV_q7fzl z5|-pe2n9hPE}?G%=_PR;IzbWYb-bZ0aNUASg{uk|@{!>(p+9jGZ(HmMAK+TYf(cR# z?ISy2UFuL{z}0}O30DiQHe4OJUWV%xxU^7qjFgNBloP5zA>j_u1MX~H`6t{Vje&WVKqUKIS1bKl{Qk^2oBT=2;!@O*DyKwPaR^!W#5XOLgbRnGrC`(gHE_9I+Rq3sJmnf)|7gFD!)0LdC* zS&qbolDq6Ygh^$B6zu$jVgJPVJZ7Ce1)G0@-9LefC(!V8c23|C3bSum`_uUs^Un#0 z1tI{W^VwtGZ!~iLu%tFCaU%6uiKKEhxB#nKy%d(p)aoLR)yrUQR+$c7fVEX+T6zJN zxyd#ABD5{8`xl{^$;q$}Lxg+UJ~2TPt712-F~bJEyC0sbG5Zvm{(u#S8YJ+>LbYVg zhoI)R;-8L*Jt1@gnLVg}q=eu)K_TQW;oA2N(0#qoJ;Ew}g6juV#QCRC`NRB6RJqxA zgy|{bLnY%B4T`g3ZUlMb*hX}cR{IFTk%53{2PmeTYRCS#-Qw287Sq&hwwd+TEZ3!w zy}5Rpo{myI&teNS?EHInPJWLnRAq6mLGGR0r;>0G2~6-B5sEx z#|lE8g_5tMn_KQFRI2U0y*qnd^1yRo0}2b!cShu6`&-y7C&Q~OB z0XeFk5H4X~_?j|fV4QU~Wg4vRp3UvOF7ibWD>03U8oD|2%E$;tY-GTOXV&oCY?*EB;vvM@F{TlHAr3kzd^HzeEySmlp>$dZnUL;JqXj%WL)Ho2}#tXsJge5-IldU^PjN)h^|nHYA0 z!KPWrVXJ^-tC(c7fJrfr0v3e?W`R&HCsZw18}jn@7dZFAM2l z1D!{O2R(%}u=UQP!Q-Mr8rY)e(Li-E4Q%A|Xz+My6^*VHQ0dx=F@59(xr2iG=R14! zp_@ko)x|XHc@*(Ws|8)sL!`aKbaFCr9!&U)vZ!xSiJs);?zMP7%HD>s*C8q26-yZI z>vEkFf9HVPQ!8es^x0t(=OhcMy-Bju<&D)+r-|5kcY2v5J~Kg)h_6N1xG_)cH#T6~z>aL5#9Q;l zaS)mR9kw4&XW!5N0n&Z9*h(BOPY2s!V6|sWjv|@DUE-mfPGrK!f2d@!(#b=dpg{sL zqz?fhFYoX%?~tP8AnNm;&vH6Nlk-fAIa|S^Wrbz? zHgO)tE7>^+lz(D}abH4_u$5qkXwbp=?8o%+T=JNuN7%H*>ly9Hd!ig4-9Q1Cgd;4L zASCc8e&38ra&}uPhAmx^Ru(ox$M%R8bTq;sz5O=p&S<|$Vw%NX4PKWoATOfSR2jK-N11dkpX-|c=X04 z)b>Nyu*5G%zD3Fr5l3Dnv7C^b>O~=bZ2LYPE`obPeUiz4xYvt9B?QKE?mt0=Sqw_4 z`1$-(Jm~t2oggpXDWIw|xB4BB9)#3;M9-C#%8YpyFw`@`BK}jb*GIXD!Q(|z0CO|{9GnG?yziX^Am_vM z==-CkQApu1`rcBL9K9u2tUq)B+ScuR>C^sK-zKl_fl2aa1>fBCJ@!%YQ}!9ou*9c0 zec~9!E?|sqATEO#X^)UQija5Oa&iZii&;FztPd(4E6EHte}h~glXrnkU5>Gz)Spm< zzQ?|!gLd%=zIB7t0d?rBROUASDoz;L+tY3oO4xZZe`6O~TAX4=*-7}8=1FAxK%ZPJ z*fl0S(5=BCMPWP3aefio$)uBj~8wM^WlXd;+LA( z`%CtkxF~Z|M4UE3h+}GGf$1qYBL&%9#_)3VJL5tu1z*-?EpsX00%bH&i7h|}S z)GKO>0#kNBz^Jl$8#{eqI-Zx_SUJ(l3XjebaXl|s739aOa^jqQO?uaw-QXmbGiPVD z2qEFu31Wq3i+ye1|EYt8ce|G&!jzZdI2r1*}JP6nq3BYSe< z*Mf(^3;O=Qo>~8<(JKG{!?i&9)9&*3-v#y$o3VotY~)8*HvG%lzuw8%ztJgw|8t$| zAN}a3^aiE<$M%2s&U<^WZQuQ+)_<}68=ZF6{vls1?f*I;{-<9;^z(lqs|V5l1rb&# zh;W(YQCJyagyP?y3NP%ZiKYD)+y8U>e=yJd|6dH<=#=sQTA=*@FTd~q|58E;C6rJ? z2_=+JLJ1|5P(leMlu$wmC6rJ?2_=+JLJ1|5P(leMlu$wmCH!{b|2xWu#{hT$0Epo1 Ay8r+H diff --git a/pycalc.py b/pycalc.py index bf696c7e..8f0f00d0 100644 --- a/pycalc.py +++ b/pycalc.py @@ -1,360 +1,361 @@ -import argparse -from math import pi,e,cos,sin,acos,asin,tan,atan,log,log10,sqrt,exp,factorial - -ap = argparse.ArgumentParser(description = 'Pure-python command-line calculator.') -ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') -ap.add_argument('-p', '--PRINT', default='n', choices=['y', 'n'], type = str, help = 'print evaluation process') -ap.add_argument('-m', '--MODULE', type = str, help = 'use modules MODULE [MODULE...] additional modules to use') -args = ap.parse_args() -##print(args.EXPRESSION) -##print(args.PRINT) -##print(args.MODULE) -xpr = args.EXPRESSION -show = args.PRINT -#show = 'y' - -##xpr = modstr=args.MODULE -##xpr = -##xpr = mod = __import__(modstr) -##xpr = print (modstr,'=',mod.myfunc(3)) - - -## Unary operators -##xpr = "-13" -##xpr = "6-(-13)" -##xpr = "1---1" -##xpr = "-+---+-1" -## Operation priority -##xpr = "1+2*2" -##xpr = "1+(2+3*2)*3" -##xpr = "10*(2+1)" -##xpr = "10^(2+1)" -##xpr = "100/3^2" -##xpr = "100/3%2^2" -## Functions and constants -##xpr = "pi+e" -##xpr = "log(e)" -##xpr = "sin(pi/2)" -##xpr = "log10(100)" -##xpr = "sin(pi/2)*111*6" -##xpr = "2*sin(pi/2)" -##xpr = "abs(-5)" -##xpr = "round(123.456789)" -##xpr = Associative -##xpr = "102%12%7" -##xpr = "100/4/3" -##xpr = "2^3^4" -## Comparison operators -##xpr = "1+2*3==1+2*3" -##xpr = "e^5>=e^5+1" -##xpr = "1+2*4/3+1!=1+2*4/3+2" -## Common tests -##xpr = "(100)" -##xpr = "666" -##xpr = "-.1" -##xpr = "1/3" -##xpr = "1.0/3.0" -##xpr = ".1 * 2.0^56.0" -##xpr = "e^34" -##xpr = "(2.0^(pi/pi+e/e+2.0^0.0))" -##xpr = "(2.0^(pi/pi+e/e+2.0^0.0))^(1.0/3.0)" -##xpr = "sin(pi/2^1) + log(1*4+2^2+1, 3^2)" -##xpr = "10*e^0*log10(.4 -5/ -0.1-10) - -abs(-53/10) + -5" -##xpr = "sin(-cos(-sin(3.0)-cos(-sin(-3.0*5.0)-sin(cos(log10(43.0))))+cos(sin(sin(34.0-2.0^2.0))))--cos(1.0)--cos(0.0)^3.0)" -##xpr = "2.0^(2.0^2.0*2.0^2.0)" -## ошибка ? "sin(e^log(e^e^sin(23.0),45.0) + cos(3.0+log10(e^-e)))" -##xpr = "sin(e^log(e^e^sin(23.0)*45.0) + cos(3.0+log10(e^-e)))" -##xpr = Error cases -##xpr = "" -##xpr = "+" -##xpr = "1-" -##xpr = "1 2" -##xpr = "ee" -##xpr = "==7" -##xpr = "1 + 2(3 * 4))" -##xpr = "((1+2)" -##xpr = "1 + 1 2 3 4 5 6 " -##xpr = "log100(100)" -##xpr = "------" -##xpr = "5 > = 6" -##xpr = "5 / / 6" -##xpr = "6 < = 6" -##xpr = "6 * * 6" -##xpr = "(((((" -##xpr = “pow(2, 3, 4)” - -## EVAL TEST -##test=xpr -##test=test.replace('^','**') -##test=test.replace(' ','') -##test=test.replace(',','.') -##print ('EVAL:',test,'=',eval(test)) -##print(xpr) - -oper = ('!','^','//','/','*','%','-','+','(',')','==','<=','>=','<','>','!=','=') -digit = ('1','2','3','4','5','6','7','8','9','0','.') -func = ('sin','cos','tan','log10','log','exp','abs','round','sqrt') -stroka = '' -slovo = '' -operator = '' -spisok = [] -a = 0. -b = 0. -result = 0. - - -#разбор строки на элементы списка -def parse(stroka): - slovo='' - #исправление неверно введенных знаков - stroka = stroka.replace(' ','') - stroka = stroka.replace(',','.') - stroka = stroka.replace('--','+') - stroka = stroka.replace('++','+') - stroka = stroka.replace('+-','-') - stroka = stroka.replace('-+','-') - stroka = stroka.replace('<+','<') - stroka = stroka.replace('>+','>') - stroka = stroka.replace('=<','<=') - stroka = stroka.replace('=>','>=') - stroka = stroka.replace('==+','+') - if stroka[0] == '+': stroka=stroka[1:] - #print('parse:',stroka) - - #разбор строки - for i,sym in enumerate(stroka + ' '): #добавлен дополнительный пробел - if sym in oper or i == len(stroka): - #print(i,slovo,sym) - if slovo == 'pi': - spisok.append(pi) - elif slovo == 'e': - spisok.append(e) - elif slovo in func: - spisok.append(slovo) - elif slovo.replace('.','').isdigit() and slovo.count('.')<2: - spisok.append(float(slovo)) - elif slovo != '': - print('ERROR: wrong symbol "',slovo,sym,'"') - exit(0) - spisok.append(sym) - slovo = '' - #print(sym) - - else: - slovo = slovo + sym - #print(i,sym,spisok) - spisok.pop() #удаляется добавленный пробел - - for i,data in enumerate(spisok): - if spisok[i] == '/' and spisok[i + 1] == '/': - spisok[i] = '//' - spisok.pop(i + 1) - if spisok[i] == '>' and spisok[i + 1] == '=': - spisok[i] = '>=' - spisok.pop(i + 1) - if spisok[i] == '<' and spisok[i + 1] == '=': - spisok[i] = '<=' - spisok.pop(i + 1) - if spisok[i] == '=' and spisok[i + 1] == '=' or spisok[i] =='=': - spisok[i] = '==' - spisok.pop(i + 1) - if spisok[i] == '!' and spisok[i + 1] == '=': - spisok[i] = '!=' - spisok.pop(i + 1) - if spisok[i] == '-' and spisok[i - 1] in ('^','//','/','*','%','-','+','==','<=','>=','<','>','!=','=') and type(spisok[i + 1]) == float: - spisok[i + 1] = spisok[i + 1]* - 1 - spisok.pop(i) - if (spisok[i] == '-' and i == 0) or(spisok[i] == '-' and spisok[i - 1] in('*','^','+','-','(','<','>','=') ): - spisok[i] = -1 - spisok.insert(i + 1,'*') - if spisok[i] == '-' and spisok[i - 1] == '/': - spisok[i - 1] = '*' - spisok[i] = -1 - spisok.insert(i + 1,'/') - #print(spisok) - return(spisok) - - -def operate(operator,a,b): - if operator == "+": - result = a + b - elif operator == "-": - result = a - b - elif operator == "*": - result = a * b - - elif operator == "//": - if b != 0: - result = a // b - else: - print('ERROR: division by zero') - exit(0) - elif operator == "/": - if b != 0: - result = a / b - else: - print('ERROR: division by zero') - exit(0) - elif operator == "%": - result = a % b - elif operator == "^": - result = a**b - elif operator == "<=": - result = a <= b - elif operator == ">=": - result = a >= b - elif operator == "<": - result = a < b - elif operator == ">": - result = a > b - elif operator == "==": - result = a == b - elif operator == "!=": - result = a != b - elif operator == "abs": - result = abs(a) - elif operator == "round": - result = round(a) - elif operator == "cos": - result = cos(a) - elif operator == "sin": - result = sin(a) - elif operator == "tan": - result = tan(a) - elif operator == "log": - result = log(a) - elif operator == "log10": - result = log10(a) - elif operator == "sqrt": - result = sqrt(a) - elif operator == "cos": - result = cos(a) - elif operator == "exp": - result = exp(a) - elif operator == "!": - result = factorial(a) - else: - print('ERROR: unknown math operator',operator) - result = 0 - if show == 'y': - if operator in oper: - print('Operate:',a,operator,b,'=',result) - elif operator in func: - print('Operate:',operator,a,'=',result) - return result - -#вычисление выражения без скобок -def calculate(spisok): - if show == 'y': print('Calculate:',spisok) - # перебор списка функций - for f in func: - for i in range(spisok.count(f)): - #print(f,spisok.count(f)) - s = spisok.index(f) - spisok[s] = (operate(f,spisok[s + 1],0)) - spisok[s + 1] = '' - wipe(spisok) - #print(*spisok,sep='') - - #вычисление возведение в степень с реверсом списка - #print('^ count:',spisok.count('^')) - if '^' in spisok: - spisok.reverse() - #print('reverse: ',spisok) - while '^' in spisok: - i = spisok.index('^') - #print('i = ',i) - spisok[i] = spisok[i + 1]**spisok[i - 1] - #print(spisok[i + 1],'^',spisok[i - 1],'=',spisok[i]) - spisok[i - 1] = '' - spisok[i + 1] = '' - #print(spisok) - wipe(spisok) - #print(spisok) - spisok.reverse() - - #перебор списка математических операций - for j in oper: - #print('operation = ',j) - #print(spisok) - i = 1 - while i < len(spisok): - if spisok[i] == j: - #print('calculate: ',*spisok,sep='') - spisok[i] = operate(spisok[i],spisok[i - 1],spisok[i + 1]) - spisok[i - 1] = '' - spisok[i + 1] = '' - #print(spisok) - wipe(spisok) - i = i - 1 - i = i + 1 - #print('Stop calculate:',float(spisok[0])) - wipe(spisok) - #print(spisok) - result = spisok[0] - if len(spisok) > 1: - print('ERROR: missed operator') - #exit(0) - return(result) - -#очистка списка от пустых значений '' -def wipe(spisok): - #print('WIPE:\n',spisok) - while '' in spisok: - i = spisok.index('') - spisok.pop(i) - #print('WIPED:\n',spisok) - return(spisok) - -#поиск начала и конца выражения в скобках() -def brktindx(spisok): - bl = spisok.index('(') - br = spisok.index(')') - s = spisok[bl + 1:br] - #print('BL BR ',bl + 1,' ',br,' ',*s,sep='') - while '(' in s: - if s.count('(') == s.count(')'): - bl = spisok.index('(',bl + 1) - br = spisok.index(')',bl + 1) - s = spisok[bl + 1:br] - #print('BL BR ',bl + 1,' ',br,' ', *s,sep='') - else: - br = spisok.index(')',br + 1) - s = spisok[bl:br + 1] - return(bl + 1,br) - - -# основная функция -def calc(xpr): - #проверка скобок в строке - if xpr.count('(') != xpr.count(')'): - print('ERROR: brackets are not balanced') - exit(0) - - #разбор строики в список - spisok = parse(xpr) - #print(*spisok,sep=',') - - - - - - #поиск скобок и вычисление в скобках - while '(' in spisok: - a,b = brktindx(spisok) - #print('in brackets: ',*spisok[a:b],sep='') - spisok[a - 1] = calculate(spisok[a:b]) - while a < b + 1: - spisok[a] = '' - a = a + 1 - wipe(spisok) - #print(*spisok,sep='') - - #вычисление без скобок - result = calculate(spisok) - #print(result) - return (result) - -print (calc(xpr)) - - +#16.04.2019 12:00 +import argparse +from math import pi,e,cos,sin,acos,asin,tan,atan,log,log10,sqrt,exp,factorial + +ap = argparse.ArgumentParser(description = 'Pure-python command-line calculator.') +ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') +ap.add_argument('-p', '--PRINT', default='n', choices=['y', 'n'], type = str, help = 'print evaluation process') +ap.add_argument('-m', '--MODULE', type = str, help = 'use modules MODULE [MODULE...] additional modules to use') +args = ap.parse_args() +##print(args.EXPRESSION) +##print(args.PRINT) +##print(args.MODULE) +xpr = args.EXPRESSION +show = args.PRINT +#show = 'y' + +##xpr = modstr=args.MODULE +##xpr = +##xpr = mod = __import__(modstr) +##xpr = print (modstr,'=',mod.myfunc(3)) + + +## Unary operators +##xpr = "-13" +##xpr = "6-(-13)" +##xpr = "1---1" +##xpr = "-+---+-1" +## Operation priority +##xpr = "1+2*2" +##xpr = "1+(2+3*2)*3" +##xpr = "10*(2+1)" +##xpr = "10^(2+1)" +##xpr = "100/3^2" +##xpr = "100/3%2^2" +## Functions and constants +##xpr = "pi+e" +##xpr = "log(e)" +##xpr = "sin(pi/2)" +##xpr = "log10(100)" +##xpr = "sin(pi/2)*111*6" +##xpr = "2*sin(pi/2)" +##xpr = "abs(-5)" +##xpr = "round(123.456789)" +##xpr = Associative +##xpr = "102%12%7" +##xpr = "100/4/3" +##xpr = "2^3^4" +## Comparison operators +##xpr = "1+2*3==1+2*3" +##xpr = "e^5>=e^5+1" +##xpr = "1+2*4/3+1!=1+2*4/3+2" +## Common tests +##xpr = "(100)" +##xpr = "666" +##xpr = "-.1" +##xpr = "1/3" +##xpr = "1.0/3.0" +##xpr = ".1 * 2.0^56.0" +##xpr = "e^34" +##xpr = "(2.0^(pi/pi+e/e+2.0^0.0))" +##xpr = "(2.0^(pi/pi+e/e+2.0^0.0))^(1.0/3.0)" +##xpr = "sin(pi/2^1) + log(1*4+2^2+1, 3^2)" +##xpr = "10*e^0*log10(.4 -5/ -0.1-10) - -abs(-53/10) + -5" +##xpr = "sin(-cos(-sin(3.0)-cos(-sin(-3.0*5.0)-sin(cos(log10(43.0))))+cos(sin(sin(34.0-2.0^2.0))))--cos(1.0)--cos(0.0)^3.0)" +##xpr = "2.0^(2.0^2.0*2.0^2.0)" +## ошибка ? "sin(e^log(e^e^sin(23.0),45.0) + cos(3.0+log10(e^-e)))" +##xpr = "sin(e^log(e^e^sin(23.0)*45.0) + cos(3.0+log10(e^-e)))" +##xpr = Error cases +##xpr = "" +##xpr = "+" +##xpr = "1-" +##xpr = "1 2" +##xpr = "ee" +##xpr = "==7" +##xpr = "1 + 2(3 * 4))" +##xpr = "((1+2)" +##xpr = "1 + 1 2 3 4 5 6 " +##xpr = "log100(100)" +##xpr = "------" +##xpr = "5 > = 6" +##xpr = "5 / / 6" +##xpr = "6 < = 6" +##xpr = "6 * * 6" +##xpr = "(((((" +##xpr = “pow(2, 3, 4)” + +## EVAL TEST +##test=xpr +##test=test.replace('^','**') +##test=test.replace(' ','') +##test=test.replace(',','.') +##print ('EVAL:',test,'=',eval(test)) +##print(xpr) + +oper = ('!','^','//','/','*','%','-','+','(',')','==','<=','>=','<','>','!=','=') +digit = ('1','2','3','4','5','6','7','8','9','0','.') +func = ('sin','cos','tan','log10','log','exp','abs','round','sqrt') +stroka = '' +slovo = '' +operator = '' +spisok = [] +a = 0. +b = 0. +result = 0. + + +#разбор строки на элементы списка +def parse(stroka): + slovo='' + #исправление неверно введенных знаков + stroka = stroka.replace(' ','') + stroka = stroka.replace(',','.') + stroka = stroka.replace('--','+') + stroka = stroka.replace('++','+') + stroka = stroka.replace('+-','-') + stroka = stroka.replace('-+','-') + stroka = stroka.replace('<+','<') + stroka = stroka.replace('>+','>') + stroka = stroka.replace('=<','<=') + stroka = stroka.replace('=>','>=') + stroka = stroka.replace('==+','+') + if stroka[0] == '+': stroka=stroka[1:] + #print('parse:',stroka) + + #разбор строки + for i,sym in enumerate(stroka + ' '): #добавлен дополнительный пробел + if sym in oper or i == len(stroka): + #print(i,slovo,sym) + if slovo == 'pi': + spisok.append(pi) + elif slovo == 'e': + spisok.append(e) + elif slovo in func: + spisok.append(slovo) + elif slovo.replace('.','').isdigit() and slovo.count('.')<2: + spisok.append(float(slovo)) + elif slovo != '': + print('ERROR: wrong symbol "',slovo,sym,'"') + exit(0) + spisok.append(sym) + slovo = '' + #print(sym) + + else: + slovo = slovo + sym + #print(i,sym,spisok) + spisok.pop() #удаляется добавленный пробел + + for i,data in enumerate(spisok): + if spisok[i] == '/' and spisok[i + 1] == '/': + spisok[i] = '//' + spisok.pop(i + 1) + if spisok[i] == '>' and spisok[i + 1] == '=': + spisok[i] = '>=' + spisok.pop(i + 1) + if spisok[i] == '<' and spisok[i + 1] == '=': + spisok[i] = '<=' + spisok.pop(i + 1) + if spisok[i] == '=' and spisok[i + 1] == '=' or spisok[i] =='=': + spisok[i] = '==' + spisok.pop(i + 1) + if spisok[i] == '!' and spisok[i + 1] == '=': + spisok[i] = '!=' + spisok.pop(i + 1) + if spisok[i] == '-' and spisok[i - 1] in ('^','//','/','*','%','-','+','==','<=','>=','<','>','!=','=') and type(spisok[i + 1]) == float: + spisok[i + 1] = spisok[i + 1]* - 1 + spisok.pop(i) + if (spisok[i] == '-' and i == 0) or(spisok[i] == '-' and spisok[i - 1] in('*','^','+','-','(','<','>','=') ): + spisok[i] = -1 + spisok.insert(i + 1,'*') + if spisok[i] == '-' and spisok[i - 1] == '/': + spisok[i - 1] = '*' + spisok[i] = -1 + spisok.insert(i + 1,'/') + #print(spisok) + return(spisok) + + +def operate(operator,a,b): + if operator == "+": + result = a + b + elif operator == "-": + result = a - b + elif operator == "*": + result = a * b + + elif operator == "//": + if b != 0: + result = a // b + else: + print('ERROR: division by zero') + exit(0) + elif operator == "/": + if b != 0: + result = a / b + else: + print('ERROR: division by zero') + exit(0) + elif operator == "%": + result = a % b + elif operator == "^": + result = a**b + elif operator == "<=": + result = a <= b + elif operator == ">=": + result = a >= b + elif operator == "<": + result = a < b + elif operator == ">": + result = a > b + elif operator == "==": + result = a == b + elif operator == "!=": + result = a != b + elif operator == "abs": + result = abs(a) + elif operator == "round": + result = round(a) + elif operator == "cos": + result = cos(a) + elif operator == "sin": + result = sin(a) + elif operator == "tan": + result = tan(a) + elif operator == "log": + result = log(a) + elif operator == "log10": + result = log10(a) + elif operator == "sqrt": + result = sqrt(a) + elif operator == "cos": + result = cos(a) + elif operator == "exp": + result = exp(a) + elif operator == "!": + result = factorial(a) + else: + print('ERROR: unknown math operator',operator) + result = 0 + if show == 'y': + if operator in oper: + print('Operate:',a,operator,b,'=',result) + elif operator in func: + print('Operate:',operator,a,'=',result) + return result + +#вычисление выражения без скобок +def calculate(spisok): + if show == 'y': print('Calculate:',spisok) + # перебор списка функций + for f in func: + for i in range(spisok.count(f)): + #print(f,spisok.count(f)) + s = spisok.index(f) + spisok[s] = (operate(f,spisok[s + 1],0)) + spisok[s + 1] = '' + wipe(spisok) + #print(*spisok,sep='') + + #вычисление возведение в степень с реверсом списка + #print('^ count:',spisok.count('^')) + if '^' in spisok: + spisok.reverse() + #print('reverse: ',spisok) + while '^' in spisok: + i = spisok.index('^') + #print('i = ',i) + spisok[i] = spisok[i + 1]**spisok[i - 1] + #print(spisok[i + 1],'^',spisok[i - 1],'=',spisok[i]) + spisok[i - 1] = '' + spisok[i + 1] = '' + #print(spisok) + wipe(spisok) + #print(spisok) + spisok.reverse() + + #перебор списка математических операций + for j in oper: + #print('operation = ',j) + #print(spisok) + i = 1 + while i < len(spisok): + if spisok[i] == j: + #print('calculate: ',*spisok,sep='') + spisok[i] = operate(spisok[i],spisok[i - 1],spisok[i + 1]) + spisok[i - 1] = '' + spisok[i + 1] = '' + #print(spisok) + wipe(spisok) + i = i - 1 + i = i + 1 + #print('Stop calculate:',float(spisok[0])) + wipe(spisok) + #print(spisok) + result = spisok[0] + if len(spisok) > 1: + print('ERROR: missed operator') + #exit(0) + return(result) + +#очистка списка от пустых значений '' +def wipe(spisok): + #print('WIPE:\n',spisok) + while '' in spisok: + i = spisok.index('') + spisok.pop(i) + #print('WIPED:\n',spisok) + return(spisok) + +#поиск начала и конца выражения в скобках() +def brktindx(spisok): + bl = spisok.index('(') + br = spisok.index(')') + s = spisok[bl + 1:br] + #print('BL BR ',bl + 1,' ',br,' ',*s,sep='') + while '(' in s: + if s.count('(') == s.count(')'): + bl = spisok.index('(',bl + 1) + br = spisok.index(')',bl + 1) + s = spisok[bl + 1:br] + #print('BL BR ',bl + 1,' ',br,' ', *s,sep='') + else: + br = spisok.index(')',br + 1) + s = spisok[bl:br + 1] + return(bl + 1,br) + + +# основная функция +def calc(xpr): + #проверка скобок в строке + if xpr.count('(') != xpr.count(')'): + print('ERROR: brackets are not balanced') + exit(0) + + #разбор строики в список + spisok = parse(xpr) + #print(*spisok,sep=',') + + + + + + #поиск скобок и вычисление в скобках + while '(' in spisok: + a,b = brktindx(spisok) + #print('in brackets: ',*spisok[a:b],sep='') + spisok[a - 1] = calculate(spisok[a:b]) + while a < b + 1: + spisok[a] = '' + a = a + 1 + wipe(spisok) + #print(*spisok,sep='') + + #вычисление без скобок + result = calculate(spisok) + #print(result) + return (result) + +print (calc(xpr)) + + diff --git a/setup.py b/setup.py new file mode 100644 index 00000000..09bb96d8 --- /dev/null +++ b/setup.py @@ -0,0 +1,13 @@ +from setuptools import setup + +setup( + name='pycalc', # Required + version='1.0', # Required + description='Pure-python command-line calculator.', # Optional + url='https://github.com/novash-k/PythonHomework', # Optional + author='Konstantin Novash', # Optional + author_email='novash.ki@gmail.com', # Optional + py_modules=["pycalc"] # Required + #packages=['pycalc_project'] # Required + #python_requires='>3.0, <3.7' + ) From 018205857767988014ac4a66fd32f59e88f69698 Mon Sep 17 00:00:00 2001 From: novash-k Date: Tue, 16 Apr 2019 06:26:03 -0400 Subject: [PATCH 008/159] branch novash --- pycalc.py | 1 + 1 file changed, 1 insertion(+) diff --git a/pycalc.py b/pycalc.py index 8f0f00d0..56731eba 100644 --- a/pycalc.py +++ b/pycalc.py @@ -1,4 +1,5 @@ #16.04.2019 12:00 +# to master import argparse from math import pi,e,cos,sin,acos,asin,tan,atan,log,log10,sqrt,exp,factorial From 314a53e0dc89ff3fbf0f8fc96d60475787164a42 Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 17 Apr 2019 04:58:24 -0400 Subject: [PATCH 009/159] branch novash setup main --- pycalc.py | 6 ++++-- setup.py | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/pycalc.py b/pycalc.py index 56731eba..d742d49a 100644 --- a/pycalc.py +++ b/pycalc.py @@ -1,5 +1,7 @@ #16.04.2019 12:00 # to master +#main + import argparse from math import pi,e,cos,sin,acos,asin,tan,atan,log,log10,sqrt,exp,factorial @@ -327,7 +329,7 @@ def brktindx(spisok): # основная функция -def calc(xpr): +def main(xpr): #проверка скобок в строке if xpr.count('(') != xpr.count(')'): print('ERROR: brackets are not balanced') @@ -357,6 +359,6 @@ def calc(xpr): #print(result) return (result) -print (calc(xpr)) +print (main(xpr)) diff --git a/setup.py b/setup.py index 09bb96d8..e397f400 100644 --- a/setup.py +++ b/setup.py @@ -8,6 +8,7 @@ author='Konstantin Novash', # Optional author_email='novash.ki@gmail.com', # Optional py_modules=["pycalc"] # Required + entry-points={'pycalc': ['pycalc=pycalc:main']} #packages=['pycalc_project'] # Required #python_requires='>3.0, <3.7' ) From 7a77aa6762aa57a7a0d6098b844e47851a3792f6 Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 17 Apr 2019 09:30:52 -0400 Subject: [PATCH 010/159] branch novash setup main --- setup.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index e397f400..abacd055 100644 --- a/setup.py +++ b/setup.py @@ -7,8 +7,8 @@ url='https://github.com/novash-k/PythonHomework', # Optional author='Konstantin Novash', # Optional author_email='novash.ki@gmail.com', # Optional - py_modules=["pycalc"] # Required - entry-points={'pycalc': ['pycalc=pycalc:main']} + py_modules=["pycalc"], # Required + entry_points = {'console_scripts': ['pycalc=pycalc:main',],}, #packages=['pycalc_project'] # Required #python_requires='>3.0, <3.7' ) From 4dcb475b0e320aecbbecde7b3ca438aa3d44fc6a Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 17 Apr 2019 09:36:41 -0400 Subject: [PATCH 011/159] branch novash setup main --- final_task/pycalc-1.0.tar.gz | Bin 3994 -> 0 bytes final_task/pycalc.py | 9 ++++++--- final_task/setup.py | 14 ++++++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) delete mode 100644 final_task/pycalc-1.0.tar.gz diff --git a/final_task/pycalc-1.0.tar.gz b/final_task/pycalc-1.0.tar.gz deleted file mode 100644 index 814a4f6608be1e47d296c427bd245e5ef8589793..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3994 zcmV;L4`uKliwFn~L$h20|72-%bT4puV_|G#Eio=IE_7jX0PP&@ZreuEe@h_mu#ORs zlt_uBzFNWbUD~>LMO(*k`f)(cGAL}i4_2YVXKzry5+`U5@G*|Z{?kh;I z&?mW>U6LXxQg+3%V>1gNNepHVCn~!N66ZVGl8c`U{CV#E^3bk5`F$gz+J5W-uCU+ z-`TE>hc9CN+s$V2`s;eM{+iL!Vg1`J%~&H^x&AL4HVD@MVXcJUBP8tKr@_>%4Gxd4 z-Ts^HjQ{UwZLPHb>wtUo=;*+n96I|#U>zOwr}k(_Ou`C7E1>YK38i!RJ=p*5TYpmD z+aS*tEw_ZQ8gX3wx1|;=~ zbKmlh)sy-z>jse@INphHdkRIbOWum7oa`{vutlX~%N}(Jr>~vZe>}np>{EE#9?*#o z{NCGnYv;}fJHqSKA9%JKun|O+yCC18?l>fInEwukm zyItD(T}FKM~A%q zK6ezR2-=j_K3tfhDPG2Z@J{Y93TwnWnR+8ryu35X>%wAQ#1xnO3nIVtQa<_tb2_G& z<8&BVmTJR2Js3N~>4^H~y__5%C{(SBKna+O<&1h=n`Oh``|IGRyz_!2+4i0{K zM7VJO7p=e6=@<>DH;hK3S^EE9cl~+sdE^7D*WYNiTao=YT1`X8_18L$a{aFZ!gz0a zN3P}hRABkQ*b0uLOu)4jstg=o@$HFX;e&-wFcpf0w~=#%m#!)PM_!=NhpuvH4Ip~k z)<_U6mzZ(qwcFm&bWA6~E|xqgkq-dYpx~y5l;ei$QC5hXA+1=Z|d-u&dI}nJ2 zQflIOYuBx%2vaZ*PnF9Zr2p z!eoMQL~@UR)@rqV0zKM1_lU7zlt6?Gy(1sj05W@=b>!?zvaqqigp{yYTg+glfz3ju zj`NiTm{`8HNqWIQb{<64j9Sswc{7 z6)LK{ia@%D9rD$+LEVGX1ZCBz7|EWhl2L6`47rlzsB0Cd)>ACC-g1>zZ}g08%`Jo1 z5%LBM7v=B?SPWPW_fv^+x^|T&$iZ4An&bfXEV*{wkkd%ICIP2h#EP!#m3E@VsN{8G z^?gZgC2KrqIvGm3(Wo_B?as@uB-(EKzB904M(@+)P>oxR$&RNIfo{q0aURHn;2=crl~k2gEy+IA04UL6OOc(86%sJkfsvRvXz~k z&;K<$n|(d|e)fp`fs09d%v^f3hb061Qkp0pj0rhFMU@Lkdn%RX>}=-HS1w7v?Rky| z!Oy1&HA{3~O}VOMfh4^JP1?R`rc4QhFr)@3TQjXR5~#eKL4;mOgEUEtv`N-cEO`o* zL878Xw&0_ks;R?YvZhToGdOJ!t&*yd5EkX1KmL#FJdg~~P6Y<>^T+>XK7afD+i#P1 zx9>vq*+4rr0XurcTg{{H$Qn>d?1_q4sfcoZD}mOcHU<7_VjLU^BqG4ID=LV_q7fzl z5|-pe2n9hPE}?G%=_PR;IzbWYb-bZ0aNUASg{uk|@{!>(p+9jGZ(HmMAK+TYf(cR# z?ISy2UFuL{z}0}O30DiQHe4OJUWV%xxU^7qjFgNBloP5zA>j_u1MX~H`6t{Vje&WVKqUKIS1bKl{Qk^2oBT=2;!@O*DyKwPaR^!W#5XOLgbRnGrC`(gHE_9I+Rq3sJmnf)|7gFD!)0LdC* zS&qbolDq6Ygh^$B6zu$jVgJPVJZ7Ce1)G0@-9LefC(!V8c23|C3bSum`_uUs^Un#0 z1tI{W^VwtGZ!~iLu%tFCaU%6uiKKEhxB#nKy%d(p)aoLR)yrUQR+$c7fVEX+T6zJN zxyd#ABD5{8`xl{^$;q$}Lxg+UJ~2TPt712-F~bJEyC0sbG5Zvm{(u#S8YJ+>LbYVg zhoI)R;-8L*Jt1@gnLVg}q=eu)K_TQW;oA2N(0#qoJ;Ew}g6juV#QCRC`NRB6RJqxA zgy|{bLnY%B4T`g3ZUlMb*hX}cR{IFTk%53{2PmeTYRCS#-Qw287Sq&hwwd+TEZ3!w zy}5Rpo{myI&teNS?EHInPJWLnRAq6mLGGR0r;>0G2~6-B5sEx z#|lE8g_5tMn_KQFRI2U0y*qnd^1yRo0}2b!cShu6`&-y7C&Q~OB z0XeFk5H4X~_?j|fV4QU~Wg4vRp3UvOF7ibWD>03U8oD|2%E$;tY-GTOXV&oCY?*EB;vvM@F{TlHAr3kzd^HzeEySmlp>$dZnUL;JqXj%WL)Ho2}#tXsJge5-IldU^PjN)h^|nHYA0 z!KPWrVXJ^-tC(c7fJrfr0v3e?W`R&HCsZw18}jn@7dZFAM2l z1D!{O2R(%}u=UQP!Q-Mr8rY)e(Li-E4Q%A|Xz+My6^*VHQ0dx=F@59(xr2iG=R14! zp_@ko)x|XHc@*(Ws|8)sL!`aKbaFCr9!&U)vZ!xSiJs);?zMP7%HD>s*C8q26-yZI z>vEkFf9HVPQ!8es^x0t(=OhcMy-Bju<&D)+r-|5kcY2v5J~Kg)h_6N1xG_)cH#T6~z>aL5#9Q;l zaS)mR9kw4&XW!5N0n&Z9*h(BOPY2s!V6|sWjv|@DUE-mfPGrK!f2d@!(#b=dpg{sL zqz?fhFYoX%?~tP8AnNm;&vH6Nlk-fAIa|S^Wrbz? zHgO)tE7>^+lz(D}abH4_u$5qkXwbp=?8o%+T=JNuN7%H*>ly9Hd!ig4-9Q1Cgd;4L zASCc8e&38ra&}uPhAmx^Ru(ox$M%R8bTq;sz5O=p&S<|$Vw%NX4PKWoATOfSR2jK-N11dkpX-|c=X04 z)b>Nyu*5G%zD3Fr5l3Dnv7C^b>O~=bZ2LYPE`obPeUiz4xYvt9B?QKE?mt0=Sqw_4 z`1$-(Jm~t2oggpXDWIw|xB4BB9)#3;M9-C#%8YpyFw`@`BK}jb*GIXD!Q(|z0CO|{9GnG?yziX^Am_vM z==-CkQApu1`rcBL9K9u2tUq)B+ScuR>C^sK-zKl_fl2aa1>fBCJ@!%YQ}!9ou*9c0 zec~9!E?|sqATEO#X^)UQija5Oa&iZii&;FztPd(4E6EHte}h~glXrnkU5>Gz)Spm< zzQ?|!gLd%=zIB7t0d?rBROUASDoz;L+tY3oO4xZZe`6O~TAX4=*-7}8=1FAxK%ZPJ z*fl0S(5=BCMPWP3aefio$)uBj~8wM^WlXd;+LA( z`%CtkxF~Z|M4UE3h+}GGf$1qYBL&%9#_)3VJL5tu1z*-?EpsX00%bH&i7h|}S z)GKO>0#kNBz^Jl$8#{eqI-Zx_SUJ(l3XjebaXl|s739aOa^jqQO?uaw-QXmbGiPVD z2qEFu31Wq3i+ye1|EYt8ce|G&!jzZdI2r1*}JP6nq3BYSe< z*Mf(^3;O=Qo>~8<(JKG{!?i&9)9&*3-v#y$o3VotY~)8*HvG%lzuw8%ztJgw|8t$| zAN}a3^aiE<$M%2s&U<^WZQuQ+)_<}68=ZF6{vls1?f*I;{-<9;^z(lqs|V5l1rb&# zh;W(YQCJyagyP?y3NP%ZiKYD)+y8U>e=yJd|6dH<=#=sQTA=*@FTd~q|58E;C6rJ? z2_=+JLJ1|5P(leMlu$wmC6rJ?2_=+JLJ1|5P(leMlu$wmCH!{b|2xWu#{hT$0Epo1 Ay8r+H diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 2a0d4ce2..d742d49a 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,3 +1,7 @@ +#16.04.2019 12:00 +# to master +#main + import argparse from math import pi,e,cos,sin,acos,asin,tan,atan,log,log10,sqrt,exp,factorial @@ -325,7 +329,7 @@ def brktindx(spisok): # основная функция -def calc(xpr): +def main(xpr): #проверка скобок в строке if xpr.count('(') != xpr.count(')'): print('ERROR: brackets are not balanced') @@ -355,7 +359,6 @@ def calc(xpr): #print(result) return (result) -print (calc(xpr)) - +print (main(xpr)) diff --git a/final_task/setup.py b/final_task/setup.py index e69de29b..abacd055 100644 --- a/final_task/setup.py +++ b/final_task/setup.py @@ -0,0 +1,14 @@ +from setuptools import setup + +setup( + name='pycalc', # Required + version='1.0', # Required + description='Pure-python command-line calculator.', # Optional + url='https://github.com/novash-k/PythonHomework', # Optional + author='Konstantin Novash', # Optional + author_email='novash.ki@gmail.com', # Optional + py_modules=["pycalc"], # Required + entry_points = {'console_scripts': ['pycalc=pycalc:main',],}, + #packages=['pycalc_project'] # Required + #python_requires='>3.0, <3.7' + ) From ac3813bbf2d0b64d5080330838607cc76e82288f Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 17 Apr 2019 19:13:46 -0400 Subject: [PATCH 012/159] new func --- final_task/pycalc.py | 364 +++++++++++++++++-------------------------- pycalc.py | 364 ------------------------------------------- setup.py | 14 -- 3 files changed, 144 insertions(+), 598 deletions(-) delete mode 100644 pycalc.py delete mode 100644 setup.py diff --git a/final_task/pycalc.py b/final_task/pycalc.py index d742d49a..eb91e988 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,9 +1,8 @@ -#16.04.2019 12:00 -# to master -#main +#18.04.2019 00:20 import argparse -from math import pi,e,cos,sin,acos,asin,tan,atan,log,log10,sqrt,exp,factorial +import math +from math import * ap = argparse.ArgumentParser(description = 'Pure-python command-line calculator.') ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') @@ -23,70 +22,6 @@ ##xpr = print (modstr,'=',mod.myfunc(3)) -## Unary operators -##xpr = "-13" -##xpr = "6-(-13)" -##xpr = "1---1" -##xpr = "-+---+-1" -## Operation priority -##xpr = "1+2*2" -##xpr = "1+(2+3*2)*3" -##xpr = "10*(2+1)" -##xpr = "10^(2+1)" -##xpr = "100/3^2" -##xpr = "100/3%2^2" -## Functions and constants -##xpr = "pi+e" -##xpr = "log(e)" -##xpr = "sin(pi/2)" -##xpr = "log10(100)" -##xpr = "sin(pi/2)*111*6" -##xpr = "2*sin(pi/2)" -##xpr = "abs(-5)" -##xpr = "round(123.456789)" -##xpr = Associative -##xpr = "102%12%7" -##xpr = "100/4/3" -##xpr = "2^3^4" -## Comparison operators -##xpr = "1+2*3==1+2*3" -##xpr = "e^5>=e^5+1" -##xpr = "1+2*4/3+1!=1+2*4/3+2" -## Common tests -##xpr = "(100)" -##xpr = "666" -##xpr = "-.1" -##xpr = "1/3" -##xpr = "1.0/3.0" -##xpr = ".1 * 2.0^56.0" -##xpr = "e^34" -##xpr = "(2.0^(pi/pi+e/e+2.0^0.0))" -##xpr = "(2.0^(pi/pi+e/e+2.0^0.0))^(1.0/3.0)" -##xpr = "sin(pi/2^1) + log(1*4+2^2+1, 3^2)" -##xpr = "10*e^0*log10(.4 -5/ -0.1-10) - -abs(-53/10) + -5" -##xpr = "sin(-cos(-sin(3.0)-cos(-sin(-3.0*5.0)-sin(cos(log10(43.0))))+cos(sin(sin(34.0-2.0^2.0))))--cos(1.0)--cos(0.0)^3.0)" -##xpr = "2.0^(2.0^2.0*2.0^2.0)" -## ошибка ? "sin(e^log(e^e^sin(23.0),45.0) + cos(3.0+log10(e^-e)))" -##xpr = "sin(e^log(e^e^sin(23.0)*45.0) + cos(3.0+log10(e^-e)))" -##xpr = Error cases -##xpr = "" -##xpr = "+" -##xpr = "1-" -##xpr = "1 2" -##xpr = "ee" -##xpr = "==7" -##xpr = "1 + 2(3 * 4))" -##xpr = "((1+2)" -##xpr = "1 + 1 2 3 4 5 6 " -##xpr = "log100(100)" -##xpr = "------" -##xpr = "5 > = 6" -##xpr = "5 / / 6" -##xpr = "6 < = 6" -##xpr = "6 * * 6" -##xpr = "(((((" -##xpr = “pow(2, 3, 4)” - ## EVAL TEST ##test=xpr ##test=test.replace('^','**') @@ -96,91 +31,102 @@ ##print(xpr) oper = ('!','^','//','/','*','%','-','+','(',')','==','<=','>=','<','>','!=','=') -digit = ('1','2','3','4','5','6','7','8','9','0','.') -func = ('sin','cos','tan','log10','log','exp','abs','round','sqrt') -stroka = '' -slovo = '' + +#func = ('sin','cos','tan','log10','log','exp','abs','round','sqrt') +func = dir(math) +print(func) +xprstr = '' +#word = '' operator = '' -spisok = [] +xprlst = [] a = 0. b = 0. result = 0. #разбор строки на элементы списка -def parse(stroka): - slovo='' +def parse(xprstr): + word='' #исправление неверно введенных знаков - stroka = stroka.replace(' ','') - stroka = stroka.replace(',','.') - stroka = stroka.replace('--','+') - stroka = stroka.replace('++','+') - stroka = stroka.replace('+-','-') - stroka = stroka.replace('-+','-') - stroka = stroka.replace('<+','<') - stroka = stroka.replace('>+','>') - stroka = stroka.replace('=<','<=') - stroka = stroka.replace('=>','>=') - stroka = stroka.replace('==+','+') - if stroka[0] == '+': stroka=stroka[1:] - #print('parse:',stroka) + xprstr = xprstr.replace(' ','') + xprstr = xprstr.replace(',','.') + xprstr = xprstr.replace('--','+') + xprstr = xprstr.replace('++','+') + xprstr = xprstr.replace('+-','-') + xprstr = xprstr.replace('-+','-') + xprstr = xprstr.replace('<+','<') + xprstr = xprstr.replace('>+','>') + xprstr = xprstr.replace('=<','<=') + xprstr = xprstr.replace('=>','>=') + xprstr = xprstr.replace('==+','+') + if xprstr[0] == '+': xprstr=xprstr[1:] + #print('parse:',xprstr) #разбор строки - for i,sym in enumerate(stroka + ' '): #добавлен дополнительный пробел - if sym in oper or i == len(stroka): - #print(i,slovo,sym) - if slovo == 'pi': - spisok.append(pi) - elif slovo == 'e': - spisok.append(e) - elif slovo in func: - spisok.append(slovo) - elif slovo.replace('.','').isdigit() and slovo.count('.')<2: - spisok.append(float(slovo)) - elif slovo != '': - print('ERROR: wrong symbol "',slovo,sym,'"') + for i,sym in enumerate(xprstr + ' '): #добавлен дополнительный пробел + if sym in oper or i == len(xprstr): + #print(i,word,sym) + if word == 'pi': + xprlst.append(pi) + elif word == 'e': + xprlst.append(e) + elif word in func: + xprlst.append(word) + elif word.replace('.','').isdigit() and word.count('.')<2: + xprlst.append(float(word)) + elif word != '': + print('ERROR: wrong symbol "',word,sym,'"') exit(0) - spisok.append(sym) - slovo = '' + xprlst.append(sym) + word = '' #print(sym) else: - slovo = slovo + sym - #print(i,sym,spisok) - spisok.pop() #удаляется добавленный пробел + word = word + sym + #print(i,sym,xprlst) + xprlst.pop() #удаляется добавленный пробел - for i,data in enumerate(spisok): - if spisok[i] == '/' and spisok[i + 1] == '/': - spisok[i] = '//' - spisok.pop(i + 1) - if spisok[i] == '>' and spisok[i + 1] == '=': - spisok[i] = '>=' - spisok.pop(i + 1) - if spisok[i] == '<' and spisok[i + 1] == '=': - spisok[i] = '<=' - spisok.pop(i + 1) - if spisok[i] == '=' and spisok[i + 1] == '=' or spisok[i] =='=': - spisok[i] = '==' - spisok.pop(i + 1) - if spisok[i] == '!' and spisok[i + 1] == '=': - spisok[i] = '!=' - spisok.pop(i + 1) - if spisok[i] == '-' and spisok[i - 1] in ('^','//','/','*','%','-','+','==','<=','>=','<','>','!=','=') and type(spisok[i + 1]) == float: - spisok[i + 1] = spisok[i + 1]* - 1 - spisok.pop(i) - if (spisok[i] == '-' and i == 0) or(spisok[i] == '-' and spisok[i - 1] in('*','^','+','-','(','<','>','=') ): - spisok[i] = -1 - spisok.insert(i + 1,'*') - if spisok[i] == '-' and spisok[i - 1] == '/': - spisok[i - 1] = '*' - spisok[i] = -1 - spisok.insert(i + 1,'/') - #print(spisok) - return(spisok) + for i,data in enumerate(xprlst): + if xprlst[i] == '/' and xprlst[i + 1] == '/': + xprlst[i] = '//' + xprlst.pop(i + 1) + if xprlst[i] == '>' and xprlst[i + 1] == '=': + xprlst[i] = '>=' + xprlst.pop(i + 1) + if xprlst[i] == '<' and xprlst[i + 1] == '=': + xprlst[i] = '<=' + xprlst.pop(i + 1) + if xprlst[i] == '=' and xprlst[i + 1] == '=' or xprlst[i] =='=': + xprlst[i] = '==' + xprlst.pop(i + 1) + if xprlst[i] == '!' and xprlst[i + 1] == '=': + xprlst[i] = '!=' + xprlst.pop(i + 1) + if xprlst[i] == '-' and xprlst[i - 1] in ('^','//','/','*','%','-','+','==','<=','>=','<','>','!=','=') and type(xprlst[i + 1]) == float: + xprlst[i + 1] = xprlst[i + 1]* - 1 + xprlst.pop(i) + if (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] in('*','^','+','-','(','<','>','=') ): + xprlst[i] = -1 + xprlst.insert(i + 1,'*') + if xprlst[i] == '-' and xprlst[i - 1] == '/': + xprlst[i - 1] = '*' + xprlst[i] = -1 + xprlst.insert(i + 1,'/') + #print(xprlst) + return(xprlst) + + +def operate2(operator,a,b): + if operator in dir(math): + result=math.__dict__[operator](a) + return result + def operate(operator,a,b): - if operator == "+": + if operator in dir(math): + result=math.__dict__[operator](a) + elif operator == "+": result = a + b elif operator == "-": result = a - b @@ -215,28 +161,6 @@ def operate(operator,a,b): result = a == b elif operator == "!=": result = a != b - elif operator == "abs": - result = abs(a) - elif operator == "round": - result = round(a) - elif operator == "cos": - result = cos(a) - elif operator == "sin": - result = sin(a) - elif operator == "tan": - result = tan(a) - elif operator == "log": - result = log(a) - elif operator == "log10": - result = log10(a) - elif operator == "sqrt": - result = sqrt(a) - elif operator == "cos": - result = cos(a) - elif operator == "exp": - result = exp(a) - elif operator == "!": - result = factorial(a) else: print('ERROR: unknown math operator',operator) result = 0 @@ -248,83 +172,83 @@ def operate(operator,a,b): return result #вычисление выражения без скобок -def calculate(spisok): - if show == 'y': print('Calculate:',spisok) +def calculate(xprlst): + if show == 'y': print('Calculate:',xprlst) # перебор списка функций for f in func: - for i in range(spisok.count(f)): - #print(f,spisok.count(f)) - s = spisok.index(f) - spisok[s] = (operate(f,spisok[s + 1],0)) - spisok[s + 1] = '' - wipe(spisok) - #print(*spisok,sep='') + for i in range(xprlst.count(f)): + #print(f,xprlst.count(f)) + s = xprlst.index(f) + xprlst[s] = (operate(f,xprlst[s + 1],0)) + xprlst[s + 1] = '' + wipe(xprlst) + #print(*xprlst,sep='') #вычисление возведение в степень с реверсом списка - #print('^ count:',spisok.count('^')) - if '^' in spisok: - spisok.reverse() - #print('reverse: ',spisok) - while '^' in spisok: - i = spisok.index('^') + #print('^ count:',xprlst.count('^')) + if '^' in xprlst: + xprlst.reverse() + #print('reverse: ',xprlst) + while '^' in xprlst: + i = xprlst.index('^') #print('i = ',i) - spisok[i] = spisok[i + 1]**spisok[i - 1] - #print(spisok[i + 1],'^',spisok[i - 1],'=',spisok[i]) - spisok[i - 1] = '' - spisok[i + 1] = '' - #print(spisok) - wipe(spisok) - #print(spisok) - spisok.reverse() + xprlst[i] = xprlst[i + 1]**xprlst[i - 1] + #print(xprlst[i + 1],'^',xprlst[i - 1],'=',xprlst[i]) + xprlst[i - 1] = '' + xprlst[i + 1] = '' + #print(xprlst) + wipe(xprlst) + #print(xprlst) + xprlst.reverse() #перебор списка математических операций for j in oper: #print('operation = ',j) - #print(spisok) + #print(xprlst) i = 1 - while i < len(spisok): - if spisok[i] == j: - #print('calculate: ',*spisok,sep='') - spisok[i] = operate(spisok[i],spisok[i - 1],spisok[i + 1]) - spisok[i - 1] = '' - spisok[i + 1] = '' - #print(spisok) - wipe(spisok) + while i < len(xprlst): + if xprlst[i] == j: + #print('calculate: ',*xprlst,sep='') + xprlst[i] = operate(xprlst[i],xprlst[i - 1],xprlst[i + 1]) + xprlst[i - 1] = '' + xprlst[i + 1] = '' + #print(xprlst) + wipe(xprlst) i = i - 1 i = i + 1 - #print('Stop calculate:',float(spisok[0])) - wipe(spisok) - #print(spisok) - result = spisok[0] - if len(spisok) > 1: + #print('Stop calculate:',float(xprlst[0])) + wipe(xprlst) + #print(xprlst) + result = xprlst[0] + if len(xprlst) > 1: print('ERROR: missed operator') #exit(0) return(result) #очистка списка от пустых значений '' -def wipe(spisok): - #print('WIPE:\n',spisok) - while '' in spisok: - i = spisok.index('') - spisok.pop(i) - #print('WIPED:\n',spisok) - return(spisok) +def wipe(xprlst): + #print('WIPE:\n',xprlst) + while '' in xprlst: + i = xprlst.index('') + xprlst.pop(i) + #print('WIPED:\n',xprlst) + return(xprlst) #поиск начала и конца выражения в скобках() -def brktindx(spisok): - bl = spisok.index('(') - br = spisok.index(')') - s = spisok[bl + 1:br] +def brktindx(xprlst): + bl = xprlst.index('(') + br = xprlst.index(')') + s = xprlst[bl + 1:br] #print('BL BR ',bl + 1,' ',br,' ',*s,sep='') while '(' in s: if s.count('(') == s.count(')'): - bl = spisok.index('(',bl + 1) - br = spisok.index(')',bl + 1) - s = spisok[bl + 1:br] + bl = xprlst.index('(',bl + 1) + br = xprlst.index(')',bl + 1) + s = xprlst[bl + 1:br] #print('BL BR ',bl + 1,' ',br,' ', *s,sep='') else: - br = spisok.index(')',br + 1) - s = spisok[bl:br + 1] + br = xprlst.index(')',br + 1) + s = xprlst[bl:br + 1] return(bl + 1,br) @@ -336,26 +260,26 @@ def main(xpr): exit(0) #разбор строики в список - spisok = parse(xpr) - #print(*spisok,sep=',') + xprlst = parse(xpr) + #print(*xprlst,sep=',') #поиск скобок и вычисление в скобках - while '(' in spisok: - a,b = brktindx(spisok) - #print('in brackets: ',*spisok[a:b],sep='') - spisok[a - 1] = calculate(spisok[a:b]) + while '(' in xprlst: + a,b = brktindx(xprlst) + #print('in brackets: ',*xprlst[a:b],sep='') + xprlst[a - 1] = calculate(xprlst[a:b]) while a < b + 1: - spisok[a] = '' + xprlst[a] = '' a = a + 1 - wipe(spisok) - #print(*spisok,sep='') + wipe(xprlst) + #print(*xprlst,sep='') #вычисление без скобок - result = calculate(spisok) + result = calculate(xprlst) #print(result) return (result) diff --git a/pycalc.py b/pycalc.py deleted file mode 100644 index d742d49a..00000000 --- a/pycalc.py +++ /dev/null @@ -1,364 +0,0 @@ -#16.04.2019 12:00 -# to master -#main - -import argparse -from math import pi,e,cos,sin,acos,asin,tan,atan,log,log10,sqrt,exp,factorial - -ap = argparse.ArgumentParser(description = 'Pure-python command-line calculator.') -ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') -ap.add_argument('-p', '--PRINT', default='n', choices=['y', 'n'], type = str, help = 'print evaluation process') -ap.add_argument('-m', '--MODULE', type = str, help = 'use modules MODULE [MODULE...] additional modules to use') -args = ap.parse_args() -##print(args.EXPRESSION) -##print(args.PRINT) -##print(args.MODULE) -xpr = args.EXPRESSION -show = args.PRINT -#show = 'y' - -##xpr = modstr=args.MODULE -##xpr = -##xpr = mod = __import__(modstr) -##xpr = print (modstr,'=',mod.myfunc(3)) - - -## Unary operators -##xpr = "-13" -##xpr = "6-(-13)" -##xpr = "1---1" -##xpr = "-+---+-1" -## Operation priority -##xpr = "1+2*2" -##xpr = "1+(2+3*2)*3" -##xpr = "10*(2+1)" -##xpr = "10^(2+1)" -##xpr = "100/3^2" -##xpr = "100/3%2^2" -## Functions and constants -##xpr = "pi+e" -##xpr = "log(e)" -##xpr = "sin(pi/2)" -##xpr = "log10(100)" -##xpr = "sin(pi/2)*111*6" -##xpr = "2*sin(pi/2)" -##xpr = "abs(-5)" -##xpr = "round(123.456789)" -##xpr = Associative -##xpr = "102%12%7" -##xpr = "100/4/3" -##xpr = "2^3^4" -## Comparison operators -##xpr = "1+2*3==1+2*3" -##xpr = "e^5>=e^5+1" -##xpr = "1+2*4/3+1!=1+2*4/3+2" -## Common tests -##xpr = "(100)" -##xpr = "666" -##xpr = "-.1" -##xpr = "1/3" -##xpr = "1.0/3.0" -##xpr = ".1 * 2.0^56.0" -##xpr = "e^34" -##xpr = "(2.0^(pi/pi+e/e+2.0^0.0))" -##xpr = "(2.0^(pi/pi+e/e+2.0^0.0))^(1.0/3.0)" -##xpr = "sin(pi/2^1) + log(1*4+2^2+1, 3^2)" -##xpr = "10*e^0*log10(.4 -5/ -0.1-10) - -abs(-53/10) + -5" -##xpr = "sin(-cos(-sin(3.0)-cos(-sin(-3.0*5.0)-sin(cos(log10(43.0))))+cos(sin(sin(34.0-2.0^2.0))))--cos(1.0)--cos(0.0)^3.0)" -##xpr = "2.0^(2.0^2.0*2.0^2.0)" -## ошибка ? "sin(e^log(e^e^sin(23.0),45.0) + cos(3.0+log10(e^-e)))" -##xpr = "sin(e^log(e^e^sin(23.0)*45.0) + cos(3.0+log10(e^-e)))" -##xpr = Error cases -##xpr = "" -##xpr = "+" -##xpr = "1-" -##xpr = "1 2" -##xpr = "ee" -##xpr = "==7" -##xpr = "1 + 2(3 * 4))" -##xpr = "((1+2)" -##xpr = "1 + 1 2 3 4 5 6 " -##xpr = "log100(100)" -##xpr = "------" -##xpr = "5 > = 6" -##xpr = "5 / / 6" -##xpr = "6 < = 6" -##xpr = "6 * * 6" -##xpr = "(((((" -##xpr = “pow(2, 3, 4)” - -## EVAL TEST -##test=xpr -##test=test.replace('^','**') -##test=test.replace(' ','') -##test=test.replace(',','.') -##print ('EVAL:',test,'=',eval(test)) -##print(xpr) - -oper = ('!','^','//','/','*','%','-','+','(',')','==','<=','>=','<','>','!=','=') -digit = ('1','2','3','4','5','6','7','8','9','0','.') -func = ('sin','cos','tan','log10','log','exp','abs','round','sqrt') -stroka = '' -slovo = '' -operator = '' -spisok = [] -a = 0. -b = 0. -result = 0. - - -#разбор строки на элементы списка -def parse(stroka): - slovo='' - #исправление неверно введенных знаков - stroka = stroka.replace(' ','') - stroka = stroka.replace(',','.') - stroka = stroka.replace('--','+') - stroka = stroka.replace('++','+') - stroka = stroka.replace('+-','-') - stroka = stroka.replace('-+','-') - stroka = stroka.replace('<+','<') - stroka = stroka.replace('>+','>') - stroka = stroka.replace('=<','<=') - stroka = stroka.replace('=>','>=') - stroka = stroka.replace('==+','+') - if stroka[0] == '+': stroka=stroka[1:] - #print('parse:',stroka) - - #разбор строки - for i,sym in enumerate(stroka + ' '): #добавлен дополнительный пробел - if sym in oper or i == len(stroka): - #print(i,slovo,sym) - if slovo == 'pi': - spisok.append(pi) - elif slovo == 'e': - spisok.append(e) - elif slovo in func: - spisok.append(slovo) - elif slovo.replace('.','').isdigit() and slovo.count('.')<2: - spisok.append(float(slovo)) - elif slovo != '': - print('ERROR: wrong symbol "',slovo,sym,'"') - exit(0) - spisok.append(sym) - slovo = '' - #print(sym) - - else: - slovo = slovo + sym - #print(i,sym,spisok) - spisok.pop() #удаляется добавленный пробел - - for i,data in enumerate(spisok): - if spisok[i] == '/' and spisok[i + 1] == '/': - spisok[i] = '//' - spisok.pop(i + 1) - if spisok[i] == '>' and spisok[i + 1] == '=': - spisok[i] = '>=' - spisok.pop(i + 1) - if spisok[i] == '<' and spisok[i + 1] == '=': - spisok[i] = '<=' - spisok.pop(i + 1) - if spisok[i] == '=' and spisok[i + 1] == '=' or spisok[i] =='=': - spisok[i] = '==' - spisok.pop(i + 1) - if spisok[i] == '!' and spisok[i + 1] == '=': - spisok[i] = '!=' - spisok.pop(i + 1) - if spisok[i] == '-' and spisok[i - 1] in ('^','//','/','*','%','-','+','==','<=','>=','<','>','!=','=') and type(spisok[i + 1]) == float: - spisok[i + 1] = spisok[i + 1]* - 1 - spisok.pop(i) - if (spisok[i] == '-' and i == 0) or(spisok[i] == '-' and spisok[i - 1] in('*','^','+','-','(','<','>','=') ): - spisok[i] = -1 - spisok.insert(i + 1,'*') - if spisok[i] == '-' and spisok[i - 1] == '/': - spisok[i - 1] = '*' - spisok[i] = -1 - spisok.insert(i + 1,'/') - #print(spisok) - return(spisok) - - -def operate(operator,a,b): - if operator == "+": - result = a + b - elif operator == "-": - result = a - b - elif operator == "*": - result = a * b - - elif operator == "//": - if b != 0: - result = a // b - else: - print('ERROR: division by zero') - exit(0) - elif operator == "/": - if b != 0: - result = a / b - else: - print('ERROR: division by zero') - exit(0) - elif operator == "%": - result = a % b - elif operator == "^": - result = a**b - elif operator == "<=": - result = a <= b - elif operator == ">=": - result = a >= b - elif operator == "<": - result = a < b - elif operator == ">": - result = a > b - elif operator == "==": - result = a == b - elif operator == "!=": - result = a != b - elif operator == "abs": - result = abs(a) - elif operator == "round": - result = round(a) - elif operator == "cos": - result = cos(a) - elif operator == "sin": - result = sin(a) - elif operator == "tan": - result = tan(a) - elif operator == "log": - result = log(a) - elif operator == "log10": - result = log10(a) - elif operator == "sqrt": - result = sqrt(a) - elif operator == "cos": - result = cos(a) - elif operator == "exp": - result = exp(a) - elif operator == "!": - result = factorial(a) - else: - print('ERROR: unknown math operator',operator) - result = 0 - if show == 'y': - if operator in oper: - print('Operate:',a,operator,b,'=',result) - elif operator in func: - print('Operate:',operator,a,'=',result) - return result - -#вычисление выражения без скобок -def calculate(spisok): - if show == 'y': print('Calculate:',spisok) - # перебор списка функций - for f in func: - for i in range(spisok.count(f)): - #print(f,spisok.count(f)) - s = spisok.index(f) - spisok[s] = (operate(f,spisok[s + 1],0)) - spisok[s + 1] = '' - wipe(spisok) - #print(*spisok,sep='') - - #вычисление возведение в степень с реверсом списка - #print('^ count:',spisok.count('^')) - if '^' in spisok: - spisok.reverse() - #print('reverse: ',spisok) - while '^' in spisok: - i = spisok.index('^') - #print('i = ',i) - spisok[i] = spisok[i + 1]**spisok[i - 1] - #print(spisok[i + 1],'^',spisok[i - 1],'=',spisok[i]) - spisok[i - 1] = '' - spisok[i + 1] = '' - #print(spisok) - wipe(spisok) - #print(spisok) - spisok.reverse() - - #перебор списка математических операций - for j in oper: - #print('operation = ',j) - #print(spisok) - i = 1 - while i < len(spisok): - if spisok[i] == j: - #print('calculate: ',*spisok,sep='') - spisok[i] = operate(spisok[i],spisok[i - 1],spisok[i + 1]) - spisok[i - 1] = '' - spisok[i + 1] = '' - #print(spisok) - wipe(spisok) - i = i - 1 - i = i + 1 - #print('Stop calculate:',float(spisok[0])) - wipe(spisok) - #print(spisok) - result = spisok[0] - if len(spisok) > 1: - print('ERROR: missed operator') - #exit(0) - return(result) - -#очистка списка от пустых значений '' -def wipe(spisok): - #print('WIPE:\n',spisok) - while '' in spisok: - i = spisok.index('') - spisok.pop(i) - #print('WIPED:\n',spisok) - return(spisok) - -#поиск начала и конца выражения в скобках() -def brktindx(spisok): - bl = spisok.index('(') - br = spisok.index(')') - s = spisok[bl + 1:br] - #print('BL BR ',bl + 1,' ',br,' ',*s,sep='') - while '(' in s: - if s.count('(') == s.count(')'): - bl = spisok.index('(',bl + 1) - br = spisok.index(')',bl + 1) - s = spisok[bl + 1:br] - #print('BL BR ',bl + 1,' ',br,' ', *s,sep='') - else: - br = spisok.index(')',br + 1) - s = spisok[bl:br + 1] - return(bl + 1,br) - - -# основная функция -def main(xpr): - #проверка скобок в строке - if xpr.count('(') != xpr.count(')'): - print('ERROR: brackets are not balanced') - exit(0) - - #разбор строики в список - spisok = parse(xpr) - #print(*spisok,sep=',') - - - - - - #поиск скобок и вычисление в скобках - while '(' in spisok: - a,b = brktindx(spisok) - #print('in brackets: ',*spisok[a:b],sep='') - spisok[a - 1] = calculate(spisok[a:b]) - while a < b + 1: - spisok[a] = '' - a = a + 1 - wipe(spisok) - #print(*spisok,sep='') - - #вычисление без скобок - result = calculate(spisok) - #print(result) - return (result) - -print (main(xpr)) - - diff --git a/setup.py b/setup.py deleted file mode 100644 index abacd055..00000000 --- a/setup.py +++ /dev/null @@ -1,14 +0,0 @@ -from setuptools import setup - -setup( - name='pycalc', # Required - version='1.0', # Required - description='Pure-python command-line calculator.', # Optional - url='https://github.com/novash-k/PythonHomework', # Optional - author='Konstantin Novash', # Optional - author_email='novash.ki@gmail.com', # Optional - py_modules=["pycalc"], # Required - entry_points = {'console_scripts': ['pycalc=pycalc:main',],}, - #packages=['pycalc_project'] # Required - #python_requires='>3.0, <3.7' - ) From e3324b71df116a80c7ccdb698242ca5dbe1fbedf Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 17 Apr 2019 19:17:40 -0400 Subject: [PATCH 013/159] new func --- final_task/pycalc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index eb91e988..a8dbc0f6 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -34,7 +34,7 @@ #func = ('sin','cos','tan','log10','log','exp','abs','round','sqrt') func = dir(math) -print(func) +#print(func) xprstr = '' #word = '' operator = '' From b41747192000d2bfe11e60765fda75c7879c39ad Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 17 Apr 2019 19:25:28 -0400 Subject: [PATCH 014/159] new func --- final_task/pycalc.py | 222 +++++++++++++++++++++---------------------- 1 file changed, 111 insertions(+), 111 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index a8dbc0f6..323e4c00 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,4 +1,4 @@ -#18.04.2019 00:20 +# 18.04.2019 00:20 import argparse import math @@ -9,34 +9,34 @@ ap.add_argument('-p', '--PRINT', default='n', choices=['y', 'n'], type = str, help = 'print evaluation process') ap.add_argument('-m', '--MODULE', type = str, help = 'use modules MODULE [MODULE...] additional modules to use') args = ap.parse_args() -##print(args.EXPRESSION) -##print(args.PRINT) -##print(args.MODULE) +# print(args.EXPRESSION) +# print(args.PRINT) +# print(args.MODULE) xpr = args.EXPRESSION show = args.PRINT -#show = 'y' +# show = 'y' -##xpr = modstr=args.MODULE -##xpr = -##xpr = mod = __import__(modstr) -##xpr = print (modstr,'=',mod.myfunc(3)) +# xpr = modstr=args.MODULE +# xpr = +# xpr = mod = __import__(modstr) +# xpr = print (modstr, '=',mod.myfunc(3)) -## EVAL TEST -##test=xpr -##test=test.replace('^','**') -##test=test.replace(' ','') -##test=test.replace(',','.') -##print ('EVAL:',test,'=',eval(test)) -##print(xpr) +# EVAL TEST +# test=xpr +# test=test.replace('^', '**') +# test=test.replace(' ', '') +# test=test.replace(', ', '.') +# print ('EVAL:',test, '=',eval(test)) +# print(xpr) -oper = ('!','^','//','/','*','%','-','+','(',')','==','<=','>=','<','>','!=','=') +oper = ('!', '^', '//', '/', '*', '%', '-', '+', '(', ')', '==', '<=', '>=', '<', '>', '!=', '=') -#func = ('sin','cos','tan','log10','log','exp','abs','round','sqrt') +# func = ('sin', 'cos', 'tan', 'log10', 'log', 'exp', 'abs', 'round', 'sqrt') func = dir(math) -#print(func) +# print(func) xprstr = '' -#word = '' +# word = '' operator = '' xprlst = [] a = 0. @@ -44,75 +44,75 @@ result = 0. -#разбор строки на элементы списка +# разбор строки на элементы списка def parse(xprstr): word='' - #исправление неверно введенных знаков - xprstr = xprstr.replace(' ','') - xprstr = xprstr.replace(',','.') - xprstr = xprstr.replace('--','+') - xprstr = xprstr.replace('++','+') - xprstr = xprstr.replace('+-','-') - xprstr = xprstr.replace('-+','-') - xprstr = xprstr.replace('<+','<') - xprstr = xprstr.replace('>+','>') - xprstr = xprstr.replace('=<','<=') - xprstr = xprstr.replace('=>','>=') - xprstr = xprstr.replace('==+','+') - if xprstr[0] == '+': xprstr=xprstr[1:] - #print('parse:',xprstr) + # исправление неверно введенных знаков + xprstr = xprstr.replace(' ', '') + xprstr = xprstr.replace(', ', '.') + xprstr = xprstr.replace('--', '+') + xprstr = xprstr.replace('++', '+') + xprstr = xprstr.replace('+-', '-') + xprstr = xprstr.replace('-+', '-') + xprstr = xprstr.replace('<+', '<') + xprstr = xprstr.replace('>+', '>') + xprstr = xprstr.replace('=<', '<=') + xprstr = xprstr.replace('=>', '>=') + xprstr = xprstr.replace('==+', '+') + if xprstr[0]=='+': xprstr=xprstr[1:] + # print('parse:',xprstr) - #разбор строки - for i,sym in enumerate(xprstr + ' '): #добавлен дополнительный пробел - if sym in oper or i == len(xprstr): - #print(i,word,sym) - if word == 'pi': + # разбор строки + for i,sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел + if sym in oper or i==len(xprstr): + # print(i,word,sym) + if word=='pi': xprlst.append(pi) - elif word == 'e': + elif word=='e': xprlst.append(e) elif word in func: xprlst.append(word) - elif word.replace('.','').isdigit() and word.count('.')<2: + elif word.replace('.', '').isdigit() and word.count('.')<2: xprlst.append(float(word)) elif word != '': - print('ERROR: wrong symbol "',word,sym,'"') + print('ERROR: wrong symbol "',word,sym, '"') exit(0) xprlst.append(sym) word = '' - #print(sym) + # print(sym) else: word = word + sym - #print(i,sym,xprlst) - xprlst.pop() #удаляется добавленный пробел + # print(i,sym,xprlst) + xprlst.pop() # удаляется добавленный пробел for i,data in enumerate(xprlst): - if xprlst[i] == '/' and xprlst[i + 1] == '/': + if xprlst[i]=='/' and xprlst[i + 1]=='/': xprlst[i] = '//' xprlst.pop(i + 1) - if xprlst[i] == '>' and xprlst[i + 1] == '=': + if xprlst[i]=='>' and xprlst[i + 1]=='=': xprlst[i] = '>=' xprlst.pop(i + 1) - if xprlst[i] == '<' and xprlst[i + 1] == '=': + if xprlst[i]=='<' and xprlst[i + 1]=='=': xprlst[i] = '<=' xprlst.pop(i + 1) - if xprlst[i] == '=' and xprlst[i + 1] == '=' or xprlst[i] =='=': + if xprlst[i]=='=' and xprlst[i + 1]=='=' or xprlst[i] =='=': xprlst[i] = '==' xprlst.pop(i + 1) - if xprlst[i] == '!' and xprlst[i + 1] == '=': + if xprlst[i]=='!' and xprlst[i + 1]=='=': xprlst[i] = '!=' xprlst.pop(i + 1) - if xprlst[i] == '-' and xprlst[i - 1] in ('^','//','/','*','%','-','+','==','<=','>=','<','>','!=','=') and type(xprlst[i + 1]) == float: + if xprlst[i]=='-' and xprlst[i - 1] in ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '=') and type(xprlst[i + 1])==float: xprlst[i + 1] = xprlst[i + 1]* - 1 xprlst.pop(i) - if (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] in('*','^','+','-','(','<','>','=') ): + if (xprlst[i]=='-' and i==0) or(xprlst[i]=='-' and xprlst[i - 1] in('*', '^', '+', '-', '(', '<', '>', '=') ): xprlst[i] = -1 - xprlst.insert(i + 1,'*') - if xprlst[i] == '-' and xprlst[i - 1] == '/': + xprlst.insert(i + 1, '*') + if xprlst[i]=='-' and xprlst[i - 1]=='/': xprlst[i - 1] = '*' xprlst[i] = -1 - xprlst.insert(i + 1,'/') - #print(xprlst) + xprlst.insert(i + 1, '/') + # print(xprlst) return(xprlst) @@ -126,161 +126,161 @@ def operate2(operator,a,b): def operate(operator,a,b): if operator in dir(math): result=math.__dict__[operator](a) - elif operator == "+": + elif operator=="+": result = a + b - elif operator == "-": + elif operator=="-": result = a - b - elif operator == "*": + elif operator=="*": result = a * b - elif operator == "//": + elif operator=="//": if b != 0: result = a // b else: print('ERROR: division by zero') exit(0) - elif operator == "/": + elif operator=="/": if b != 0: result = a / b else: print('ERROR: division by zero') exit(0) - elif operator == "%": + elif operator=="%": result = a % b - elif operator == "^": + elif operator=="^": result = a**b - elif operator == "<=": + elif operator=="<=": result = a <= b - elif operator == ">=": + elif operator==">=": result = a >= b - elif operator == "<": + elif operator=="<": result = a < b - elif operator == ">": + elif operator==">": result = a > b - elif operator == "==": - result = a == b - elif operator == "!=": + elif operator=="==": + result = a==b + elif operator=="!=": result = a != b else: print('ERROR: unknown math operator',operator) result = 0 - if show == 'y': + if show=='y': if operator in oper: - print('Operate:',a,operator,b,'=',result) + print('Operate:',a,operator,b, '=',result) elif operator in func: - print('Operate:',operator,a,'=',result) + print('Operate:',operator,a, '=',result) return result -#вычисление выражения без скобок +# вычисление выражения без скобок def calculate(xprlst): - if show == 'y': print('Calculate:',xprlst) - # перебор списка функций + if show=='y': print('Calculate:',xprlst) + # перебор списка функций for f in func: for i in range(xprlst.count(f)): - #print(f,xprlst.count(f)) + # print(f,xprlst.count(f)) s = xprlst.index(f) xprlst[s] = (operate(f,xprlst[s + 1],0)) xprlst[s + 1] = '' wipe(xprlst) - #print(*xprlst,sep='') + # print(*xprlst,sep='') - #вычисление возведение в степень с реверсом списка - #print('^ count:',xprlst.count('^')) + # вычисление возведение в степень с реверсом списка + # print('^ count:',xprlst.count('^')) if '^' in xprlst: xprlst.reverse() - #print('reverse: ',xprlst) + # print('reverse: ',xprlst) while '^' in xprlst: i = xprlst.index('^') - #print('i = ',i) + # print('i = ',i) xprlst[i] = xprlst[i + 1]**xprlst[i - 1] - #print(xprlst[i + 1],'^',xprlst[i - 1],'=',xprlst[i]) + # print(xprlst[i + 1], '^',xprlst[i - 1], '=',xprlst[i]) xprlst[i - 1] = '' xprlst[i + 1] = '' - #print(xprlst) + # print(xprlst) wipe(xprlst) - #print(xprlst) + # print(xprlst) xprlst.reverse() - #перебор списка математических операций + # перебор списка математических операций for j in oper: - #print('operation = ',j) - #print(xprlst) + # print('operation = ',j) + # print(xprlst) i = 1 while i < len(xprlst): - if xprlst[i] == j: - #print('calculate: ',*xprlst,sep='') + if xprlst[i]==j: + # print('calculate: ',*xprlst,sep='') xprlst[i] = operate(xprlst[i],xprlst[i - 1],xprlst[i + 1]) xprlst[i - 1] = '' xprlst[i + 1] = '' - #print(xprlst) + # print(xprlst) wipe(xprlst) i = i - 1 i = i + 1 - #print('Stop calculate:',float(xprlst[0])) + # print('Stop calculate:',float(xprlst[0])) wipe(xprlst) - #print(xprlst) + # print(xprlst) result = xprlst[0] if len(xprlst) > 1: print('ERROR: missed operator') - #exit(0) + # exit(0) return(result) -#очистка списка от пустых значений '' +# очистка списка от пустых значений '' def wipe(xprlst): - #print('WIPE:\n',xprlst) + # print('WIPE:\n',xprlst) while '' in xprlst: i = xprlst.index('') xprlst.pop(i) - #print('WIPED:\n',xprlst) + # print('WIPED:\n',xprlst) return(xprlst) -#поиск начала и конца выражения в скобках() +# поиск начала и конца выражения в скобках() def brktindx(xprlst): bl = xprlst.index('(') br = xprlst.index(')') s = xprlst[bl + 1:br] - #print('BL BR ',bl + 1,' ',br,' ',*s,sep='') + # print('BL BR ',bl + 1, ' ',br, ' ',*s,sep='') while '(' in s: - if s.count('(') == s.count(')'): + if s.count('(')==s.count(')'): bl = xprlst.index('(',bl + 1) br = xprlst.index(')',bl + 1) s = xprlst[bl + 1:br] - #print('BL BR ',bl + 1,' ',br,' ', *s,sep='') + # print('BL BR ',bl + 1, ' ',br, ' ', *s,sep='') else: br = xprlst.index(')',br + 1) s = xprlst[bl:br + 1] return(bl + 1,br) -# основная функция +# основная функция def main(xpr): - #проверка скобок в строке + # проверка скобок в строке if xpr.count('(') != xpr.count(')'): print('ERROR: brackets are not balanced') exit(0) - #разбор строики в список + # разбор строики в список xprlst = parse(xpr) - #print(*xprlst,sep=',') + # print(*xprlst,sep=', ') - #поиск скобок и вычисление в скобках + # поиск скобок и вычисление в скобках while '(' in xprlst: a,b = brktindx(xprlst) - #print('in brackets: ',*xprlst[a:b],sep='') + # print('in brackets: ',*xprlst[a:b],sep='') xprlst[a - 1] = calculate(xprlst[a:b]) while a < b + 1: xprlst[a] = '' a = a + 1 wipe(xprlst) - #print(*xprlst,sep='') + # print(*xprlst,sep='') - #вычисление без скобок + # вычисление без скобок result = calculate(xprlst) - #print(result) + # print(result) return (result) print (main(xpr)) From 8bae085c8e4bc2b2d1eaaa068f72a2daf8a9245d Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 17 Apr 2019 19:30:18 -0400 Subject: [PATCH 015/159] new func --- final_task/pycalc.py | 342 +++++++++++++++++++++---------------------- 1 file changed, 171 insertions(+), 171 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 323e4c00..5c9c6320 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,74 +1,74 @@ -# 18.04.2019 00:20 +#18.04.2019 00:20 import argparse import math from math import * -ap = argparse.ArgumentParser(description = 'Pure-python command-line calculator.') +ap=argparse.ArgumentParser(description='Pure-python command-line calculator.') ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') -ap.add_argument('-p', '--PRINT', default='n', choices=['y', 'n'], type = str, help = 'print evaluation process') -ap.add_argument('-m', '--MODULE', type = str, help = 'use modules MODULE [MODULE...] additional modules to use') -args = ap.parse_args() -# print(args.EXPRESSION) -# print(args.PRINT) -# print(args.MODULE) -xpr = args.EXPRESSION -show = args.PRINT -# show = 'y' +ap.add_argument('-p', '--PRINT', default='n', choices=['y', 'n'], type=str, help='print evaluation process') +ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') +args=ap.parse_args() +##print(args.EXPRESSION) +##print(args.PRINT) +##print(args.MODULE) +xpr=args.EXPRESSION +show=args.PRINT +#show='y' -# xpr = modstr=args.MODULE -# xpr = -# xpr = mod = __import__(modstr) -# xpr = print (modstr, '=',mod.myfunc(3)) +##xpr=modstr=args.MODULE +##xpr= +##xpr=mod=__import__(modstr) +##xpr=print (modstr, '=',mod.myfunc(3)) -# EVAL TEST -# test=xpr -# test=test.replace('^', '**') -# test=test.replace(' ', '') -# test=test.replace(', ', '.') -# print ('EVAL:',test, '=',eval(test)) -# print(xpr) +## EVAL TEST +##test=xpr +##test=test.replace('^', '**') +##test=test.replace(' ', '') +##test=test.replace(', ', '.') +##print ('EVAL:',test, '=',eval(test)) +##print(xpr) -oper = ('!', '^', '//', '/', '*', '%', '-', '+', '(', ')', '==', '<=', '>=', '<', '>', '!=', '=') +oper=('!', '^', '//', '/', '*', '%', '-', '+', '(', ')', '==', '<=', '>=', '<', '>', '!=', '=') -# func = ('sin', 'cos', 'tan', 'log10', 'log', 'exp', 'abs', 'round', 'sqrt') -func = dir(math) -# print(func) -xprstr = '' -# word = '' -operator = '' -xprlst = [] -a = 0. -b = 0. -result = 0. +#func=('sin', 'cos', 'tan', 'log10', 'log', 'exp', 'abs', 'round', 'sqrt') +func=dir(math) +print(func) +xprstr='' +#word='' +operator='' +xprlst=[] +a=0. +b=0. +result=0. -# разбор строки на элементы списка +#разбор строки на элементы списка def parse(xprstr): word='' - # исправление неверно введенных знаков - xprstr = xprstr.replace(' ', '') - xprstr = xprstr.replace(', ', '.') - xprstr = xprstr.replace('--', '+') - xprstr = xprstr.replace('++', '+') - xprstr = xprstr.replace('+-', '-') - xprstr = xprstr.replace('-+', '-') - xprstr = xprstr.replace('<+', '<') - xprstr = xprstr.replace('>+', '>') - xprstr = xprstr.replace('=<', '<=') - xprstr = xprstr.replace('=>', '>=') - xprstr = xprstr.replace('==+', '+') - if xprstr[0]=='+': xprstr=xprstr[1:] - # print('parse:',xprstr) + #исправление неверно введенных знаков + xprstr=xprstr.replace(' ', '') + xprstr=xprstr.replace(', ', '.') + xprstr=xprstr.replace('--', '+') + xprstr=xprstr.replace('++', '+') + xprstr=xprstr.replace('+-', '-') + xprstr=xprstr.replace('-+', '-') + xprstr=xprstr.replace('<+', '<') + xprstr=xprstr.replace('>+', '>') + xprstr=xprstr.replace('=<', '<=') + xprstr=xprstr.replace('=>', '>=') + xprstr=xprstr.replace('==+', '+') + if xprstr[0] == '+': xprstr=xprstr[1:] + #print('parse:',xprstr) - # разбор строки - for i,sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел - if sym in oper or i==len(xprstr): - # print(i,word,sym) - if word=='pi': + #разбор строки + for i,sym in enumerate(xprstr + ' '): #добавлен дополнительный пробел + if sym in oper or i == len(xprstr): + #print(i,word,sym) + if word == 'pi': xprlst.append(pi) - elif word=='e': + elif word == 'e': xprlst.append(e) elif word in func: xprlst.append(word) @@ -78,41 +78,41 @@ def parse(xprstr): print('ERROR: wrong symbol "',word,sym, '"') exit(0) xprlst.append(sym) - word = '' - # print(sym) + word='' + #print(sym) else: - word = word + sym - # print(i,sym,xprlst) - xprlst.pop() # удаляется добавленный пробел + word=word + sym + #print(i,sym,xprlst) + xprlst.pop() #удаляется добавленный пробел for i,data in enumerate(xprlst): - if xprlst[i]=='/' and xprlst[i + 1]=='/': - xprlst[i] = '//' + if xprlst[i] == '/' and xprlst[i + 1] == '/': + xprlst[i]='//' xprlst.pop(i + 1) - if xprlst[i]=='>' and xprlst[i + 1]=='=': - xprlst[i] = '>=' + if xprlst[i] == '>' and xprlst[i + 1] == '=': + xprlst[i]='>=' xprlst.pop(i + 1) - if xprlst[i]=='<' and xprlst[i + 1]=='=': - xprlst[i] = '<=' + if xprlst[i] == '<' and xprlst[i + 1] == '=': + xprlst[i]='<=' xprlst.pop(i + 1) - if xprlst[i]=='=' and xprlst[i + 1]=='=' or xprlst[i] =='=': - xprlst[i] = '==' + if xprlst[i] == '=' and xprlst[i + 1] == '=' or xprlst[i] =='=': + xprlst[i]='==' xprlst.pop(i + 1) - if xprlst[i]=='!' and xprlst[i + 1]=='=': - xprlst[i] = '!=' + if xprlst[i] == '!' and xprlst[i + 1] == '=': + xprlst[i]='!=' xprlst.pop(i + 1) - if xprlst[i]=='-' and xprlst[i - 1] in ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '=') and type(xprlst[i + 1])==float: - xprlst[i + 1] = xprlst[i + 1]* - 1 + if xprlst[i] == '-' and xprlst[i - 1] in ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '=') and type(xprlst[i + 1]) == float: + xprlst[i + 1]=xprlst[i + 1]* - 1 xprlst.pop(i) - if (xprlst[i]=='-' and i==0) or(xprlst[i]=='-' and xprlst[i - 1] in('*', '^', '+', '-', '(', '<', '>', '=') ): - xprlst[i] = -1 + if (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] in('*', '^', '+', '-', '(', '<', '>', '=') ): + xprlst[i]=-1 xprlst.insert(i + 1, '*') - if xprlst[i]=='-' and xprlst[i - 1]=='/': - xprlst[i - 1] = '*' - xprlst[i] = -1 + if xprlst[i] == '-' and xprlst[i - 1] == '/': + xprlst[i - 1]='*' + xprlst[i]=-1 xprlst.insert(i + 1, '/') - # print(xprlst) + #print(xprlst) return(xprlst) @@ -126,161 +126,161 @@ def operate2(operator,a,b): def operate(operator,a,b): if operator in dir(math): result=math.__dict__[operator](a) - elif operator=="+": - result = a + b - elif operator=="-": - result = a - b - elif operator=="*": - result = a * b + elif operator == "+": + result=a + b + elif operator == "-": + result=a - b + elif operator == "*": + result=a * b - elif operator=="//": + elif operator == "//": if b != 0: - result = a // b + result=a // b else: print('ERROR: division by zero') exit(0) - elif operator=="/": + elif operator == "/": if b != 0: - result = a / b + result=a / b else: print('ERROR: division by zero') exit(0) - elif operator=="%": - result = a % b - elif operator=="^": - result = a**b - elif operator=="<=": - result = a <= b - elif operator==">=": - result = a >= b - elif operator=="<": - result = a < b - elif operator==">": - result = a > b - elif operator=="==": - result = a==b - elif operator=="!=": - result = a != b + elif operator == "%": + result=a % b + elif operator == "^": + result=a**b + elif operator == "<=": + result=a <= b + elif operator == ">=": + result=a >= b + elif operator == "<": + result=a < b + elif operator == ">": + result=a > b + elif operator == "==": + result=a == b + elif operator == "!=": + result=a != b else: print('ERROR: unknown math operator',operator) - result = 0 - if show=='y': + result=0 + if show == 'y': if operator in oper: print('Operate:',a,operator,b, '=',result) elif operator in func: print('Operate:',operator,a, '=',result) return result -# вычисление выражения без скобок +#вычисление выражения без скобок def calculate(xprlst): - if show=='y': print('Calculate:',xprlst) - # перебор списка функций + if show == 'y': print('Calculate:',xprlst) + # перебор списка функций for f in func: for i in range(xprlst.count(f)): - # print(f,xprlst.count(f)) - s = xprlst.index(f) - xprlst[s] = (operate(f,xprlst[s + 1],0)) - xprlst[s + 1] = '' + #print(f,xprlst.count(f)) + s=xprlst.index(f) + xprlst[s]=(operate(f,xprlst[s + 1],0)) + xprlst[s + 1]='' wipe(xprlst) - # print(*xprlst,sep='') + #print(*xprlst,sep='') - # вычисление возведение в степень с реверсом списка - # print('^ count:',xprlst.count('^')) + #вычисление возведение в степень с реверсом списка + #print('^ count:',xprlst.count('^')) if '^' in xprlst: xprlst.reverse() - # print('reverse: ',xprlst) + #print('reverse: ',xprlst) while '^' in xprlst: - i = xprlst.index('^') - # print('i = ',i) - xprlst[i] = xprlst[i + 1]**xprlst[i - 1] - # print(xprlst[i + 1], '^',xprlst[i - 1], '=',xprlst[i]) - xprlst[i - 1] = '' - xprlst[i + 1] = '' - # print(xprlst) + i=xprlst.index('^') + #print('i=',i) + xprlst[i]=xprlst[i + 1]**xprlst[i - 1] + #print(xprlst[i + 1], '^',xprlst[i - 1], '=',xprlst[i]) + xprlst[i - 1]='' + xprlst[i + 1]='' + #print(xprlst) wipe(xprlst) - # print(xprlst) + #print(xprlst) xprlst.reverse() - # перебор списка математических операций + #перебор списка математических операций for j in oper: - # print('operation = ',j) - # print(xprlst) - i = 1 + #print('operation=',j) + #print(xprlst) + i=1 while i < len(xprlst): - if xprlst[i]==j: - # print('calculate: ',*xprlst,sep='') - xprlst[i] = operate(xprlst[i],xprlst[i - 1],xprlst[i + 1]) - xprlst[i - 1] = '' - xprlst[i + 1] = '' - # print(xprlst) + if xprlst[i] == j: + #print('calculate: ',*xprlst,sep='') + xprlst[i]=operate(xprlst[i],xprlst[i - 1],xprlst[i + 1]) + xprlst[i - 1]='' + xprlst[i + 1]='' + #print(xprlst) wipe(xprlst) - i = i - 1 - i = i + 1 - # print('Stop calculate:',float(xprlst[0])) + i=i - 1 + i=i + 1 + #print('Stop calculate:',float(xprlst[0])) wipe(xprlst) - # print(xprlst) - result = xprlst[0] + #print(xprlst) + result=xprlst[0] if len(xprlst) > 1: print('ERROR: missed operator') - # exit(0) + #exit(0) return(result) -# очистка списка от пустых значений '' +#очистка списка от пустых значений '' def wipe(xprlst): - # print('WIPE:\n',xprlst) + #print('WIPE:\n',xprlst) while '' in xprlst: - i = xprlst.index('') + i=xprlst.index('') xprlst.pop(i) - # print('WIPED:\n',xprlst) + #print('WIPED:\n',xprlst) return(xprlst) -# поиск начала и конца выражения в скобках() +#поиск начала и конца выражения в скобках() def brktindx(xprlst): - bl = xprlst.index('(') - br = xprlst.index(')') - s = xprlst[bl + 1:br] - # print('BL BR ',bl + 1, ' ',br, ' ',*s,sep='') + bl=xprlst.index('(') + br=xprlst.index(')') + s=xprlst[bl + 1:br] + #print('BL BR ',bl + 1, ' ',br, ' ',*s,sep='') while '(' in s: - if s.count('(')==s.count(')'): - bl = xprlst.index('(',bl + 1) - br = xprlst.index(')',bl + 1) - s = xprlst[bl + 1:br] - # print('BL BR ',bl + 1, ' ',br, ' ', *s,sep='') + if s.count('(') == s.count(')'): + bl=xprlst.index('(',bl + 1) + br=xprlst.index(')',bl + 1) + s=xprlst[bl + 1:br] + #print('BL BR ',bl + 1, ' ',br, ' ', *s,sep='') else: - br = xprlst.index(')',br + 1) - s = xprlst[bl:br + 1] + br=xprlst.index(')',br + 1) + s=xprlst[bl:br + 1] return(bl + 1,br) -# основная функция +# основная функция def main(xpr): - # проверка скобок в строке + #проверка скобок в строке if xpr.count('(') != xpr.count(')'): print('ERROR: brackets are not balanced') exit(0) - # разбор строики в список - xprlst = parse(xpr) - # print(*xprlst,sep=', ') + #разбор строики в список + xprlst=parse(xpr) + #print(*xprlst,sep=', ') - # поиск скобок и вычисление в скобках + #поиск скобок и вычисление в скобках while '(' in xprlst: - a,b = brktindx(xprlst) - # print('in brackets: ',*xprlst[a:b],sep='') - xprlst[a - 1] = calculate(xprlst[a:b]) + a,b=brktindx(xprlst) + #print('in brackets: ',*xprlst[a:b],sep='') + xprlst[a - 1]=calculate(xprlst[a:b]) while a < b + 1: - xprlst[a] = '' - a = a + 1 + xprlst[a]='' + a=a + 1 wipe(xprlst) - # print(*xprlst,sep='') + #print(*xprlst,sep='') - # вычисление без скобок - result = calculate(xprlst) - # print(result) + #вычисление без скобок + result=calculate(xprlst) + #print(result) return (result) print (main(xpr)) From d90f7c1134b880d413247b82aa044939c99ad698 Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 17 Apr 2019 19:35:03 -0400 Subject: [PATCH 016/159] new func --- final_task/pycalc.py | 122 +++++++++++++++++++++---------------------- 1 file changed, 61 insertions(+), 61 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 5c9c6320..1f209848 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,4 +1,4 @@ -#18.04.2019 00:20 +# 18.04.2019 00:20 import argparse import math @@ -9,34 +9,34 @@ ap.add_argument('-p', '--PRINT', default='n', choices=['y', 'n'], type=str, help='print evaluation process') ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') args=ap.parse_args() -##print(args.EXPRESSION) -##print(args.PRINT) -##print(args.MODULE) +# print(args.EXPRESSION) +# print(args.PRINT) +# print(args.MODULE) xpr=args.EXPRESSION show=args.PRINT -#show='y' +# show='y' -##xpr=modstr=args.MODULE -##xpr= -##xpr=mod=__import__(modstr) -##xpr=print (modstr, '=',mod.myfunc(3)) +# xpr=modstr=args.MODULE +# xpr= +# xpr=mod=__import__(modstr) +# xpr=print (modstr, '=',mod.myfunc(3)) -## EVAL TEST -##test=xpr -##test=test.replace('^', '**') -##test=test.replace(' ', '') -##test=test.replace(', ', '.') -##print ('EVAL:',test, '=',eval(test)) -##print(xpr) +# EVAL TEST +# test=xpr +# test=test.replace('^', '**') +# test=test.replace(' ', '') +# test=test.replace(', ', '.') +# print ('EVAL:',test, '=',eval(test)) +# print(xpr) oper=('!', '^', '//', '/', '*', '%', '-', '+', '(', ')', '==', '<=', '>=', '<', '>', '!=', '=') -#func=('sin', 'cos', 'tan', 'log10', 'log', 'exp', 'abs', 'round', 'sqrt') +# func=('sin', 'cos', 'tan', 'log10', 'log', 'exp', 'abs', 'round', 'sqrt') func=dir(math) -print(func) +#print(func) xprstr='' -#word='' +# word='' operator='' xprlst=[] a=0. @@ -44,10 +44,10 @@ result=0. -#разбор строки на элементы списка +# разбор строки на элементы списка def parse(xprstr): word='' - #исправление неверно введенных знаков + # исправление неверно введенных знаков xprstr=xprstr.replace(' ', '') xprstr=xprstr.replace(', ', '.') xprstr=xprstr.replace('--', '+') @@ -60,12 +60,12 @@ def parse(xprstr): xprstr=xprstr.replace('=>', '>=') xprstr=xprstr.replace('==+', '+') if xprstr[0] == '+': xprstr=xprstr[1:] - #print('parse:',xprstr) + # print('parse:',xprstr) - #разбор строки - for i,sym in enumerate(xprstr + ' '): #добавлен дополнительный пробел + # разбор строки + for i,sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in oper or i == len(xprstr): - #print(i,word,sym) + # print(i,word,sym) if word == 'pi': xprlst.append(pi) elif word == 'e': @@ -79,12 +79,12 @@ def parse(xprstr): exit(0) xprlst.append(sym) word='' - #print(sym) + # print(sym) else: word=word + sym - #print(i,sym,xprlst) - xprlst.pop() #удаляется добавленный пробел + # print(i,sym,xprlst) + xprlst.pop() # удаляется добавленный пробел for i,data in enumerate(xprlst): if xprlst[i] == '/' and xprlst[i + 1] == '/': @@ -112,7 +112,7 @@ def parse(xprstr): xprlst[i - 1]='*' xprlst[i]=-1 xprlst.insert(i + 1, '/') - #print(xprlst) + # print(xprlst) return(xprlst) @@ -171,81 +171,81 @@ def operate(operator,a,b): print('Operate:',operator,a, '=',result) return result -#вычисление выражения без скобок +# вычисление выражения без скобок def calculate(xprlst): if show == 'y': print('Calculate:',xprlst) # перебор списка функций for f in func: for i in range(xprlst.count(f)): - #print(f,xprlst.count(f)) + # print(f,xprlst.count(f)) s=xprlst.index(f) xprlst[s]=(operate(f,xprlst[s + 1],0)) xprlst[s + 1]='' wipe(xprlst) - #print(*xprlst,sep='') + # print(*xprlst,sep='') - #вычисление возведение в степень с реверсом списка - #print('^ count:',xprlst.count('^')) + # вычисление возведение в степень с реверсом списка + # print('^ count:',xprlst.count('^')) if '^' in xprlst: xprlst.reverse() - #print('reverse: ',xprlst) + # print('reverse: ',xprlst) while '^' in xprlst: i=xprlst.index('^') - #print('i=',i) + # print('i=',i) xprlst[i]=xprlst[i + 1]**xprlst[i - 1] - #print(xprlst[i + 1], '^',xprlst[i - 1], '=',xprlst[i]) + # print(xprlst[i + 1], '^',xprlst[i - 1], '=',xprlst[i]) xprlst[i - 1]='' xprlst[i + 1]='' - #print(xprlst) + # print(xprlst) wipe(xprlst) - #print(xprlst) + # print(xprlst) xprlst.reverse() - #перебор списка математических операций + # перебор списка математических операций for j in oper: - #print('operation=',j) - #print(xprlst) + # print('operation=',j) + # print(xprlst) i=1 while i < len(xprlst): if xprlst[i] == j: - #print('calculate: ',*xprlst,sep='') + # print('calculate: ',*xprlst,sep='') xprlst[i]=operate(xprlst[i],xprlst[i - 1],xprlst[i + 1]) xprlst[i - 1]='' xprlst[i + 1]='' - #print(xprlst) + # print(xprlst) wipe(xprlst) i=i - 1 i=i + 1 - #print('Stop calculate:',float(xprlst[0])) + # print('Stop calculate:',float(xprlst[0])) wipe(xprlst) - #print(xprlst) + # print(xprlst) result=xprlst[0] if len(xprlst) > 1: print('ERROR: missed operator') - #exit(0) + # exit(0) return(result) -#очистка списка от пустых значений '' +# очистка списка от пустых значений '' def wipe(xprlst): - #print('WIPE:\n',xprlst) + # print('WIPE:\n',xprlst) while '' in xprlst: i=xprlst.index('') xprlst.pop(i) - #print('WIPED:\n',xprlst) + # print('WIPED:\n',xprlst) return(xprlst) -#поиск начала и конца выражения в скобках() +# поиск начала и конца выражения в скобках() def brktindx(xprlst): bl=xprlst.index('(') br=xprlst.index(')') s=xprlst[bl + 1:br] - #print('BL BR ',bl + 1, ' ',br, ' ',*s,sep='') + # print('BL BR ',bl + 1, ' ',br, ' ',*s,sep='') while '(' in s: if s.count('(') == s.count(')'): bl=xprlst.index('(',bl + 1) br=xprlst.index(')',bl + 1) s=xprlst[bl + 1:br] - #print('BL BR ',bl + 1, ' ',br, ' ', *s,sep='') + # print('BL BR ',bl + 1, ' ',br, ' ', *s,sep='') else: br=xprlst.index(')',br + 1) s=xprlst[bl:br + 1] @@ -254,33 +254,33 @@ def brktindx(xprlst): # основная функция def main(xpr): - #проверка скобок в строке + # проверка скобок в строке if xpr.count('(') != xpr.count(')'): print('ERROR: brackets are not balanced') exit(0) - #разбор строики в список + # разбор строики в список xprlst=parse(xpr) - #print(*xprlst,sep=', ') + # print(*xprlst,sep=', ') - #поиск скобок и вычисление в скобках + # поиск скобок и вычисление в скобках while '(' in xprlst: a,b=brktindx(xprlst) - #print('in brackets: ',*xprlst[a:b],sep='') + # print('in brackets: ',*xprlst[a:b],sep='') xprlst[a - 1]=calculate(xprlst[a:b]) while a < b + 1: xprlst[a]='' a=a + 1 wipe(xprlst) - #print(*xprlst,sep='') + # print(*xprlst,sep='') - #вычисление без скобок + # вычисление без скобок result=calculate(xprlst) - #print(result) + # print(result) return (result) print (main(xpr)) From 5c59adee42f574e9edecf8161443f9bf2924b325 Mon Sep 17 00:00:00 2001 From: novash-k Date: Thu, 18 Apr 2019 11:54:29 -0400 Subject: [PATCH 017/159] new func --- final_task/pycalc.py | 181 ++++++++++++++++++++++--------------------- 1 file changed, 94 insertions(+), 87 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 1f209848..5cef758b 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -4,112 +4,119 @@ import math from math import * -ap=argparse.ArgumentParser(description='Pure-python command-line calculator.') +ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') ap.add_argument('-p', '--PRINT', default='n', choices=['y', 'n'], type=str, help='print evaluation process') ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') -args=ap.parse_args() +args = ap.parse_args() # print(args.EXPRESSION) # print(args.PRINT) # print(args.MODULE) -xpr=args.EXPRESSION -show=args.PRINT -# show='y' +xpr = args.EXPRESSION +show = args.PRINT +# show = 'y' -# xpr=modstr=args.MODULE +# xpr = modstr = args.MODULE # xpr= # xpr=mod=__import__(modstr) # xpr=print (modstr, '=',mod.myfunc(3)) # EVAL TEST -# test=xpr -# test=test.replace('^', '**') -# test=test.replace(' ', '') -# test=test.replace(', ', '.') +# test = xpr +# test = test.replace('^', '**') +# test = test.replace(' ', '') +# test = test.replace(', ', '.') # print ('EVAL:',test, '=',eval(test)) # print(xpr) -oper=('!', '^', '//', '/', '*', '%', '-', '+', '(', ')', '==', '<=', '>=', '<', '>', '!=', '=') +oper = ('!', '^', '//', '/', '*', '%', '-', '+', '(', ')', '==', '<=', '>=', '<', '>', '!=', '=') + +# func = ('sin', 'cos', 'tan', 'log10', 'log', 'exp', 'abs', 'round', 'sqrt') + +funclist = dir(math)+['abs'] # list of math functions names +funcdict = math.__dict__ # dict of math functions +funcdict['abs'] = abs + -# func=('sin', 'cos', 'tan', 'log10', 'log', 'exp', 'abs', 'round', 'sqrt') -func=dir(math) #print(func) -xprstr='' -# word='' -operator='' -xprlst=[] -a=0. -b=0. -result=0. +xprstr = '' +# word = '' +operator = '' +xprlst = [] +a = 0. +b = 0. +result = 0. # разбор строки на элементы списка def parse(xprstr): - word='' + word = '' # исправление неверно введенных знаков - xprstr=xprstr.replace(' ', '') - xprstr=xprstr.replace(', ', '.') - xprstr=xprstr.replace('--', '+') - xprstr=xprstr.replace('++', '+') - xprstr=xprstr.replace('+-', '-') - xprstr=xprstr.replace('-+', '-') - xprstr=xprstr.replace('<+', '<') - xprstr=xprstr.replace('>+', '>') - xprstr=xprstr.replace('=<', '<=') - xprstr=xprstr.replace('=>', '>=') - xprstr=xprstr.replace('==+', '+') - if xprstr[0] == '+': xprstr=xprstr[1:] - # print('parse:',xprstr) + xprstr = xprstr.replace(' ', '') + xprstr = xprstr.replace(', ', '.') + xprstr = xprstr.replace('--', '+') + xprstr = xprstr.replace('++', '+') + xprstr = xprstr.replace('+-', '-') + xprstr = xprstr.replace('-+', '-') + xprstr = xprstr.replace('<+', '<') + xprstr = xprstr.replace('>+', '>') + xprstr = xprstr.replace('=<', '<=') + xprstr = xprstr.replace('=>', '>=') + xprstr = xprstr.replace('==+', '+') + if xprstr[0] == '+': xprstr = xprstr[1:] + print('parse:',xprstr) # разбор строки for i,sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in oper or i == len(xprstr): - # print(i,word,sym) if word == 'pi': xprlst.append(pi) elif word == 'e': xprlst.append(e) - elif word in func: + elif word in funclist: + print(word,' in math') xprlst.append(word) elif word.replace('.', '').isdigit() and word.count('.')<2: xprlst.append(float(word)) - elif word != '': - print('ERROR: wrong symbol "',word,sym, '"') - exit(0) + #elif word != '': + #else: + # print('ERROR: wrong symbol "',word,sym, '"') + # exit(0) xprlst.append(sym) - word='' - # print(sym) - + word = '' else: - word=word + sym - # print(i,sym,xprlst) + word = word + sym + xprlst.pop() # удаляется добавленный пробел + + print(xprlst) + for i,data in enumerate(xprlst): if xprlst[i] == '/' and xprlst[i + 1] == '/': - xprlst[i]='//' + xprlst[i] = '//' xprlst.pop(i + 1) if xprlst[i] == '>' and xprlst[i + 1] == '=': - xprlst[i]='>=' + xprlst[i] = '>=' xprlst.pop(i + 1) if xprlst[i] == '<' and xprlst[i + 1] == '=': - xprlst[i]='<=' + xprlst[i] = '<=' xprlst.pop(i + 1) if xprlst[i] == '=' and xprlst[i + 1] == '=' or xprlst[i] =='=': - xprlst[i]='==' + xprlst[i] = '==' xprlst.pop(i + 1) if xprlst[i] == '!' and xprlst[i + 1] == '=': - xprlst[i]='!=' + xprlst[i] = '!=' xprlst.pop(i + 1) if xprlst[i] == '-' and xprlst[i - 1] in ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '=') and type(xprlst[i + 1]) == float: - xprlst[i + 1]=xprlst[i + 1]* - 1 + xprlst[i + 1] = xprlst[i + 1]* - 1 xprlst.pop(i) if (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] in('*', '^', '+', '-', '(', '<', '>', '=') ): - xprlst[i]=-1 + xprlst[i] = -1 xprlst.insert(i + 1, '*') if xprlst[i] == '-' and xprlst[i - 1] == '/': - xprlst[i - 1]='*' + xprlst[i - 1] = '*' xprlst[i]=-1 xprlst.insert(i + 1, '/') # print(xprlst) @@ -118,20 +125,20 @@ def parse(xprstr): def operate2(operator,a,b): if operator in dir(math): - result=math.__dict__[operator](a) + result = math.__dict__[operator](a) return result def operate(operator,a,b): if operator in dir(math): - result=math.__dict__[operator](a) + result = funcdict[operator](a) elif operator == "+": - result=a + b + result = a + b elif operator == "-": result=a - b elif operator == "*": - result=a * b + result = a * b elif operator == "//": if b != 0: @@ -175,14 +182,14 @@ def operate(operator,a,b): def calculate(xprlst): if show == 'y': print('Calculate:',xprlst) # перебор списка функций - for f in func: + for f in funclist: for i in range(xprlst.count(f)): # print(f,xprlst.count(f)) - s=xprlst.index(f) - xprlst[s]=(operate(f,xprlst[s + 1],0)) - xprlst[s + 1]='' + s = xprlst.index(f) + xprlst[s] = (operate(f,xprlst[s + 1],0)) + xprlst[s + 1] = '' wipe(xprlst) - # print(*xprlst,sep='') + # print(*xprlst,sep = '') # вычисление возведение в степень с реверсом списка # print('^ count:',xprlst.count('^')) @@ -190,12 +197,12 @@ def calculate(xprlst): xprlst.reverse() # print('reverse: ',xprlst) while '^' in xprlst: - i=xprlst.index('^') + i = xprlst.index('^') # print('i=',i) - xprlst[i]=xprlst[i + 1]**xprlst[i - 1] + xprlst[i] = xprlst[i + 1]**xprlst[i - 1] # print(xprlst[i + 1], '^',xprlst[i - 1], '=',xprlst[i]) - xprlst[i - 1]='' - xprlst[i + 1]='' + xprlst[i - 1] = '' + xprlst[i + 1] = '' # print(xprlst) wipe(xprlst) # print(xprlst) @@ -205,21 +212,21 @@ def calculate(xprlst): for j in oper: # print('operation=',j) # print(xprlst) - i=1 + i = 1 while i < len(xprlst): if xprlst[i] == j: # print('calculate: ',*xprlst,sep='') - xprlst[i]=operate(xprlst[i],xprlst[i - 1],xprlst[i + 1]) - xprlst[i - 1]='' - xprlst[i + 1]='' + xprlst[i] = operate(xprlst[i],xprlst[i - 1],xprlst[i + 1]) + xprlst[i - 1] = '' + xprlst[i + 1] = '' # print(xprlst) wipe(xprlst) - i=i - 1 - i=i + 1 + i = i - 1 + i = i + 1 # print('Stop calculate:',float(xprlst[0])) wipe(xprlst) # print(xprlst) - result=xprlst[0] + result = xprlst[0] if len(xprlst) > 1: print('ERROR: missed operator') # exit(0) @@ -229,26 +236,26 @@ def calculate(xprlst): def wipe(xprlst): # print('WIPE:\n',xprlst) while '' in xprlst: - i=xprlst.index('') + i = xprlst.index('') xprlst.pop(i) # print('WIPED:\n',xprlst) return(xprlst) # поиск начала и конца выражения в скобках() def brktindx(xprlst): - bl=xprlst.index('(') - br=xprlst.index(')') - s=xprlst[bl + 1:br] + bl = xprlst.index('(') + br = xprlst.index(')') + s = xprlst[bl + 1:br] # print('BL BR ',bl + 1, ' ',br, ' ',*s,sep='') while '(' in s: if s.count('(') == s.count(')'): - bl=xprlst.index('(',bl + 1) - br=xprlst.index(')',bl + 1) - s=xprlst[bl + 1:br] + bl = xprlst.index('(',bl + 1) + br = xprlst.index(')',bl + 1) + s = xprlst[bl + 1:br] # print('BL BR ',bl + 1, ' ',br, ' ', *s,sep='') else: - br=xprlst.index(')',br + 1) - s=xprlst[bl:br + 1] + br = xprlst.index(')',br + 1) + s = xprlst[bl:br + 1] return(bl + 1,br) @@ -260,7 +267,7 @@ def main(xpr): exit(0) # разбор строики в список - xprlst=parse(xpr) + xprlst = parse(xpr) # print(*xprlst,sep=', ') @@ -269,17 +276,17 @@ def main(xpr): # поиск скобок и вычисление в скобках while '(' in xprlst: - a,b=brktindx(xprlst) + a,b = brktindx(xprlst) # print('in brackets: ',*xprlst[a:b],sep='') - xprlst[a - 1]=calculate(xprlst[a:b]) + xprlst[a - 1] = calculate(xprlst[a:b]) while a < b + 1: - xprlst[a]='' - a=a + 1 + xprlst[a] = '' + a = a + 1 wipe(xprlst) # print(*xprlst,sep='') # вычисление без скобок - result=calculate(xprlst) + result = calculate(xprlst) # print(result) return (result) From 9d81d9415c9bbe019c3aefe36262f11aafad0c69 Mon Sep 17 00:00:00 2001 From: novash-k Date: Thu, 18 Apr 2019 12:03:31 -0400 Subject: [PATCH 018/159] new func --- final_task/pycalc.py | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 5cef758b..709ac374 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -39,7 +39,7 @@ funcdict['abs'] = abs -#print(func) +# print(func) xprstr = '' # word = '' operator = '' @@ -79,8 +79,8 @@ def parse(xprstr): xprlst.append(word) elif word.replace('.', '').isdigit() and word.count('.')<2: xprlst.append(float(word)) - #elif word != '': - #else: + # elif word != '': + # else: # print('ERROR: wrong symbol "',word,sym, '"') # exit(0) xprlst.append(sym) @@ -90,7 +90,7 @@ def parse(xprstr): xprlst.pop() # удаляется добавленный пробел - print(xprlst) + # print(xprlst) for i,data in enumerate(xprlst): @@ -122,14 +122,6 @@ def parse(xprstr): # print(xprlst) return(xprlst) - -def operate2(operator,a,b): - if operator in dir(math): - result = math.__dict__[operator](a) - return result - - - def operate(operator,a,b): if operator in dir(math): result = funcdict[operator](a) From ed77bd9774dd452e89b5f618c8d702b91eafc2df Mon Sep 17 00:00:00 2001 From: novash-k Date: Thu, 18 Apr 2019 12:05:16 -0400 Subject: [PATCH 019/159] new func --- final_task/pycalc.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 709ac374..8a34a455 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -262,10 +262,6 @@ def main(xpr): xprlst = parse(xpr) # print(*xprlst,sep=', ') - - - - # поиск скобок и вычисление в скобках while '(' in xprlst: a,b = brktindx(xprlst) From 43a47af079745d0c59a0165095b8e6911d76ee6d Mon Sep 17 00:00:00 2001 From: novash-k Date: Thu, 18 Apr 2019 13:20:11 -0400 Subject: [PATCH 020/159] branch novash setup main --- final_task/pycalc.py | 137 +++++++++++++++++++++++-------------------- 1 file changed, 72 insertions(+), 65 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 8a34a455..3c931055 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,3 +1,4 @@ +# coding=utf-8 # 18.04.2019 00:20 import argparse @@ -19,7 +20,7 @@ # xpr = modstr = args.MODULE # xpr= # xpr=mod=__import__(modstr) -# xpr=print (modstr, '=',mod.myfunc(3)) +# xpr=print (modstr, '=', mod.myfunc(3)) # EVAL TEST @@ -27,7 +28,7 @@ # test = test.replace('^', '**') # test = test.replace(' ', '') # test = test.replace(', ', '.') -# print ('EVAL:',test, '=',eval(test)) +# print ('EVAL:', test, '=', eval(test)) # print(xpr) oper = ('!', '^', '//', '/', '*', '%', '-', '+', '(', ')', '==', '<=', '>=', '<', '>', '!=', '=') @@ -64,36 +65,36 @@ def parse(xprstr): xprstr = xprstr.replace('=<', '<=') xprstr = xprstr.replace('=>', '>=') xprstr = xprstr.replace('==+', '+') - if xprstr[0] == '+': xprstr = xprstr[1:] - print('parse:',xprstr) + if xprstr[0] == '+': + xprstr = xprstr[1:] + print('parse:', xprstr) # разбор строки - for i,sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел + for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in oper or i == len(xprstr): if word == 'pi': xprlst.append(pi) elif word == 'e': xprlst.append(e) elif word in funclist: - print(word,' in math') + print(word, ' in math') xprlst.append(word) - elif word.replace('.', '').isdigit() and word.count('.')<2: + elif word.replace('.', '').isdigit() and word.count('.') < 2: xprlst.append(float(word)) # elif word != '': # else: - # print('ERROR: wrong symbol "',word,sym, '"') + # print('ERROR: wrong symbol "', word, sym, '"') # exit(0) xprlst.append(sym) word = '' else: word = word + sym - xprlst.pop() # удаляется добавленный пробел + xprlst.pop() # удаляется добавленный пробел # print(xprlst) - - for i,data in enumerate(xprlst): + for i, data in enumerate(xprlst): if xprlst[i] == '/' and xprlst[i + 1] == '/': xprlst[i] = '//' xprlst.pop(i + 1) @@ -103,152 +104,157 @@ def parse(xprstr): if xprlst[i] == '<' and xprlst[i + 1] == '=': xprlst[i] = '<=' xprlst.pop(i + 1) - if xprlst[i] == '=' and xprlst[i + 1] == '=' or xprlst[i] =='=': + if xprlst[i] == '=' and xprlst[i + 1] == '=' or xprlst[i] == '=': xprlst[i] = '==' xprlst.pop(i + 1) if xprlst[i] == '!' and xprlst[i + 1] == '=': xprlst[i] = '!=' xprlst.pop(i + 1) if xprlst[i] == '-' and xprlst[i - 1] in ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '=') and type(xprlst[i + 1]) == float: - xprlst[i + 1] = xprlst[i + 1]* - 1 + xprlst[i + 1] = xprlst[i + 1] * - 1 xprlst.pop(i) - if (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] in('*', '^', '+', '-', '(', '<', '>', '=') ): + if (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] in('*', '^', '+', '-', '(', '<', '>', '=')): xprlst[i] = -1 xprlst.insert(i + 1, '*') if xprlst[i] == '-' and xprlst[i - 1] == '/': xprlst[i - 1] = '*' - xprlst[i]=-1 + xprlst[i] = -1 xprlst.insert(i + 1, '/') - # print(xprlst) - return(xprlst) + # print(xprlst) + return xprlst -def operate(operator,a,b): + +def operate(operator, a, b): if operator in dir(math): result = funcdict[operator](a) elif operator == "+": - result = a + b + result = a + b elif operator == "-": - result=a - b + result = a - b elif operator == "*": - result = a * b + result = a * b elif operator == "//": if b != 0: - result=a // b + result = a // b else: print('ERROR: division by zero') exit(0) elif operator == "/": if b != 0: - result=a / b + result = a / b else: print('ERROR: division by zero') exit(0) elif operator == "%": - result=a % b + result = a % b elif operator == "^": - result=a**b + result = a**b elif operator == "<=": - result=a <= b + result = a <= b elif operator == ">=": - result=a >= b + result = a >= b elif operator == "<": - result=a < b + result = a < b elif operator == ">": - result=a > b + result = a > b elif operator == "==": - result=a == b + result = a == b elif operator == "!=": - result=a != b + result = a != b else: - print('ERROR: unknown math operator',operator) - result=0 + print('ERROR: unknown math operator', operator) + result = 0 if show == 'y': if operator in oper: - print('Operate:',a,operator,b, '=',result) - elif operator in func: - print('Operate:',operator,a, '=',result) + print('Operate:', a, operator, b, '=', result) + elif operator in funclist: + print('Operate:', operator, a, '=', result) return result + # вычисление выражения без скобок def calculate(xprlst): - if show == 'y': print('Calculate:',xprlst) - # перебор списка функций + if show == 'y': + print('Calculate:', xprlst) + # перебор списка функций for f in funclist: for i in range(xprlst.count(f)): - # print(f,xprlst.count(f)) + # print(f, xprlst.count(f)) s = xprlst.index(f) - xprlst[s] = (operate(f,xprlst[s + 1],0)) + xprlst[s] = (operate(f, xprlst[s + 1], 0)) xprlst[s + 1] = '' wipe(xprlst) - # print(*xprlst,sep = '') - + # print(*xprlst, sep = '') + # вычисление возведение в степень с реверсом списка - # print('^ count:',xprlst.count('^')) + # print('^ count:', xprlst.count('^')) if '^' in xprlst: xprlst.reverse() - # print('reverse: ',xprlst) + # print('reverse: ', xprlst) while '^' in xprlst: i = xprlst.index('^') - # print('i=',i) + # print('i=', i) xprlst[i] = xprlst[i + 1]**xprlst[i - 1] - # print(xprlst[i + 1], '^',xprlst[i - 1], '=',xprlst[i]) + # print(xprlst[i + 1], '^', xprlst[i - 1], '=', xprlst[i]) xprlst[i - 1] = '' xprlst[i + 1] = '' # print(xprlst) wipe(xprlst) # print(xprlst) xprlst.reverse() - + # перебор списка математических операций for j in oper: - # print('operation=',j) + # print('operation=', j) # print(xprlst) i = 1 while i < len(xprlst): if xprlst[i] == j: - # print('calculate: ',*xprlst,sep='') - xprlst[i] = operate(xprlst[i],xprlst[i - 1],xprlst[i + 1]) + # print('calculate: ', *xprlst, sep='') + xprlst[i] = operate(xprlst[i], xprlst[i - 1], xprlst[i + 1]) xprlst[i - 1] = '' xprlst[i + 1] = '' # print(xprlst) wipe(xprlst) i = i - 1 i = i + 1 - # print('Stop calculate:',float(xprlst[0])) + # print('Stop calculate:', float(xprlst[0])) wipe(xprlst) # print(xprlst) result = xprlst[0] if len(xprlst) > 1: print('ERROR: missed operator') # exit(0) - return(result) + return result + # очистка списка от пустых значений '' def wipe(xprlst): - # print('WIPE:\n',xprlst) + # print('WIPE:\n', xprlst) while '' in xprlst: i = xprlst.index('') xprlst.pop(i) - # print('WIPED:\n',xprlst) + # print('WIPED:\n', xprlst) return(xprlst) + # поиск начала и конца выражения в скобках() def brktindx(xprlst): bl = xprlst.index('(') br = xprlst.index(')') s = xprlst[bl + 1:br] - # print('BL BR ',bl + 1, ' ',br, ' ',*s,sep='') + # print('BL BR ', bl + 1, ' ', br, ' ', *s, sep='') while '(' in s: if s.count('(') == s.count(')'): - bl = xprlst.index('(',bl + 1) - br = xprlst.index(')',bl + 1) + bl = xprlst.index('(', bl + 1) + br = xprlst.index(')', bl + 1) s = xprlst[bl + 1:br] - # print('BL BR ',bl + 1, ' ',br, ' ', *s,sep='') + # print('BL BR ', bl + 1, ' ', br, ' ', *s, sep='') else: - br = xprlst.index(')',br + 1) + br = xprlst.index(')', br + 1) s = xprlst[bl:br + 1] - return(bl + 1,br) + return(bl + 1, br) # основная функция @@ -260,24 +266,25 @@ def main(xpr): # разбор строики в список xprlst = parse(xpr) - # print(*xprlst,sep=', ') + # print(*xprlst, sep=', ') # поиск скобок и вычисление в скобках while '(' in xprlst: - a,b = brktindx(xprlst) - # print('in brackets: ',*xprlst[a:b],sep='') + a, b = brktindx(xprlst) + # print('in brackets: ', *xprlst[a:b], sep='') xprlst[a - 1] = calculate(xprlst[a:b]) while a < b + 1: xprlst[a] = '' a = a + 1 wipe(xprlst) - # print(*xprlst,sep='') + # print(*xprlst, sep='') # вычисление без скобок result = calculate(xprlst) # print(result) return (result) -print (main(xpr)) + +print(main(xpr)) From b3261d17078a714ac3a6692d84514fc50da3c72a Mon Sep 17 00:00:00 2001 From: novash-k Date: Thu, 18 Apr 2019 13:30:00 -0400 Subject: [PATCH 021/159] branch novash setup main --- final_task/pycalc.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 3c931055..a4692300 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,5 +1,6 @@ # coding=utf-8 # 18.04.2019 00:20 +# pycharm import argparse import math @@ -67,7 +68,7 @@ def parse(xprstr): xprstr = xprstr.replace('==+', '+') if xprstr[0] == '+': xprstr = xprstr[1:] - print('parse:', xprstr) + # print('parse:', xprstr) # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел @@ -236,7 +237,7 @@ def wipe(xprlst): i = xprlst.index('') xprlst.pop(i) # print('WIPED:\n', xprlst) - return(xprlst) + return xprlst # поиск начала и конца выражения в скобках() From a57b87a8564c185f926ffc7ec3e50886aa75787d Mon Sep 17 00:00:00 2001 From: novash-k Date: Thu, 18 Apr 2019 13:38:41 -0400 Subject: [PATCH 022/159] branch novash setup main --- final_task/pycalc.py | 28 ++++++---------------------- 1 file changed, 6 insertions(+), 22 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index a4692300..0025cbe4 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -8,15 +8,9 @@ ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') -ap.add_argument('-p', '--PRINT', default='n', choices=['y', 'n'], type=str, help='print evaluation process') ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') args = ap.parse_args() -# print(args.EXPRESSION) -# print(args.PRINT) -# print(args.MODULE) xpr = args.EXPRESSION -show = args.PRINT -# show = 'y' # xpr = modstr = args.MODULE # xpr= @@ -24,14 +18,6 @@ # xpr=print (modstr, '=', mod.myfunc(3)) -# EVAL TEST -# test = xpr -# test = test.replace('^', '**') -# test = test.replace(' ', '') -# test = test.replace(', ', '.') -# print ('EVAL:', test, '=', eval(test)) -# print(xpr) - oper = ('!', '^', '//', '/', '*', '%', '-', '+', '(', ')', '==', '<=', '>=', '<', '>', '!=', '=') # func = ('sin', 'cos', 'tan', 'log10', 'log', 'exp', 'abs', 'round', 'sqrt') @@ -78,7 +64,7 @@ def parse(xprstr): elif word == 'e': xprlst.append(e) elif word in funclist: - print(word, ' in math') + # print(word, ' in math') xprlst.append(word) elif word.replace('.', '').isdigit() and word.count('.') < 2: xprlst.append(float(word)) @@ -166,18 +152,16 @@ def operate(operator, a, b): else: print('ERROR: unknown math operator', operator) result = 0 - if show == 'y': - if operator in oper: - print('Operate:', a, operator, b, '=', result) - elif operator in funclist: - print('Operate:', operator, a, '=', result) + # if operator in oper: + # print('Operate:', a, operator, b, '=', result) + # elif operator in funclist: + # print('Operate:', operator, a, '=', result) return result # вычисление выражения без скобок def calculate(xprlst): - if show == 'y': - print('Calculate:', xprlst) + # print('Calculate:', xprlst) # перебор списка функций for f in funclist: for i in range(xprlst.count(f)): From f00338432006403c43d04cc879ea0b5ef0de5723 Mon Sep 17 00:00:00 2001 From: novash-k Date: Thu, 18 Apr 2019 19:58:30 -0400 Subject: [PATCH 023/159] test --- final_task/func.py | 18 +++++++ final_task/pycalc.py | 116 +++++++++++++++++++++++-------------------- 2 files changed, 80 insertions(+), 54 deletions(-) create mode 100644 final_task/func.py diff --git a/final_task/func.py b/final_task/func.py new file mode 100644 index 00000000..e2115ab8 --- /dev/null +++ b/final_task/func.py @@ -0,0 +1,18 @@ +import math +from math import * + +funcdict = {'sin':sin, 'cos':cos, 'pow':pow} + + +def func(oper,*args): + print(oper, args) + print(oper, *args) + print(funcdict[oper](*args) ) + return + +#return funcdict['pow'](a) + + +func('pow',2,3) + +func('sin',2) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 0025cbe4..8cea0b03 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,6 +1,4 @@ # coding=utf-8 -# 18.04.2019 00:20 -# pycharm import argparse import math @@ -12,19 +10,13 @@ args = ap.parse_args() xpr = args.EXPRESSION -# xpr = modstr = args.MODULE -# xpr= -# xpr=mod=__import__(modstr) -# xpr=print (modstr, '=', mod.myfunc(3)) - - +split = ('^', '//', '/', '*', '%', '-', '+', '(', ')', '==', '<=', '>=', '<', '>', '!=', '=', ',') oper = ('!', '^', '//', '/', '*', '%', '-', '+', '(', ')', '==', '<=', '>=', '<', '>', '!=', '=') -# func = ('sin', 'cos', 'tan', 'log10', 'log', 'exp', 'abs', 'round', 'sqrt') - -funclist = dir(math)+['abs'] # list of math functions names +funclist = dir(math)+['abs', 'round'] # list of math functions names funcdict = math.__dict__ # dict of math functions funcdict['abs'] = abs +funcdict['round'] = round # print(func) @@ -42,7 +34,6 @@ def parse(xprstr): word = '' # исправление неверно введенных знаков xprstr = xprstr.replace(' ', '') - xprstr = xprstr.replace(', ', '.') xprstr = xprstr.replace('--', '+') xprstr = xprstr.replace('++', '+') xprstr = xprstr.replace('+-', '-') @@ -58,7 +49,7 @@ def parse(xprstr): # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел - if sym in oper or i == len(xprstr): + if sym in split or i == len(xprstr): if word == 'pi': xprlst.append(pi) elif word == 'e': @@ -111,66 +102,80 @@ def parse(xprstr): return xprlst -def operate(operator, a, b): +def operate(operator, *args): + #print('def operate', operator, args) if operator in dir(math): - result = funcdict[operator](a) + result = funcdict[operator](*args) elif operator == "+": - result = a + b + result = args[0] + args[1] elif operator == "-": - result = a - b + result = args[0] - args[1] elif operator == "*": - result = a * b - + result = args[0] * args[1] elif operator == "//": - if b != 0: - result = a // b + if args[1] != 0: + result = args[0] // args[1] else: print('ERROR: division by zero') exit(0) elif operator == "/": - if b != 0: - result = a / b + if args[1] != 0: + result = args[0] / args[1] else: print('ERROR: division by zero') exit(0) elif operator == "%": - result = a % b + result = args[0] % args[1] elif operator == "^": result = a**b elif operator == "<=": - result = a <= b + result = args[0] <= args[1] elif operator == ">=": - result = a >= b + result = args[0] >= args[1] elif operator == "<": - result = a < b + result = args[0] < args[1] elif operator == ">": - result = a > b + result = args[0] > args[1] elif operator == "==": - result = a == b + result = args[0] == args[1] elif operator == "!=": - result = a != b + result = args[0] != args[1] else: print('ERROR: unknown math operator', operator) result = 0 - # if operator in oper: - # print('Operate:', a, operator, b, '=', result) - # elif operator in funclist: - # print('Operate:', operator, a, '=', result) + + +# if operator in oper: +# print('Operate:', a, operator, b, '=', result) +# elif operator in funclist: +# print('Operate:', operator, a, '=', result) + + return result # вычисление выражения без скобок def calculate(xprlst): - # print('Calculate:', xprlst) + #print('Calculate:', xprlst) # перебор списка функций for f in funclist: for i in range(xprlst.count(f)): + #print(f,'in funclist') # print(f, xprlst.count(f)) s = xprlst.index(f) - xprlst[s] = (operate(f, xprlst[s + 1], 0)) - xprlst[s + 1] = '' + if ',' in xprlst: + #print (f,xprlst[s + 1], xprlst[s + 3]) + xprlst[s] = (operate(f, xprlst[s + 1], xprlst[s + 3])) + xprlst[s + 1] = '' + xprlst[s + 2] = '' + xprlst[s + 3] = '' + else: + #print('norm') + #print (f,xprlst[s + 1]) + xprlst[s] = (operate(f, xprlst[s + 1])) + xprlst[s + 1] = '' wipe(xprlst) - # print(*xprlst, sep = '') + # вычисление возведение в степень с реверсом списка # print('^ count:', xprlst.count('^')) @@ -196,7 +201,7 @@ def calculate(xprlst): i = 1 while i < len(xprlst): if xprlst[i] == j: - # print('calculate: ', *xprlst, sep='') + #print(xprlst[i-1], j, xprlst[i+1]) xprlst[i] = operate(xprlst[i], xprlst[i - 1], xprlst[i + 1]) xprlst[i - 1] = '' xprlst[i + 1] = '' @@ -206,12 +211,12 @@ def calculate(xprlst): i = i + 1 # print('Stop calculate:', float(xprlst[0])) wipe(xprlst) - # print(xprlst) - result = xprlst[0] - if len(xprlst) > 1: - print('ERROR: missed operator') - # exit(0) - return result + #print(xprlst) + + # if len(xprlst) > 1: + # print('ERROR: missed operator') + # #exit(0) + return xprlst # очистка списка от пустых значений '' @@ -242,6 +247,10 @@ def brktindx(xprlst): return(bl + 1, br) + + + + # основная функция def main(xpr): # проверка скобок в строке @@ -256,13 +265,14 @@ def main(xpr): # поиск скобок и вычисление в скобках while '(' in xprlst: a, b = brktindx(xprlst) - # print('in brackets: ', *xprlst[a:b], sep='') - xprlst[a - 1] = calculate(xprlst[a:b]) - while a < b + 1: - xprlst[a] = '' - a = a + 1 - wipe(xprlst) - # print(*xprlst, sep='') + inbrackets = xprlst[a:b] + #print('in brackets to oper: ', inbrackets) + tmp = calculate(xprlst[a:b]) + #print (tmp) + xprlst = xprlst[0:a-1] + tmp + xprlst[b+1:] + + #print(xprlst) + # вычисление без скобок result = calculate(xprlst) @@ -271,5 +281,3 @@ def main(xpr): print(main(xpr)) - - From f4cd8722a81c7c32e427947242cf693a9dc9a64d Mon Sep 17 00:00:00 2001 From: novash-k Date: Thu, 18 Apr 2019 20:02:21 -0400 Subject: [PATCH 024/159] test --- final_task/pycalc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 8cea0b03..cf00bad4 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -277,7 +277,7 @@ def main(xpr): # вычисление без скобок result = calculate(xprlst) # print(result) - return (result) + return (result[0]) print(main(xpr)) From 4090997ca35a292d7547fa5e6a5c2f7a1daa28b8 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 19 Apr 2019 10:43:30 -0400 Subject: [PATCH 025/159] zz --- final_task/pycalc.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index cf00bad4..63a03de7 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -103,7 +103,7 @@ def parse(xprstr): def operate(operator, *args): - #print('def operate', operator, args) + print('def operate', operator, args) if operator in dir(math): result = funcdict[operator](*args) elif operator == "+": @@ -156,11 +156,11 @@ def operate(operator, *args): # вычисление выражения без скобок def calculate(xprlst): - #print('Calculate:', xprlst) + print('Calculate:', xprlst) # перебор списка функций for f in funclist: for i in range(xprlst.count(f)): - #print(f,'in funclist') + print(f,'in funclist') # print(f, xprlst.count(f)) s = xprlst.index(f) if ',' in xprlst: @@ -265,8 +265,7 @@ def main(xpr): # поиск скобок и вычисление в скобках while '(' in xprlst: a, b = brktindx(xprlst) - inbrackets = xprlst[a:b] - #print('in brackets to oper: ', inbrackets) + print('in brackets:',xprlst[a:b]) tmp = calculate(xprlst[a:b]) #print (tmp) xprlst = xprlst[0:a-1] + tmp + xprlst[b+1:] From b8b5be6c054d85ac883a41a8f5124ed2eb5511fa Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 19 Apr 2019 10:50:02 -0400 Subject: [PATCH 026/159] zz --- final_task/pycalc.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 63a03de7..cf00bad4 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -103,7 +103,7 @@ def parse(xprstr): def operate(operator, *args): - print('def operate', operator, args) + #print('def operate', operator, args) if operator in dir(math): result = funcdict[operator](*args) elif operator == "+": @@ -156,11 +156,11 @@ def operate(operator, *args): # вычисление выражения без скобок def calculate(xprlst): - print('Calculate:', xprlst) + #print('Calculate:', xprlst) # перебор списка функций for f in funclist: for i in range(xprlst.count(f)): - print(f,'in funclist') + #print(f,'in funclist') # print(f, xprlst.count(f)) s = xprlst.index(f) if ',' in xprlst: @@ -265,7 +265,8 @@ def main(xpr): # поиск скобок и вычисление в скобках while '(' in xprlst: a, b = brktindx(xprlst) - print('in brackets:',xprlst[a:b]) + inbrackets = xprlst[a:b] + #print('in brackets to oper: ', inbrackets) tmp = calculate(xprlst[a:b]) #print (tmp) xprlst = xprlst[0:a-1] + tmp + xprlst[b+1:] From 04ecb123b6adee31054d42c3f9bfd70353d614e9 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 19 Apr 2019 11:35:04 -0400 Subject: [PATCH 027/159] zz --- final_task/pycalc.py | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index cf00bad4..f52310d5 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -2,6 +2,7 @@ import argparse import math +import string from math import * ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') @@ -10,7 +11,7 @@ args = ap.parse_args() xpr = args.EXPRESSION -split = ('^', '//', '/', '*', '%', '-', '+', '(', ')', '==', '<=', '>=', '<', '>', '!=', '=', ',') +split = ('^', '//', '/', '*', '%', '-', '+', '(', ')', '==', '<=', '>=', '<', '>', '!=', '=', ',','!') oper = ('!', '^', '//', '/', '*', '%', '-', '+', '(', ')', '==', '<=', '>=', '<', '>', '!=', '=') funclist = dir(math)+['abs', 'round'] # list of math functions names @@ -67,10 +68,11 @@ def parse(xprstr): word = '' else: word = word + sym + # print(word) xprlst.pop() # удаляется добавленный пробел - # print(xprlst) + # print(xprlst) for i, data in enumerate(xprlst): if xprlst[i] == '/' and xprlst[i + 1] == '/': @@ -98,11 +100,25 @@ def parse(xprstr): xprlst[i - 1] = '*' xprlst[i] = -1 xprlst.insert(i + 1, '/') - # print(xprlst) +# print(xprlst) + + + +# ss=set(xprstr) +# digitsset = set(string.digits) +# funcset = set(funclist) +# digitsset.union(funcset) + +# print(digitsset.union(funcset)) + # print(ss) + # print('!!!!!!!!!!!!!!!!!!', ss.isdisjoint(digitsset)) + + return xprlst def operate(operator, *args): + #print('def operate', operator, args) if operator in dir(math): result = funcdict[operator](*args) @@ -156,7 +172,7 @@ def operate(operator, *args): # вычисление выражения без скобок def calculate(xprlst): - #print('Calculate:', xprlst) + # print('Calculate:', xprlst) # перебор списка функций for f in funclist: for i in range(xprlst.count(f)): @@ -196,7 +212,7 @@ def calculate(xprlst): # перебор списка математических операций for j in oper: - # print('operation=', j) + # print('operation=', j) # print(xprlst) i = 1 while i < len(xprlst): @@ -205,7 +221,7 @@ def calculate(xprlst): xprlst[i] = operate(xprlst[i], xprlst[i - 1], xprlst[i + 1]) xprlst[i - 1] = '' xprlst[i + 1] = '' - # print(xprlst) + # print(xprlst) wipe(xprlst) i = i - 1 i = i + 1 From b611f4bf869d47e8f9cc1a6f0d28e87f48dbf91c Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 19 Apr 2019 11:50:38 -0400 Subject: [PATCH 028/159] zz --- final_task/pycalc.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index f52310d5..fafa589e 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -34,7 +34,11 @@ def parse(xprstr): word = '' # исправление неверно введенных знаков - xprstr = xprstr.replace(' ', '') + if xprstr.count(' ') > 0: + print ('ERROR: unexpected spase') + exit(0) + + #xprstr = xprstr.replace(' ', '') xprstr = xprstr.replace('--', '+') xprstr = xprstr.replace('++', '+') xprstr = xprstr.replace('+-', '-') From 61ad571695c288862a129bea1dcfa96d3e0f4020 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 19 Apr 2019 15:25:22 -0400 Subject: [PATCH 029/159] zz --- final_task/pycalc.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index fafa589e..1e56852e 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -34,11 +34,8 @@ def parse(xprstr): word = '' # исправление неверно введенных знаков - if xprstr.count(' ') > 0: - print ('ERROR: unexpected spase') - exit(0) - #xprstr = xprstr.replace(' ', '') + xprstr = xprstr.replace(' ', '') xprstr = xprstr.replace('--', '+') xprstr = xprstr.replace('++', '+') xprstr = xprstr.replace('+-', '-') @@ -77,6 +74,14 @@ def parse(xprstr): xprlst.pop() # удаляется добавленный пробел # print(xprlst) + punctset = set(string.punctuation) + xprset = set(xprstr) + if xprset.issubset(punctset): + print('ERROR: no digits or functions') + exit(0) + + + for i, data in enumerate(xprlst): if xprlst[i] == '/' and xprlst[i + 1] == '/': From e53fdebc4fb32b33687998003185b6444ba9f696 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 19 Apr 2019 16:44:30 -0400 Subject: [PATCH 030/159] zz --- final_task/pycalc.py | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 1e56852e..5472f2c4 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -11,8 +11,22 @@ args = ap.parse_args() xpr = args.EXPRESSION -split = ('^', '//', '/', '*', '%', '-', '+', '(', ')', '==', '<=', '>=', '<', '>', '!=', '=', ',','!') -oper = ('!', '^', '//', '/', '*', '%', '-', '+', '(', ')', '==', '<=', '>=', '<', '>', '!=', '=') +funcset = {} +operset = {} +splitset = {} +xprset = {} + + + +split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', ',', '(', ')') +oper = ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=') + +# проверка недопустимых символов +exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} +xprset = set(xpr) +if not exset.isdisjoint(xprset): + print('ERROR: unknown symbol') + exit(0) funclist = dir(math)+['abs', 'round'] # list of math functions names funcdict = math.__dict__ # dict of math functions @@ -20,6 +34,7 @@ funcdict['round'] = round + # print(func) xprstr = '' # word = '' @@ -30,6 +45,9 @@ result = 0. + + + # разбор строки на элементы списка def parse(xprstr): word = '' @@ -40,11 +58,11 @@ def parse(xprstr): xprstr = xprstr.replace('++', '+') xprstr = xprstr.replace('+-', '-') xprstr = xprstr.replace('-+', '-') - xprstr = xprstr.replace('<+', '<') - xprstr = xprstr.replace('>+', '>') - xprstr = xprstr.replace('=<', '<=') - xprstr = xprstr.replace('=>', '>=') - xprstr = xprstr.replace('==+', '+') + # xprstr = xprstr.replace('<+', '<') + # xprstr = xprstr.replace('>+', '>') + # xprstr = xprstr.replace('=<', '<=') + # xprstr = xprstr.replace('=>', '>=') + # xprstr = xprstr.replace('==+', '+') if xprstr[0] == '+': xprstr = xprstr[1:] # print('parse:', xprstr) From e56efcafd287b3c11e36d9d90468a62d4ee5090f Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 19 Apr 2019 17:27:55 -0400 Subject: [PATCH 031/159] zz --- final_task/pycalc.py | 39 +++++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 5472f2c4..4f8b2599 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -19,7 +19,7 @@ split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', ',', '(', ')') -oper = ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=') +oper = ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '(', ')') # проверка недопустимых символов exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} @@ -70,6 +70,7 @@ def parse(xprstr): # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): + # print(word) if word == 'pi': xprlst.append(pi) elif word == 'e': @@ -80,18 +81,23 @@ def parse(xprstr): elif word.replace('.', '').isdigit() and word.count('.') < 2: xprlst.append(float(word)) # elif word != '': - # else: - # print('ERROR: wrong symbol "', word, sym, '"') - # exit(0) + elif word in split or word == '': + pass + # print('ok', word) + else: + print('ERROR: wrong symbol "', word, sym, '"') + exit(0) xprlst.append(sym) + # print(xprlst) word = '' else: word = word + sym - # print(word) + # print(word) xprlst.pop() # удаляется добавленный пробел - # print(xprlst) + #print('XPRLST:',xprlst) + punctset = set(string.punctuation) xprset = set(xprstr) if xprset.issubset(punctset): @@ -105,29 +111,34 @@ def parse(xprstr): if xprlst[i] == '/' and xprlst[i + 1] == '/': xprlst[i] = '//' xprlst.pop(i + 1) - if xprlst[i] == '>' and xprlst[i + 1] == '=': + elif xprlst[i] == '>' and xprlst[i + 1] == '=': xprlst[i] = '>=' xprlst.pop(i + 1) - if xprlst[i] == '<' and xprlst[i + 1] == '=': + elif xprlst[i] == '<' and xprlst[i + 1] == '=': xprlst[i] = '<=' xprlst.pop(i + 1) - if xprlst[i] == '=' and xprlst[i + 1] == '=' or xprlst[i] == '=': + elif xprlst[i] == '=' and xprlst[i + 1] == '=' or xprlst[i] == '=': xprlst[i] = '==' xprlst.pop(i + 1) - if xprlst[i] == '!' and xprlst[i + 1] == '=': + elif xprlst[i] == '!' and xprlst[i + 1] == '=': xprlst[i] = '!=' xprlst.pop(i + 1) - if xprlst[i] == '-' and xprlst[i - 1] in ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '=') and type(xprlst[i + 1]) == float: + elif xprlst[i] == '-' and xprlst[i - 1] in ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '=') and type(xprlst[i + 1]) == float: xprlst[i + 1] = xprlst[i + 1] * - 1 xprlst.pop(i) - if (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] in('*', '^', '+', '-', '(', '<', '>', '=')): + elif (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] in('*', '^', '+', '-', '(', '<', '>', '=')): xprlst[i] = -1 xprlst.insert(i + 1, '*') - if xprlst[i] == '-' and xprlst[i - 1] == '/': + elif xprlst[i] == '-' and xprlst[i - 1] == '/': xprlst[i - 1] = '*' xprlst[i] = -1 xprlst.insert(i + 1, '/') -# print(xprlst) + elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper: + pass + # print('ok',i) + else: + print('ERROR: unknown',xprlst[i],i) + # print(xprlst) From 50cf128ce57af4b7d451830e281c9174cee19e2c Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 19 Apr 2019 17:39:14 -0400 Subject: [PATCH 032/159] zz --- final_task/pycalc.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 4f8b2599..649ef5ee 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -18,7 +18,7 @@ -split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', ',', '(', ')') +split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') oper = ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '(', ')') # проверка недопустимых символов @@ -133,12 +133,12 @@ def parse(xprstr): xprlst[i - 1] = '*' xprlst[i] = -1 xprlst.insert(i + 1, '/') - elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper: + elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: pass # print('ok',i) else: print('ERROR: unknown',xprlst[i],i) - # print(xprlst) + print(xprlst) From c19bbd5e22d805d9496ed7dae3e77e287d3a4e53 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 19 Apr 2019 17:53:05 -0400 Subject: [PATCH 033/159] zz --- final_task/pycalc.py | 120 ++++++++++++++----------------------------- 1 file changed, 38 insertions(+), 82 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 649ef5ee..00f3ae96 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -14,15 +14,12 @@ funcset = {} operset = {} splitset = {} -xprset = {} - - split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') -oper = ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '(', ')') +oper = ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '(', ')') # проверка недопустимых символов -exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} +exset = {'"', '# ', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} xprset = set(xpr) if not exset.isdisjoint(xprset): print('ERROR: unknown symbol') @@ -32,12 +29,7 @@ funcdict = math.__dict__ # dict of math functions funcdict['abs'] = abs funcdict['round'] = round - - - -# print(func) xprstr = '' -# word = '' operator = '' xprlst = [] a = 0. @@ -45,9 +37,6 @@ result = 0. - - - # разбор строки на элементы списка def parse(xprstr): word = '' @@ -58,19 +47,13 @@ def parse(xprstr): xprstr = xprstr.replace('++', '+') xprstr = xprstr.replace('+-', '-') xprstr = xprstr.replace('-+', '-') - # xprstr = xprstr.replace('<+', '<') - # xprstr = xprstr.replace('>+', '>') - # xprstr = xprstr.replace('=<', '<=') - # xprstr = xprstr.replace('=>', '>=') - # xprstr = xprstr.replace('==+', '+') if xprstr[0] == '+': xprstr = xprstr[1:] - # print('parse:', xprstr) # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): - # print(word) + # print(word) if word == 'pi': xprlst.append(pi) elif word == 'e': @@ -88,25 +71,21 @@ def parse(xprstr): print('ERROR: wrong symbol "', word, sym, '"') exit(0) xprlst.append(sym) - # print(xprlst) + # print(xprlst) word = '' else: word = word + sym - # print(word) + # print(word) xprlst.pop() # удаляется добавленный пробел - #print('XPRLST:',xprlst) + # print('XPRLST:',xprlst) punctset = set(string.punctuation) xprset = set(xprstr) if xprset.issubset(punctset): print('ERROR: no digits or functions') exit(0) - - - - for i, data in enumerate(xprlst): if xprlst[i] == '/' and xprlst[i + 1] == '/': xprlst[i] = '//' @@ -135,97 +114,80 @@ def parse(xprstr): xprlst.insert(i + 1, '/') elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: pass - # print('ok',i) + # print('ok',i) else: - print('ERROR: unknown',xprlst[i],i) - print(xprlst) - - - -# ss=set(xprstr) -# digitsset = set(string.digits) -# funcset = set(funclist) -# digitsset.union(funcset) - -# print(digitsset.union(funcset)) - # print(ss) - # print('!!!!!!!!!!!!!!!!!!', ss.isdisjoint(digitsset)) - + print('ERROR: unknown', xprlst[i], i) + # print(xprlst) return xprlst def operate(operator, *args): - - #print('def operate', operator, args) + # print('def operate', operator, args) if operator in dir(math): result = funcdict[operator](*args) elif operator == "+": - result = args[0] + args[1] + result = args[0] + args[1] elif operator == "-": - result = args[0] - args[1] + result = args[0] - args[1] elif operator == "*": - result = args[0] * args[1] + result = args[0] * args[1] elif operator == "//": if args[1] != 0: - result = args[0] // args[1] + result = args[0] // args[1] else: print('ERROR: division by zero') exit(0) elif operator == "/": if args[1] != 0: - result = args[0] / args[1] + result = args[0] / args[1] else: print('ERROR: division by zero') exit(0) elif operator == "%": - result = args[0] % args[1] + result = args[0] % args[1] elif operator == "^": result = a**b elif operator == "<=": - result = args[0] <= args[1] + result = args[0] <= args[1] elif operator == ">=": - result = args[0] >= args[1] + result = args[0] >= args[1] elif operator == "<": - result = args[0] < args[1] + result = args[0] < args[1] elif operator == ">": - result = args[0] > args[1] + result = args[0] > args[1] elif operator == "==": - result = args[0] == args[1] + result = args[0] == args[1] elif operator == "!=": - result = args[0] != args[1] + result = args[0] != args[1] else: print('ERROR: unknown math operator', operator) result = 0 - - # if operator in oper: # print('Operate:', a, operator, b, '=', result) # elif operator in funclist: # print('Operate:', operator, a, '=', result) - - return result # вычисление выражения без скобок def calculate(xprlst): - # print('Calculate:', xprlst) + # print('Calculate:', xprlst) # перебор списка функций for f in funclist: for i in range(xprlst.count(f)): - #print(f,'in funclist') + # print(f,'in funclist') # print(f, xprlst.count(f)) s = xprlst.index(f) if ',' in xprlst: - #print (f,xprlst[s + 1], xprlst[s + 3]) + # print (f,xprlst[s + 1], xprlst[s + 3]) xprlst[s] = (operate(f, xprlst[s + 1], xprlst[s + 3])) xprlst[s + 1] = '' xprlst[s + 2] = '' xprlst[s + 3] = '' else: - #print('norm') - #print (f,xprlst[s + 1]) + # print('norm') + # print (f,xprlst[s + 1]) xprlst[s] = (operate(f, xprlst[s + 1])) xprlst[s + 1] = '' wipe(xprlst) @@ -250,26 +212,25 @@ def calculate(xprlst): # перебор списка математических операций for j in oper: - # print('operation=', j) + # print('operation=', j) # print(xprlst) i = 1 while i < len(xprlst): if xprlst[i] == j: - #print(xprlst[i-1], j, xprlst[i+1]) + # print(xprlst[i-1], j, xprlst[i+1]) xprlst[i] = operate(xprlst[i], xprlst[i - 1], xprlst[i + 1]) xprlst[i - 1] = '' xprlst[i + 1] = '' - # print(xprlst) + # print(xprlst) wipe(xprlst) i = i - 1 i = i + 1 # print('Stop calculate:', float(xprlst[0])) wipe(xprlst) - #print(xprlst) - - # if len(xprlst) > 1: - # print('ERROR: missed operator') - # #exit(0) + # print(xprlst) + # if len(xprlst) > 1: + # print('ERROR: missed operator') + # exit(0) return xprlst @@ -301,10 +262,6 @@ def brktindx(xprlst): return(bl + 1, br) - - - - # основная функция def main(xpr): # проверка скобок в строке @@ -320,18 +277,17 @@ def main(xpr): while '(' in xprlst: a, b = brktindx(xprlst) inbrackets = xprlst[a:b] - #print('in brackets to oper: ', inbrackets) + # print('in brackets to oper: ', inbrackets) tmp = calculate(xprlst[a:b]) - #print (tmp) + # print (tmp) xprlst = xprlst[0:a-1] + tmp + xprlst[b+1:] - #print(xprlst) - + # print(xprlst) # вычисление без скобок result = calculate(xprlst) # print(result) - return (result[0]) + return result[0] print(main(xpr)) From 4083dad60492e58eedea711f07661582ca5ed284 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 19 Apr 2019 18:33:06 -0400 Subject: [PATCH 034/159] zz --- final_task/pycalc.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 00f3ae96..0f0fe634 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -79,7 +79,7 @@ def parse(xprstr): xprlst.pop() # удаляется добавленный пробел - # print('XPRLST:',xprlst) + # print('XPRLST:', xprlst) punctset = set(string.punctuation) xprset = set(xprstr) @@ -114,7 +114,7 @@ def parse(xprstr): xprlst.insert(i + 1, '/') elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: pass - # print('ok',i) + # print('ok', i) else: print('ERROR: unknown', xprlst[i], i) # print(xprlst) @@ -124,6 +124,11 @@ def parse(xprstr): def operate(operator, *args): # print('def operate', operator, args) + for i in args: + if type(i) != float: + print('ERROR: operate non float arguments') + exit(0) + if operator in dir(math): result = funcdict[operator](*args) elif operator == "+": @@ -170,6 +175,7 @@ def operate(operator, *args): return result + # вычисление выражения без скобок def calculate(xprlst): # print('Calculate:', xprlst) @@ -187,7 +193,7 @@ def calculate(xprlst): xprlst[s + 3] = '' else: # print('norm') - # print (f,xprlst[s + 1]) + # print (f, xprlst[s + 1]) xprlst[s] = (operate(f, xprlst[s + 1])) xprlst[s + 1] = '' wipe(xprlst) @@ -236,11 +242,11 @@ def calculate(xprlst): # очистка списка от пустых значений '' def wipe(xprlst): - # print('WIPE:\n', xprlst) + # print('WIPE', xprlst) while '' in xprlst: i = xprlst.index('') xprlst.pop(i) - # print('WIPED:\n', xprlst) + # print('WIPED', xprlst) return xprlst From c52e512cce7c2a47d660de0504c58274b1271d50 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 19 Apr 2019 18:42:35 -0400 Subject: [PATCH 035/159] zz --- final_task/pycalc.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 0f0fe634..0b50b032 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -125,8 +125,8 @@ def parse(xprstr): def operate(operator, *args): # print('def operate', operator, args) for i in args: - if type(i) != float: - print('ERROR: operate non float arguments') + if not( type(i) == float or type(i) == int): + print('ERROR: operate non float arguments', i, args) exit(0) if operator in dir(math): From f810af4394fd1a4f63b9e3266705f28569136b4a Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 19 Apr 2019 19:10:34 -0400 Subject: [PATCH 036/159] zz --- final_task/pycalc.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 0b50b032..dc6590f1 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -42,6 +42,11 @@ def parse(xprstr): word = '' # исправление неверно введенных знаков + xprstr = xprstr.replace(' -', '-') + if xprstr.count(' ') > 0: + print ('ERROR: useless spaces') + exit(0) + xprstr = xprstr.replace(' ', '') xprstr = xprstr.replace('--', '+') xprstr = xprstr.replace('++', '+') @@ -181,6 +186,9 @@ def calculate(xprlst): # print('Calculate:', xprlst) # перебор списка функций for f in funclist: + if len(xprlst) <1: + print('ERROR: no arguments') + exit(0) for i in range(xprlst.count(f)): # print(f,'in funclist') # print(f, xprlst.count(f)) @@ -292,6 +300,7 @@ def main(xpr): # вычисление без скобок result = calculate(xprlst) + # print(result) return result[0] From 81334fcfd6e14e6f1f347ecd101b743c5efbdd63 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 19 Apr 2019 19:33:43 -0400 Subject: [PATCH 037/159] zz --- final_task/pycalc.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index dc6590f1..bcf56adf 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -35,6 +35,7 @@ a = 0. b = 0. result = 0. +funcset=set(funclist) # разбор строки на элементы списка @@ -42,10 +43,10 @@ def parse(xprstr): word = '' # исправление неверно введенных знаков - xprstr = xprstr.replace(' -', '-') - if xprstr.count(' ') > 0: - print ('ERROR: useless spaces') - exit(0) + # xprstr = xprstr.replace(' -', '-') + # if xprstr.count(' ') > 0: + # print ('ERROR: useless spaces') + # exit(0) xprstr = xprstr.replace(' ', '') xprstr = xprstr.replace('--', '+') @@ -88,7 +89,9 @@ def parse(xprstr): punctset = set(string.punctuation) xprset = set(xprstr) - if xprset.issubset(punctset): + + # print (funcset) + if xprset.issubset(punctset) or xprset.issubset(funcset): print('ERROR: no digits or functions') exit(0) for i, data in enumerate(xprlst): @@ -119,16 +122,17 @@ def parse(xprstr): xprlst.insert(i + 1, '/') elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: pass + # print('ok', i) else: print('ERROR: unknown', xprlst[i], i) - # print(xprlst) + # print(xprlst) return xprlst def operate(operator, *args): - # print('def operate', operator, args) + # print('def operate', operator, args) for i in args: if not( type(i) == float or type(i) == int): print('ERROR: operate non float arguments', i, args) @@ -183,7 +187,7 @@ def operate(operator, *args): # вычисление выражения без скобок def calculate(xprlst): - # print('Calculate:', xprlst) + # print('Calculate:', xprlst) # перебор списка функций for f in funclist: if len(xprlst) <1: From 29a886c02170cc1b28a4a988a344b662d67f57d6 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sat, 20 Apr 2019 18:58:49 -0400 Subject: [PATCH 038/159] zz --- final_task/pycalc.py | 310 +++++++++++++++++++++---------------------- final_task/test.py | 43 ++++++ 2 files changed, 198 insertions(+), 155 deletions(-) create mode 100644 final_task/test.py diff --git a/final_task/pycalc.py b/final_task/pycalc.py index bcf56adf..74ef90a3 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -16,7 +16,6 @@ splitset = {} split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') -oper = ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '(', ')') # проверка недопустимых символов exset = {'"', '# ', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} @@ -37,17 +36,20 @@ result = 0. funcset=set(funclist) +oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!='] +operhi = ['^'] + funclist # 3 +opermid = ['*', '/'] # 2 +operlow = ['+', '-'] # 1 +operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!='] # 0 + # разбор строки на элементы списка def parse(xprstr): word = '' - # исправление неверно введенных знаков - - # xprstr = xprstr.replace(' -', '-') - # if xprstr.count(' ') > 0: - # print ('ERROR: useless spaces') - # exit(0) - + # проверка скобок в строке + if xpr.count('(') != xpr.count(')'): + print('ERROR: brackets are not balanced') + exit(0) xprstr = xprstr.replace(' ', '') xprstr = xprstr.replace('--', '+') xprstr = xprstr.replace('++', '+') @@ -59,38 +61,38 @@ def parse(xprstr): # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): - # print(word) + # # print(word) if word == 'pi': xprlst.append(pi) elif word == 'e': xprlst.append(e) elif word in funclist: - # print(word, ' in math') + # # print(word, ' in math') xprlst.append(word) elif word.replace('.', '').isdigit() and word.count('.') < 2: xprlst.append(float(word)) # elif word != '': elif word in split or word == '': pass - # print('ok', word) + # # print('ok', word) else: print('ERROR: wrong symbol "', word, sym, '"') exit(0) xprlst.append(sym) - # print(xprlst) + # # print(xprlst) word = '' else: word = word + sym - # print(word) + # # print(word) xprlst.pop() # удаляется добавленный пробел - # print('XPRLST:', xprlst) + # # print('XPRLST:', xprlst) punctset = set(string.punctuation) xprset = set(xprstr) - # print (funcset) + # # print (funcset) if xprset.issubset(punctset) or xprset.issubset(funcset): print('ERROR: no digits or functions') exit(0) @@ -123,190 +125,188 @@ def parse(xprstr): elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: pass - # print('ok', i) + # # print('ok', i) else: print('ERROR: unknown', xprlst[i], i) - # print(xprlst) + # # print(xprlst) return xprlst -def operate(operator, *args): - # print('def operate', operator, args) - for i in args: - if not( type(i) == float or type(i) == int): - print('ERROR: operate non float arguments', i, args) - exit(0) +def logargs(*args): + if len(args) == 1: + res = log(args[0]) + else: + res = log(args[0],args[1]) + return res + - if operator in dir(math): - result = funcdict[operator](*args) +def operate(operator, *args): + if operator in dir(math) and not operator in ['pow', 'log']: + result = funcdict[operator](args[-1]) + elif operator == "pow": + result = pow(args[-2], args[-1]) + elif operator == "log": + result = logargs(*args) elif operator == "+": - result = args[0] + args[1] + result = args[-2] + args[-1] elif operator == "-": - result = args[0] - args[1] + result = args[-2] - args[-1] elif operator == "*": - result = args[0] * args[1] + result = args[-2] * args[-1] elif operator == "//": - if args[1] != 0: - result = args[0] // args[1] + if args[-1] != 0: + result = args[-2] // args[-1] else: print('ERROR: division by zero') exit(0) elif operator == "/": - if args[1] != 0: - result = args[0] / args[1] + if args[-1] != 0: + result = args[-2] / args[-1] else: print('ERROR: division by zero') exit(0) elif operator == "%": - result = args[0] % args[1] + result = args[-2] % args[-1] elif operator == "^": - result = a**b + result = args[-2] ** args[-1] elif operator == "<=": - result = args[0] <= args[1] + result = args[-2] <= args[-1] elif operator == ">=": - result = args[0] >= args[1] + result = args[-2] >= args[-1] elif operator == "<": - result = args[0] < args[1] + result = args[-2] < args[-1] elif operator == ">": - result = args[0] > args[1] + result = args[-2] > args[-1] elif operator == "==": - result = args[0] == args[1] + result = args[-2] == args[-1] elif operator == "!=": - result = args[0] != args[1] + result = args[-2] != args[-1] else: print('ERROR: unknown math operator', operator) result = 0 -# if operator in oper: -# print('Operate:', a, operator, b, '=', result) -# elif operator in funclist: -# print('Operate:', operator, a, '=', result) return result +def prior(op1, op2): + priorset = [operlowest, operlow, opermid, operhi] + for i, data in enumerate(priorset): + # # print(op1, i,data,) + if op1 in data: + prior1 = i + if op2 in data: + prior2 = i + # # print(prior1 <= prior2) + return prior1 <= prior2 -# вычисление выражения без скобок -def calculate(xprlst): - # print('Calculate:', xprlst) - # перебор списка функций - for f in funclist: - if len(xprlst) <1: - print('ERROR: no arguments') - exit(0) - for i in range(xprlst.count(f)): - # print(f,'in funclist') - # print(f, xprlst.count(f)) - s = xprlst.index(f) - if ',' in xprlst: - # print (f,xprlst[s + 1], xprlst[s + 3]) - xprlst[s] = (operate(f, xprlst[s + 1], xprlst[s + 3])) - xprlst[s + 1] = '' - xprlst[s + 2] = '' - xprlst[s + 3] = '' - else: - # print('norm') - # print (f, xprlst[s + 1]) - xprlst[s] = (operate(f, xprlst[s + 1])) - xprlst[s + 1] = '' - wipe(xprlst) - - - # вычисление возведение в степень с реверсом списка - # print('^ count:', xprlst.count('^')) - if '^' in xprlst: - xprlst.reverse() - # print('reverse: ', xprlst) - while '^' in xprlst: - i = xprlst.index('^') - # print('i=', i) - xprlst[i] = xprlst[i + 1]**xprlst[i - 1] - # print(xprlst[i + 1], '^', xprlst[i - 1], '=', xprlst[i]) - xprlst[i - 1] = '' - xprlst[i + 1] = '' - # print(xprlst) - wipe(xprlst) - # print(xprlst) - xprlst.reverse() - - # перебор списка математических операций - for j in oper: - # print('operation=', j) - # print(xprlst) - i = 1 - while i < len(xprlst): - if xprlst[i] == j: - # print(xprlst[i-1], j, xprlst[i+1]) - xprlst[i] = operate(xprlst[i], xprlst[i - 1], xprlst[i + 1]) - xprlst[i - 1] = '' - xprlst[i + 1] = '' - # print(xprlst) - wipe(xprlst) - i = i - 1 - i = i + 1 - # print('Stop calculate:', float(xprlst[0])) - wipe(xprlst) - # print(xprlst) - # if len(xprlst) > 1: - # print('ERROR: missed operator') - # exit(0) - return xprlst - - -# очистка списка от пустых значений '' -def wipe(xprlst): - # print('WIPE', xprlst) - while '' in xprlst: - i = xprlst.index('') - xprlst.pop(i) - # print('WIPED', xprlst) - return xprlst -# поиск начала и конца выражения в скобках() -def brktindx(xprlst): - bl = xprlst.index('(') - br = xprlst.index(')') - s = xprlst[bl + 1:br] - # print('BL BR ', bl + 1, ' ', br, ' ', *s, sep='') - while '(' in s: - if s.count('(') == s.count(')'): - bl = xprlst.index('(', bl + 1) - br = xprlst.index(')', bl + 1) - s = xprlst[bl + 1:br] - # print('BL BR ', bl + 1, ' ', br, ' ', *s, sep='') - else: - br = xprlst.index(')', br + 1) - s = xprlst[bl:br + 1] - return(bl + 1, br) # основная функция def main(xpr): - # проверка скобок в строке - if xpr.count('(') != xpr.count(')'): - print('ERROR: brackets are not balanced') - exit(0) + # разбор строики в список xprlst = parse(xpr) - # print(*xprlst, sep=', ') - - # поиск скобок и вычисление в скобках - while '(' in xprlst: - a, b = brktindx(xprlst) - inbrackets = xprlst[a:b] - # print('in brackets to oper: ', inbrackets) - tmp = calculate(xprlst[a:b]) - # print (tmp) - xprlst = xprlst[0:a-1] + tmp + xprlst[b+1:] - - # print(xprlst) + # print(*xprlst, sep=' ') + + output=[] + stack=[] + for i in xprlst: + # print('-----------------------------------') + # print('i=',i) + + if type(i) == float or type(i) == int: + output.append(i) + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') + + elif i in oper: # '^', '*', '/', '+', '-' + + # print('in oper',i) + # print(oper) + if stack == []: # если стек пуст + # print('стек пуст. добваить оператор в стек') + stack.append(i) + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') + elif stack[-1] == '(': # если стек содержит ( + # print('( положить в стек') + stack.append(i) + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') + else: + # print('оператор:',i, '<=stack', stack[-1], prior(i, stack[-1])) + while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом + # print('пока на верху стэка оператор') + # print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) + output.append(stack.pop()) # переложить оператор из стека на выход + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') + if stack == []: break + stack.append(i) # иначе положить оператор в стек + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') + + + elif i == '(': + stack.append(i) + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') + + elif i == ')': + # print(i) + while stack[-1] != '(': # пока верх стека не равен ( + # print ('push stack', stack[-1]) + output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке + stack.pop() # удаление из стека ( + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') + elif i in funclist: + # print(i,'IN FUNCLIST помещаем в стек') + stack.append(i) + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') + # print('*******') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') + + stack.reverse() + pol = output + stack # poland + # print('POLAND:',pol) + + + # print('START CALCULATE *****************') + + output = [] + stack = [] + + for i in pol: + # print('---------------') + # print('i in pol = ',i) + + if i in oper: + tmp = operate(i, *stack) + stack.pop() + stack[-1] = tmp + # print('stack=',stack) + elif i in funclist and not i in ['pow','log']: + tmp = operate(i, *stack) + stack[-1] = tmp + # print('stack=',stack) + elif i in ['pow','log']: + # print('DOBL') + tmp = operate(i, *stack) + stack.pop() + stack[-1] = tmp + # print('stack=',stack) - # вычисление без скобок - result = calculate(xprlst) - # print(result) - return result[0] + else: + stack.append(i) + # print('stack=',stack) + return stack[0] print(main(xpr)) diff --git a/final_task/test.py b/final_task/test.py new file mode 100644 index 00000000..95983e94 --- /dev/null +++ b/final_task/test.py @@ -0,0 +1,43 @@ +op1='' +op2='' + + + + +def prior(op1, op2): + oper = ['^', '*', '/', '+', '-'] # 4 + operhi = ['^'] # 3 + opermid = ['*', '/'] # 2 + operlow = ['+', '-'] # 1 + operlowest = ['(',')'] # 0 + + priorset = [operlowest, operlow, opermid, operhi] + print(priorset) + + for i, data in enumerate(priorset): + print(op1, i,data,) + if op1 in data: + prior1 = i + if op2 in data: + prior2 = i + + + print('PRIOR', prior1, prior2) + return prior1 < prior2 + +#print(prior('+', '*')) + + + +def func(oper,*args): + print('reciv',oper,args) + print + + return + + +s = [1,2,3,4,5] + +func('sun',*s) + + From 6403067c13ab61c93a6d697597f06597545f5fa7 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sat, 20 Apr 2019 19:39:03 -0400 Subject: [PATCH 039/159] z --- final_task/pycalc.py | 132 ++++++++++++++++++++++--------------------- 1 file changed, 69 insertions(+), 63 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 74ef90a3..02b9eceb 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -38,7 +38,7 @@ oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!='] operhi = ['^'] + funclist # 3 -opermid = ['*', '/'] # 2 +opermid = ['*', '/', '%'] # 2 operlow = ['+', '-'] # 1 operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!='] # 0 @@ -61,38 +61,38 @@ def parse(xprstr): # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): - # # print(word) + # print(word) if word == 'pi': xprlst.append(pi) elif word == 'e': xprlst.append(e) elif word in funclist: - # # print(word, ' in math') + # print(word, ' in math') xprlst.append(word) elif word.replace('.', '').isdigit() and word.count('.') < 2: xprlst.append(float(word)) # elif word != '': elif word in split or word == '': pass - # # print('ok', word) + # print('ok', word) else: print('ERROR: wrong symbol "', word, sym, '"') exit(0) xprlst.append(sym) - # # print(xprlst) + # print(xprlst) word = '' else: word = word + sym - # # print(word) + # print(word) xprlst.pop() # удаляется добавленный пробел - # # print('XPRLST:', xprlst) + # print('XPRLST:', xprlst) punctset = set(string.punctuation) xprset = set(xprstr) - # # print (funcset) + # print (funcset) if xprset.issubset(punctset) or xprset.issubset(funcset): print('ERROR: no digits or functions') exit(0) @@ -125,10 +125,10 @@ def parse(xprstr): elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: pass - # # print('ok', i) + # print('ok', i) else: print('ERROR: unknown', xprlst[i], i) - # # print(xprlst) + # print(xprlst) return xprlst @@ -137,7 +137,7 @@ def logargs(*args): if len(args) == 1: res = log(args[0]) else: - res = log(args[0],args[1]) + res = log(args[0],args[2]) return res @@ -145,7 +145,7 @@ def operate(operator, *args): if operator in dir(math) and not operator in ['pow', 'log']: result = funcdict[operator](args[-1]) elif operator == "pow": - result = pow(args[-2], args[-1]) + result = pow(args[-3], args[-1]) elif operator == "log": result = logargs(*args) elif operator == "+": @@ -191,12 +191,12 @@ def operate(operator, *args): def prior(op1, op2): priorset = [operlowest, operlow, opermid, operhi] for i, data in enumerate(priorset): - # # print(op1, i,data,) + # print(op1, i,data,) if op1 in data: prior1 = i if op2 in data: prior2 = i - # # print(prior1 <= prior2) + # print(prior1 <= prior2) return prior1 <= prior2 @@ -209,103 +209,109 @@ def main(xpr): # разбор строики в список xprlst = parse(xpr) - # print(*xprlst, sep=' ') + print(*xprlst, sep=' ') output=[] stack=[] for i in xprlst: - # print('-----------------------------------') - # print('i=',i) + print('-----------------------------------') + print('i=',i) - if type(i) == float or type(i) == int: + if type(i) == float or type(i) == int or i == ',': output.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') elif i in oper: # '^', '*', '/', '+', '-' - # print('in oper',i) - # print(oper) + print('in oper',i) + print(oper) if stack == []: # если стек пуст - # print('стек пуст. добваить оператор в стек') + print('стек пуст. добваить оператор в стек') stack.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') elif stack[-1] == '(': # если стек содержит ( - # print('( положить в стек') + print('( положить в стек') stack.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') else: - # print('оператор:',i, '<=stack', stack[-1], prior(i, stack[-1])) + print('оператор:',i, '<=stack', stack[-1], prior(i, stack[-1])) while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом - # print('пока на верху стэка оператор') - # print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) + print('пока на верху стэка оператор') + print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) output.append(stack.pop()) # переложить оператор из стека на выход - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') if stack == []: break stack.append(i) # иначе положить оператор в стек - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') elif i == '(': stack.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') elif i == ')': - # print(i) + print(i) while stack[-1] != '(': # пока верх стека не равен ( - # print ('push stack', stack[-1]) + print ('push stack', stack[-1]) output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке stack.pop() # удаление из стека ( - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') elif i in funclist: - # print(i,'IN FUNCLIST помещаем в стек') + print(i,'IN FUNCLIST помещаем в стек') stack.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') - # print('*******') - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') + print('*******') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') stack.reverse() pol = output + stack # poland - # print('POLAND:',pol) + print('POLAND:',pol) - # print('START CALCULATE *****************') + print('START CALCULATE *****************') output = [] stack = [] for i in pol: - # print('---------------') - # print('i in pol = ',i) + print('---------------') + print('i in pol = ',i) - if i in oper: + if i in oper+['pow','log']: tmp = operate(i, *stack) - stack.pop() - stack[-1] = tmp - # print('stack=',stack) + if ',' in stack: + stack.pop() + stack.pop() + stack[0] = tmp + else: + stack.pop() + stack[-1] = tmp + print('stack=',stack) elif i in funclist and not i in ['pow','log']: tmp = operate(i, *stack) stack[-1] = tmp - # print('stack=',stack) - elif i in ['pow','log']: - # print('DOBL') - tmp = operate(i, *stack) - stack.pop() - stack[-1] = tmp - # print('stack=',stack) + print('stack=',stack) + # elif i in ['pow','log']: + # print('DOBL') + # tmp = operate(i, *stack) + # stack.pop() + # stack.pop() + # stack[-1] = tmp + # print('stack=',stack) else: stack.append(i) - # print('stack=',stack) + print('stack=',stack) return stack[0] From 8ba5c15eae26b86453a48bc8f5ff8b61bf35e4b9 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sat, 20 Apr 2019 19:44:32 -0400 Subject: [PATCH 040/159] z --- final_task/pycalc.py | 104 +++++++++++++++++++++---------------------- 1 file changed, 52 insertions(+), 52 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 02b9eceb..7eba7985 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -61,38 +61,38 @@ def parse(xprstr): # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): - # print(word) + # # print(word) if word == 'pi': xprlst.append(pi) elif word == 'e': xprlst.append(e) elif word in funclist: - # print(word, ' in math') + # # print(word, ' in math') xprlst.append(word) elif word.replace('.', '').isdigit() and word.count('.') < 2: xprlst.append(float(word)) # elif word != '': elif word in split or word == '': pass - # print('ok', word) + # # print('ok', word) else: print('ERROR: wrong symbol "', word, sym, '"') exit(0) xprlst.append(sym) - # print(xprlst) + # # print(xprlst) word = '' else: word = word + sym - # print(word) + # # print(word) xprlst.pop() # удаляется добавленный пробел - # print('XPRLST:', xprlst) + # # print('XPRLST:', xprlst) punctset = set(string.punctuation) xprset = set(xprstr) - # print (funcset) + # # print (funcset) if xprset.issubset(punctset) or xprset.issubset(funcset): print('ERROR: no digits or functions') exit(0) @@ -125,10 +125,10 @@ def parse(xprstr): elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: pass - # print('ok', i) + # # print('ok', i) else: print('ERROR: unknown', xprlst[i], i) - # print(xprlst) + # # print(xprlst) return xprlst @@ -191,12 +191,12 @@ def operate(operator, *args): def prior(op1, op2): priorset = [operlowest, operlow, opermid, operhi] for i, data in enumerate(priorset): - # print(op1, i,data,) + # # print(op1, i,data,) if op1 in data: prior1 = i if op2 in data: prior2 = i - # print(prior1 <= prior2) + # # print(prior1 <= prior2) return prior1 <= prior2 @@ -209,82 +209,82 @@ def main(xpr): # разбор строики в список xprlst = parse(xpr) - print(*xprlst, sep=' ') + # print(*xprlst, sep=' ') output=[] stack=[] for i in xprlst: - print('-----------------------------------') - print('i=',i) + # print('-----------------------------------') + # print('i=',i) if type(i) == float or type(i) == int or i == ',': output.append(i) - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') elif i in oper: # '^', '*', '/', '+', '-' - print('in oper',i) - print(oper) + # print('in oper',i) + # print(oper) if stack == []: # если стек пуст - print('стек пуст. добваить оператор в стек') + # print('стек пуст. добваить оператор в стек') stack.append(i) - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') elif stack[-1] == '(': # если стек содержит ( - print('( положить в стек') + # print('( положить в стек') stack.append(i) - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') else: - print('оператор:',i, '<=stack', stack[-1], prior(i, stack[-1])) + # print('оператор:',i, '<=stack', stack[-1], prior(i, stack[-1])) while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом - print('пока на верху стэка оператор') - print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) + # print('пока на верху стэка оператор') + # print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) output.append(stack.pop()) # переложить оператор из стека на выход - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') if stack == []: break stack.append(i) # иначе положить оператор в стек - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') elif i == '(': stack.append(i) - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') elif i == ')': - print(i) + # print(i) while stack[-1] != '(': # пока верх стека не равен ( - print ('push stack', stack[-1]) + # print ('push stack', stack[-1]) output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке stack.pop() # удаление из стека ( - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') elif i in funclist: - print(i,'IN FUNCLIST помещаем в стек') + # print(i,'IN FUNCLIST помещаем в стек') stack.append(i) - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') - print('*******') - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') + # print('*******') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') stack.reverse() pol = output + stack # poland - print('POLAND:',pol) + # print('POLAND:',pol) - print('START CALCULATE *****************') + # print('START CALCULATE *****************') output = [] stack = [] for i in pol: - print('---------------') - print('i in pol = ',i) + # print('---------------') + # print('i in pol = ',i) if i in oper+['pow','log']: tmp = operate(i, *stack) @@ -295,23 +295,23 @@ def main(xpr): else: stack.pop() stack[-1] = tmp - print('stack=',stack) + # print('stack=',stack) elif i in funclist and not i in ['pow','log']: tmp = operate(i, *stack) stack[-1] = tmp - print('stack=',stack) + # print('stack=',stack) # elif i in ['pow','log']: - # print('DOBL') + # # print('DOBL') # tmp = operate(i, *stack) # stack.pop() # stack.pop() # stack[-1] = tmp - # print('stack=',stack) + # # print('stack=',stack) else: stack.append(i) - print('stack=',stack) + # print('stack=',stack) return stack[0] From 2e75000c6b9d3e6ff160ffabffce1fae528f5d97 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sat, 20 Apr 2019 21:00:19 -0400 Subject: [PATCH 041/159] dd --- final_task/pycalc.py | 61 ++++++++++++++++++++++++++++++++------------ 1 file changed, 44 insertions(+), 17 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 7eba7985..9b920f63 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -17,13 +17,6 @@ split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') -# проверка недопустимых символов -exset = {'"', '# ', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} -xprset = set(xpr) -if not exset.isdisjoint(xprset): - print('ERROR: unknown symbol') - exit(0) - funclist = dir(math)+['abs', 'round'] # list of math functions names funcdict = math.__dict__ # dict of math functions funcdict['abs'] = abs @@ -46,18 +39,39 @@ # разбор строки на элементы списка def parse(xprstr): word = '' + + # проверка недопустимых символов + exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} + xprset = set(xprstr) + if not exset.isdisjoint(xprset): + print('ERROR: unknown symbol') + exit(0) # проверка скобок в строке if xpr.count('(') != xpr.count(')'): print('ERROR: brackets are not balanced') exit(0) - xprstr = xprstr.replace(' ', '') + + # проверка если состоит только из знаков пунктуации + punctset = set(string.punctuation) + xprset = set(xprstr) + if xprset.issubset(punctset) or xprset.issubset(funcset): + print('ERROR: no digits or functions') + exit(0) + + xprstr = xprstr.replace(' -', '-') xprstr = xprstr.replace('--', '+') xprstr = xprstr.replace('++', '+') xprstr = xprstr.replace('+-', '-') xprstr = xprstr.replace('-+', '-') + if xprstr[0] == '+': xprstr = xprstr[1:] + # проверка пробелов + if xpr.count(' ') > 0: + print('ERROR: useles spaces') + exit(0) + # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): @@ -76,7 +90,7 @@ def parse(xprstr): pass # # print('ok', word) else: - print('ERROR: wrong symbol "', word, sym, '"') + print('ERROR: wrong symbol "', word, '"') exit(0) xprlst.append(sym) # # print(xprlst) @@ -84,18 +98,10 @@ def parse(xprstr): else: word = word + sym # # print(word) - xprlst.pop() # удаляется добавленный пробел - # # print('XPRLST:', xprlst) - punctset = set(string.punctuation) - xprset = set(xprstr) - # # print (funcset) - if xprset.issubset(punctset) or xprset.issubset(funcset): - print('ERROR: no digits or functions') - exit(0) for i, data in enumerate(xprlst): if xprlst[i] == '/' and xprlst[i + 1] == '/': xprlst[i] = '//' @@ -128,6 +134,16 @@ def parse(xprstr): # # print('ok', i) else: print('ERROR: unknown', xprlst[i], i) + + + xprset = set(xprlst) + if xprset.issubset(funcset) or xprset.issubset(operset): + print('ERROR: только функция') + exit(0) + + + + # # print(xprlst) return xprlst @@ -142,6 +158,12 @@ def logargs(*args): def operate(operator, *args): + + for i in args: + if not (type(i) == float or type(i) == int): + print('ERROR: operate non digits') + exit(0) + if operator in dir(math) and not operator in ['pow', 'log']: result = funcdict[operator](args[-1]) elif operator == "pow": @@ -287,6 +309,11 @@ def main(xpr): # print('i in pol = ',i) if i in oper+['pow','log']: + + if len(stack) < 2: + print('ERROR: no argument') + exit(0) + tmp = operate(i, *stack) if ',' in stack: stack.pop() From 148da2e0caf2512690f74e60efd3002c1f4bcb9d Mon Sep 17 00:00:00 2001 From: novash-k Date: Sat, 20 Apr 2019 21:05:57 -0400 Subject: [PATCH 042/159] dd --- final_task/pycalc.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 9b920f63..d815814c 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -57,8 +57,14 @@ def parse(xprstr): if xprset.issubset(punctset) or xprset.issubset(funcset): print('ERROR: no digits or functions') exit(0) - + xprstr = xprstr.replace(' ', ' ') + xprstr = xprstr.replace(', ', ',') + xprstr = xprstr.replace(' *', '*') + xprstr = xprstr.replace('* ', '*') + xprstr = xprstr.replace(' +', '+') + xprstr = xprstr.replace('+ ', '+') xprstr = xprstr.replace(' -', '-') + xprstr = xprstr.replace('- ', '-') xprstr = xprstr.replace('--', '+') xprstr = xprstr.replace('++', '+') xprstr = xprstr.replace('+-', '-') From 7cc8318085434a33a2bd09782a825dc79f643621 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sat, 20 Apr 2019 21:16:07 -0400 Subject: [PATCH 043/159] dd --- final_task/pycalc.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index d815814c..10884922 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -57,6 +57,7 @@ def parse(xprstr): if xprset.issubset(punctset) or xprset.issubset(funcset): print('ERROR: no digits or functions') exit(0) + xprstr = xprstr.replace(' ', ' ') xprstr = xprstr.replace(', ', ',') xprstr = xprstr.replace(' *', '*') @@ -70,11 +71,13 @@ def parse(xprstr): xprstr = xprstr.replace('+-', '-') xprstr = xprstr.replace('-+', '-') + # print(xprstr) + if xprstr[0] == '+': xprstr = xprstr[1:] # проверка пробелов - if xpr.count(' ') > 0: + if xprstr.count(' ') > 0: print('ERROR: useles spaces') exit(0) @@ -166,7 +169,7 @@ def logargs(*args): def operate(operator, *args): for i in args: - if not (type(i) == float or type(i) == int): + if not (type(i) == float or type(i) == int or i == ','): print('ERROR: operate non digits') exit(0) @@ -228,9 +231,6 @@ def prior(op1, op2): return prior1 <= prior2 - - - # основная функция def main(xpr): From d5e2806b2665537442ee03c3419d1b603416f123 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 21 Apr 2019 10:42:52 -0400 Subject: [PATCH 044/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20log(a,b)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 66 ++++++++++++++++++++++++++++++++++++-------- 1 file changed, 54 insertions(+), 12 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 10884922..fc2777c5 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -29,11 +29,11 @@ result = 0. funcset=set(funclist) -oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!='] +oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', ','] operhi = ['^'] + funclist # 3 opermid = ['*', '/', '%'] # 2 operlow = ['+', '-'] # 1 -operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!='] # 0 +operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 # разбор строки на элементы списка @@ -159,10 +159,12 @@ def parse(xprstr): def logargs(*args): + # print('START logoargs', args) if len(args) == 1: res = log(args[0]) else: - res = log(args[0],args[2]) + res = log(args[-3],args[-1]) + # print('RETURN logoargs', res) return res @@ -245,12 +247,26 @@ def main(xpr): # print('-----------------------------------') # print('i=',i) - if type(i) == float or type(i) == int or i == ',': + + if type(i) == float or type(i) == int: + output.append(i) + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') + + if i == ',': + if stack != []: + while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом + # print('пока на верху стэка оператор') + # print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) + output.append(stack.pop()) # переложить оператор из стека на выход + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') + if stack == []: break output.append(i) # print('output=',*output,sep=' ') # print('stack=',*stack,sep=' ') - elif i in oper: # '^', '*', '/', '+', '-' + elif i in oper and i != ',': # '^', '*', '/', '+', '-' # print('in oper',i) # print(oper) @@ -274,10 +290,19 @@ def main(xpr): # print('stack=',*stack,sep=' ') if stack == []: break stack.append(i) # иначе положить оператор в стек + + # if i ==',': + # output.append(i) # если это , то на выход + # else: + # stack.append(i) # иначе положить оператор в стек + + # print('output=',*output,sep=' ') # print('stack=',*stack,sep=' ') + + elif i == '(': stack.append(i) # print('output=',*output,sep=' ') @@ -302,7 +327,7 @@ def main(xpr): stack.reverse() pol = output + stack # poland - # print('POLAND:',pol) + # print('POLAND:',*pol,sep=' ') # print('START CALCULATE *****************') @@ -314,20 +339,27 @@ def main(xpr): # print('---------------') # print('i in pol = ',i) - if i in oper+['pow','log']: + if i in oper+['pow','log'] and i != ',': - if len(stack) < 2: - print('ERROR: no argument') - exit(0) + + # print(stack,'+++++++++ to pow or log') tmp = operate(i, *stack) + + # print(i,'=',tmp) + if ',' in stack: stack.pop() stack.pop() - stack[0] = tmp + stack.pop() + stack.append(tmp) + elif i in oper: + stack.pop() + stack.pop() + stack.append(tmp) else: stack.pop() - stack[-1] = tmp + stack.append(tmp) # print('stack=',stack) elif i in funclist and not i in ['pow','log']: tmp = operate(i, *stack) @@ -348,4 +380,14 @@ def main(xpr): return stack[0] +#EVAL TEST +test = xpr +test = test.replace('^', '**') +test = test.replace(' ', '') +test = test.replace(', ', '.') + + + print(main(xpr)) + +# print ('EVAL:',test, '=',eval(test)) From 30880322454946ddc8e7ce6701de1fe787ac8771 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 21 Apr 2019 11:29:06 -0400 Subject: [PATCH 045/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20log(a,b).=20=D0=BD=D0=B5=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=B0=D0=B5=D1=82=20a^b^c?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index fc2777c5..2257b912 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -177,10 +177,21 @@ def operate(operator, *args): if operator in dir(math) and not operator in ['pow', 'log']: result = funcdict[operator](args[-1]) + + + elif operator == "pow": result = pow(args[-3], args[-1]) + + + elif operator == "log": result = logargs(*args) + + + elif len(args) < 2: + print('ERROR: no arguments') + exit(0) elif operator == "+": result = args[-2] + args[-1] elif operator == "-": @@ -327,6 +338,8 @@ def main(xpr): stack.reverse() pol = output + stack # poland + + # print(xpr) # print('POLAND:',*pol,sep=' ') @@ -348,7 +361,7 @@ def main(xpr): # print(i,'=',tmp) - if ',' in stack: + if stack[-2]==',': stack.pop() stack.pop() stack.pop() From 5afe22f14a669d0df66781febf91bfba70ff3a5e Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 21 Apr 2019 11:38:13 -0400 Subject: [PATCH 046/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20log(a,b).=20=D0=BD=D0=B5=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=B0=D0=B5=D1=82=20a^b^c=20=D0=BF=D0=B5=D1=80?= =?UTF-8?q?=D0=B5=D0=B7=D0=B0=D0=BB=D0=B8=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 2257b912..6052a4cc 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -399,7 +399,7 @@ def main(xpr): test = test.replace(' ', '') test = test.replace(', ', '.') - +# test print(main(xpr)) From c6f61cb5bace63d2f3bbc0a33596be905bfff350 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 21 Apr 2019 12:08:10 -0400 Subject: [PATCH 047/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20log(a,b).=20=D0=BD=D0=B5=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=B0=D0=B5=D1=82=20a^b^c?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 132 +++++++++++++++++++++---------------------- 1 file changed, 66 insertions(+), 66 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 6052a4cc..740b416c 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -71,7 +71,7 @@ def parse(xprstr): xprstr = xprstr.replace('+-', '-') xprstr = xprstr.replace('-+', '-') - # print(xprstr) + print(xprstr) if xprstr[0] == '+': xprstr = xprstr[1:] @@ -84,29 +84,29 @@ def parse(xprstr): # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): - # # print(word) + # print(word) if word == 'pi': xprlst.append(pi) elif word == 'e': xprlst.append(e) elif word in funclist: - # # print(word, ' in math') + # print(word, ' in math') xprlst.append(word) elif word.replace('.', '').isdigit() and word.count('.') < 2: xprlst.append(float(word)) # elif word != '': elif word in split or word == '': pass - # # print('ok', word) + # print('ok', word) else: print('ERROR: wrong symbol "', word, '"') exit(0) xprlst.append(sym) - # # print(xprlst) + # print(xprlst) word = '' else: word = word + sym - # # print(word) + # print(word) xprlst.pop() # удаляется добавленный пробел @@ -140,7 +140,7 @@ def parse(xprstr): elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: pass - # # print('ok', i) + # print('ok', i) else: print('ERROR: unknown', xprlst[i], i) @@ -153,18 +153,18 @@ def parse(xprstr): - # # print(xprlst) + # print(xprlst) return xprlst def logargs(*args): - # print('START logoargs', args) - if len(args) == 1: - res = log(args[0]) - else: + print('START logoargs', args) + if ',' in args: res = log(args[-3],args[-1]) - # print('RETURN logoargs', res) + else: + res = log(args[-1]) + print('RETURN logoargs', res) return res @@ -235,12 +235,12 @@ def operate(operator, *args): def prior(op1, op2): priorset = [operlowest, operlow, opermid, operhi] for i, data in enumerate(priorset): - # # print(op1, i,data,) + # print(op1, i,data,) if op1 in data: prior1 = i if op2 in data: prior2 = i - # # print(prior1 <= prior2) + # print(prior1 <= prior2) return prior1 <= prior2 @@ -250,55 +250,55 @@ def main(xpr): # разбор строики в список xprlst = parse(xpr) - # print(*xprlst, sep=' ') + print(*xprlst, sep=' ') output=[] stack=[] for i in xprlst: - # print('-----------------------------------') - # print('i=',i) + print('-----------------------------------') + print('i=',i) if type(i) == float or type(i) == int: output.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') if i == ',': if stack != []: while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом - # print('пока на верху стэка оператор') - # print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) + print('пока на верху стэка оператор') + print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) output.append(stack.pop()) # переложить оператор из стека на выход - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') if stack == []: break output.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') elif i in oper and i != ',': # '^', '*', '/', '+', '-' - # print('in oper',i) - # print(oper) + print('in oper',i) + print(oper) if stack == []: # если стек пуст - # print('стек пуст. добваить оператор в стек') + print('стек пуст. добваить оператор в стек') stack.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') elif stack[-1] == '(': # если стек содержит ( - # print('( положить в стек') + print('( положить в стек') stack.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') else: - # print('оператор:',i, '<=stack', stack[-1], prior(i, stack[-1])) + print('оператор:',i, '<=stack', stack[-1], prior(i, stack[-1])) while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом - # print('пока на верху стэка оператор') - # print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) + print('пока на верху стэка оператор') + print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) output.append(stack.pop()) # переложить оператор из стека на выход - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') if stack == []: break stack.append(i) # иначе положить оператор в стек @@ -308,58 +308,58 @@ def main(xpr): # stack.append(i) # иначе положить оператор в стек - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') elif i == '(': stack.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') elif i == ')': - # print(i) + print(i) while stack[-1] != '(': # пока верх стека не равен ( - # print ('push stack', stack[-1]) + print ('push stack', stack[-1]) output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке stack.pop() # удаление из стека ( - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') elif i in funclist: - # print(i,'IN FUNCLIST помещаем в стек') + print(i,'IN FUNCLIST помещаем в стек') stack.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') - # print('*******') - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') + print('*******') + print('output=',*output,sep=' ') + print('stack=',*stack,sep=' ') stack.reverse() pol = output + stack # poland - # print(xpr) - # print('POLAND:',*pol,sep=' ') + print(xpr) + print('POLAND:',*pol,sep=' ') - # print('START CALCULATE *****************') + print('START CALCULATE *****************') output = [] stack = [] for i in pol: - # print('---------------') - # print('i in pol = ',i) + print('---------------') + print('i in pol = ',i) if i in oper+['pow','log'] and i != ',': - # print(stack,'+++++++++ to pow or log') + print(stack,'+++++++++ to pow or log') tmp = operate(i, *stack) - # print(i,'=',tmp) + print(i,'=',tmp) if stack[-2]==',': stack.pop() @@ -373,23 +373,23 @@ def main(xpr): else: stack.pop() stack.append(tmp) - # print('stack=',stack) + print('stack=',stack) elif i in funclist and not i in ['pow','log']: tmp = operate(i, *stack) stack[-1] = tmp - # print('stack=',stack) + print('stack=',stack) # elif i in ['pow','log']: - # # print('DOBL') + # print('DOBL') # tmp = operate(i, *stack) # stack.pop() # stack.pop() # stack[-1] = tmp - # # print('stack=',stack) + # print('stack=',stack) else: stack.append(i) - # print('stack=',stack) + print('stack=',stack) return stack[0] @@ -403,4 +403,4 @@ def main(xpr): print(main(xpr)) -# print ('EVAL:',test, '=',eval(test)) +print ('EVAL:',test, '=',eval(test)) From 7f5c9b0336d2d9f3966dc03f2bed466095176a02 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 21 Apr 2019 12:12:23 -0400 Subject: [PATCH 048/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20log(a,b).=20=D0=BD=D0=B5=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=B0=D0=B5=D1=82=20a^b^c?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 126 +++++++++++++++++++++---------------------- 1 file changed, 63 insertions(+), 63 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 740b416c..c94214b5 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -71,7 +71,7 @@ def parse(xprstr): xprstr = xprstr.replace('+-', '-') xprstr = xprstr.replace('-+', '-') - print(xprstr) + # print(xprstr) if xprstr[0] == '+': xprstr = xprstr[1:] @@ -84,29 +84,29 @@ def parse(xprstr): # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): - # print(word) + # # print(word) if word == 'pi': xprlst.append(pi) elif word == 'e': xprlst.append(e) elif word in funclist: - # print(word, ' in math') + # # print(word, ' in math') xprlst.append(word) elif word.replace('.', '').isdigit() and word.count('.') < 2: xprlst.append(float(word)) # elif word != '': elif word in split or word == '': pass - # print('ok', word) + # # print('ok', word) else: print('ERROR: wrong symbol "', word, '"') exit(0) xprlst.append(sym) - # print(xprlst) + # # print(xprlst) word = '' else: word = word + sym - # print(word) + # # print(word) xprlst.pop() # удаляется добавленный пробел @@ -140,7 +140,7 @@ def parse(xprstr): elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: pass - # print('ok', i) + # # print('ok', i) else: print('ERROR: unknown', xprlst[i], i) @@ -153,18 +153,18 @@ def parse(xprstr): - # print(xprlst) + # # print(xprlst) return xprlst def logargs(*args): - print('START logoargs', args) + # print('START logoargs', args) if ',' in args: res = log(args[-3],args[-1]) else: res = log(args[-1]) - print('RETURN logoargs', res) + # print('RETURN logoargs', res) return res @@ -235,12 +235,12 @@ def operate(operator, *args): def prior(op1, op2): priorset = [operlowest, operlow, opermid, operhi] for i, data in enumerate(priorset): - # print(op1, i,data,) + # # print(op1, i,data,) if op1 in data: prior1 = i if op2 in data: prior2 = i - # print(prior1 <= prior2) + # # print(prior1 <= prior2) return prior1 <= prior2 @@ -250,55 +250,55 @@ def main(xpr): # разбор строики в список xprlst = parse(xpr) - print(*xprlst, sep=' ') + # print(*xprlst, sep=' ') output=[] stack=[] for i in xprlst: - print('-----------------------------------') - print('i=',i) + # print('-----------------------------------') + # print('i=',i) if type(i) == float or type(i) == int: output.append(i) - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') if i == ',': if stack != []: while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом - print('пока на верху стэка оператор') - print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) + # print('пока на верху стэка оператор') + # print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) output.append(stack.pop()) # переложить оператор из стека на выход - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') if stack == []: break output.append(i) - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') elif i in oper and i != ',': # '^', '*', '/', '+', '-' - print('in oper',i) - print(oper) + # print('in oper',i) + # print(oper) if stack == []: # если стек пуст - print('стек пуст. добваить оператор в стек') + # print('стек пуст. добваить оператор в стек') stack.append(i) - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') elif stack[-1] == '(': # если стек содержит ( - print('( положить в стек') + # print('( положить в стек') stack.append(i) - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') else: - print('оператор:',i, '<=stack', stack[-1], prior(i, stack[-1])) + # print('оператор:',i, '<=stack', stack[-1], prior(i, stack[-1])) while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом - print('пока на верху стэка оператор') - print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) + # print('пока на верху стэка оператор') + # print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) output.append(stack.pop()) # переложить оператор из стека на выход - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') if stack == []: break stack.append(i) # иначе положить оператор в стек @@ -308,58 +308,58 @@ def main(xpr): # stack.append(i) # иначе положить оператор в стек - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') elif i == '(': stack.append(i) - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') elif i == ')': - print(i) + # print(i) while stack[-1] != '(': # пока верх стека не равен ( - print ('push stack', stack[-1]) + # print ('push stack', stack[-1]) output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке stack.pop() # удаление из стека ( - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') elif i in funclist: - print(i,'IN FUNCLIST помещаем в стек') + # print(i,'IN FUNCLIST помещаем в стек') stack.append(i) - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') - print('*******') - print('output=',*output,sep=' ') - print('stack=',*stack,sep=' ') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') + # print('*******') + # print('output=',*output,sep=' ') + # print('stack=',*stack,sep=' ') stack.reverse() pol = output + stack # poland - print(xpr) - print('POLAND:',*pol,sep=' ') + # print(xpr) + # print('POLAND:',*pol,sep=' ') - print('START CALCULATE *****************') + # print('START CALCULATE *****************') output = [] stack = [] for i in pol: - print('---------------') - print('i in pol = ',i) + # print('---------------') + # print('i in pol = ',i) if i in oper+['pow','log'] and i != ',': - print(stack,'+++++++++ to pow or log') + # print(stack,'+++++++++ to pow or log') tmp = operate(i, *stack) - print(i,'=',tmp) + # print(i,'=',tmp) if stack[-2]==',': stack.pop() @@ -373,23 +373,23 @@ def main(xpr): else: stack.pop() stack.append(tmp) - print('stack=',stack) + # print('stack=',stack) elif i in funclist and not i in ['pow','log']: tmp = operate(i, *stack) stack[-1] = tmp - print('stack=',stack) + # print('stack=',stack) # elif i in ['pow','log']: - # print('DOBL') + # # print('DOBL') # tmp = operate(i, *stack) # stack.pop() # stack.pop() # stack[-1] = tmp - # print('stack=',stack) + # # print('stack=',stack) else: stack.append(i) - print('stack=',stack) + # print('stack=',stack) return stack[0] @@ -403,4 +403,4 @@ def main(xpr): print(main(xpr)) -print ('EVAL:',test, '=',eval(test)) +# print ('EVAL:',test, '=',eval(test)) From 56e4dddeb1b7020ca5a3668137afb0790fca0427 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 21 Apr 2019 12:22:18 -0400 Subject: [PATCH 049/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20log(a,b).=20=D0=BD=D0=B5=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=B0=D0=B5=D1=82=20a^b^c?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index c94214b5..bd7dcf48 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -361,11 +361,12 @@ def main(xpr): # print(i,'=',tmp) - if stack[-2]==',': - stack.pop() - stack.pop() - stack.pop() - stack.append(tmp) + if ',' in stack: + if stack[-2]==',': + stack.pop() + stack.pop() + stack.pop() + stack.append(tmp) elif i in oper: stack.pop() stack.pop() From ddb330da3509d84b88b5764723bbb47982443155 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 21 Apr 2019 12:37:35 -0400 Subject: [PATCH 050/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20log(a,b).=20=D0=BD=D0=B5=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=B0=D0=B5=D1=82=20a^b^c?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index bd7dcf48..a58c462a 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -181,8 +181,11 @@ def operate(operator, *args): elif operator == "pow": - result = pow(args[-3], args[-1]) - + if len(args) == 3: + result = pow(args[-3], args[-1]) + else: + print('ERROR: wrong arguments') + exit(0) elif operator == "log": @@ -361,7 +364,7 @@ def main(xpr): # print(i,'=',tmp) - if ',' in stack: + if ',' in stack and i in ['pow', 'log']: if stack[-2]==',': stack.pop() stack.pop() From a24771c2f8fac2b378b62a0bd9388d0bae709594 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 21 Apr 2019 15:33:54 -0400 Subject: [PATCH 051/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=202^3^4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 45 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index a58c462a..35901420 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -16,6 +16,7 @@ splitset = {} split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') +splitset = set(split) funclist = dir(math)+['abs', 'round'] # list of math functions names funcdict = math.__dict__ # dict of math functions @@ -30,6 +31,7 @@ funcset=set(funclist) oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', ','] +operset = set(oper) operhi = ['^'] + funclist # 3 opermid = ['*', '/', '%'] # 2 operlow = ['+', '-'] # 1 @@ -80,6 +82,44 @@ def parse(xprstr): if xprstr.count(' ') > 0: print('ERROR: useles spaces') exit(0) + + + # добавление скобок для возведения в степень 2^3^4 + l=0 + r=len(xprstr) + for x in range(xprstr.count('^')): + r = xprstr.rindex('^',0,r) + # print('r=', r,' ',xprstr[:r]) + l = xprstr.rindex('^',0,r)+1 + # print('l=',l,'r=',r,' ',xprstr[l:r]) + tmp = xprstr[l:r] + # print('tmp=',tmp) + tmpset = set(tmp) + # print('tmpset', tmpset) + # print('operset', operset) + if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): + # print('нада скобки для степени') + xprstr=xprstr[:l]+'('+xprstr[l:] + # print(xprstr) + + l=r+2 + # print(xprstr[l:]) + + r=len(xprstr) + for i,data in enumerate(xprstr[l:]): + if data in split and data != '(': + r = l+i + break + # print('l=',l,'r=',r,' ', xprstr[l:r]) + tmp = xprstr[l:r] + # print(tmp) + xprstr=xprstr[:r]+')'+xprstr[r:] + # print(xprstr) + else: + # print('НЕ надо скобки',l,r) + r = l + + # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел @@ -151,9 +191,10 @@ def parse(xprstr): exit(0) + # # print(*xprlst,sep=' ') - # # print(xprlst) + return xprlst @@ -161,7 +202,7 @@ def parse(xprstr): def logargs(*args): # print('START logoargs', args) if ',' in args: - res = log(args[-3],args[-1]) + res = log(args[-3], args[-1]) else: res = log(args[-1]) # print('RETURN logoargs', res) From bd2c1442d1bb8d6bca9425d9d4ae2b30628f07af Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 21 Apr 2019 15:47:17 -0400 Subject: [PATCH 052/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=202^3^4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 151 ++++++++++++++++++++++--------------------- 1 file changed, 77 insertions(+), 74 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 35901420..67051a44 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -73,7 +73,7 @@ def parse(xprstr): xprstr = xprstr.replace('+-', '-') xprstr = xprstr.replace('-+', '-') - # print(xprstr) + # # print(xprstr) if xprstr[0] == '+': xprstr = xprstr[1:] @@ -87,36 +87,39 @@ def parse(xprstr): # добавление скобок для возведения в степень 2^3^4 l=0 r=len(xprstr) + for x in range(xprstr.count('^')): r = xprstr.rindex('^',0,r) # print('r=', r,' ',xprstr[:r]) + if xprstr[:r].count('^') ==0: + break l = xprstr.rindex('^',0,r)+1 - # print('l=',l,'r=',r,' ',xprstr[l:r]) + # # print('l=',l,'r=',r,' ',xprstr[l:r]) tmp = xprstr[l:r] - # print('tmp=',tmp) + # # print('tmp=',tmp) tmpset = set(tmp) - # print('tmpset', tmpset) - # print('operset', operset) + # # print('tmpset', tmpset) + # # print('operset', operset) if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): - # print('нада скобки для степени') + # # print('нада скобки для степени') xprstr=xprstr[:l]+'('+xprstr[l:] - # print(xprstr) + # # print(xprstr) l=r+2 - # print(xprstr[l:]) + # # print(xprstr[l:]) r=len(xprstr) for i,data in enumerate(xprstr[l:]): if data in split and data != '(': r = l+i break - # print('l=',l,'r=',r,' ', xprstr[l:r]) + # # print('l=',l,'r=',r,' ', xprstr[l:r]) tmp = xprstr[l:r] - # print(tmp) + # # print(tmp) xprstr=xprstr[:r]+')'+xprstr[r:] - # print(xprstr) + # # print(xprstr) else: - # print('НЕ надо скобки',l,r) + # # print('НЕ надо скобки',l,r) r = l @@ -124,29 +127,29 @@ def parse(xprstr): # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): - # # print(word) + # # # print(word) if word == 'pi': xprlst.append(pi) elif word == 'e': xprlst.append(e) elif word in funclist: - # # print(word, ' in math') + # # # print(word, ' in math') xprlst.append(word) elif word.replace('.', '').isdigit() and word.count('.') < 2: xprlst.append(float(word)) # elif word != '': elif word in split or word == '': pass - # # print('ok', word) + # # # print('ok', word) else: print('ERROR: wrong symbol "', word, '"') exit(0) xprlst.append(sym) - # # print(xprlst) + # # # print(xprlst) word = '' else: word = word + sym - # # print(word) + # # # print(word) xprlst.pop() # удаляется добавленный пробел @@ -180,7 +183,7 @@ def parse(xprstr): elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: pass - # # print('ok', i) + # # # print('ok', i) else: print('ERROR: unknown', xprlst[i], i) @@ -191,7 +194,7 @@ def parse(xprstr): exit(0) - # # print(*xprlst,sep=' ') + # # # print(*xprlst,sep=' ') @@ -200,12 +203,12 @@ def parse(xprstr): def logargs(*args): - # print('START logoargs', args) + # # print('START logoargs', args) if ',' in args: res = log(args[-3], args[-1]) else: res = log(args[-1]) - # print('RETURN logoargs', res) + # # print('RETURN logoargs', res) return res @@ -279,12 +282,12 @@ def operate(operator, *args): def prior(op1, op2): priorset = [operlowest, operlow, opermid, operhi] for i, data in enumerate(priorset): - # # print(op1, i,data,) + # # # print(op1, i,data,) if op1 in data: prior1 = i if op2 in data: prior2 = i - # # print(prior1 <= prior2) + # # # print(prior1 <= prior2) return prior1 <= prior2 @@ -294,55 +297,55 @@ def main(xpr): # разбор строики в список xprlst = parse(xpr) - # print(*xprlst, sep=' ') + # # print(*xprlst, sep=' ') output=[] stack=[] for i in xprlst: - # print('-----------------------------------') - # print('i=',i) + # # print('-----------------------------------') + # # print('i=',i) if type(i) == float or type(i) == int: output.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + # # print('output=',*output,sep=' ') + # # print('stack=',*stack,sep=' ') if i == ',': if stack != []: while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом - # print('пока на верху стэка оператор') - # print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) + # # print('пока на верху стэка оператор') + # # print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) output.append(stack.pop()) # переложить оператор из стека на выход - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + # # print('output=',*output,sep=' ') + # # print('stack=',*stack,sep=' ') if stack == []: break output.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + # # print('output=',*output,sep=' ') + # # print('stack=',*stack,sep=' ') elif i in oper and i != ',': # '^', '*', '/', '+', '-' - # print('in oper',i) - # print(oper) + # # print('in oper',i) + # # print(oper) if stack == []: # если стек пуст - # print('стек пуст. добваить оператор в стек') + # # print('стек пуст. добваить оператор в стек') stack.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + # # print('output=',*output,sep=' ') + # # print('stack=',*stack,sep=' ') elif stack[-1] == '(': # если стек содержит ( - # print('( положить в стек') + # # print('( положить в стек') stack.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + # # print('output=',*output,sep=' ') + # # print('stack=',*stack,sep=' ') else: - # print('оператор:',i, '<=stack', stack[-1], prior(i, stack[-1])) + # # print('оператор:',i, '<=stack', stack[-1], prior(i, stack[-1])) while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом - # print('пока на верху стэка оператор') - # print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) + # # print('пока на верху стэка оператор') + # # print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) output.append(stack.pop()) # переложить оператор из стека на выход - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + # # print('output=',*output,sep=' ') + # # print('stack=',*stack,sep=' ') if stack == []: break stack.append(i) # иначе положить оператор в стек @@ -352,58 +355,58 @@ def main(xpr): # stack.append(i) # иначе положить оператор в стек - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + # # print('output=',*output,sep=' ') + # # print('stack=',*stack,sep=' ') elif i == '(': stack.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + # # print('output=',*output,sep=' ') + # # print('stack=',*stack,sep=' ') elif i == ')': - # print(i) + # # print(i) while stack[-1] != '(': # пока верх стека не равен ( - # print ('push stack', stack[-1]) + # # print ('push stack', stack[-1]) output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке stack.pop() # удаление из стека ( - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + # # print('output=',*output,sep=' ') + # # print('stack=',*stack,sep=' ') elif i in funclist: - # print(i,'IN FUNCLIST помещаем в стек') + # # print(i,'IN FUNCLIST помещаем в стек') stack.append(i) - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') - # print('*******') - # print('output=',*output,sep=' ') - # print('stack=',*stack,sep=' ') + # # print('output=',*output,sep=' ') + # # print('stack=',*stack,sep=' ') + # # print('*******') + # # print('output=',*output,sep=' ') + # # print('stack=',*stack,sep=' ') stack.reverse() pol = output + stack # poland - # print(xpr) - # print('POLAND:',*pol,sep=' ') + # # print(xpr) + # # print('POLAND:',*pol,sep=' ') - # print('START CALCULATE *****************') + # # print('START CALCULATE *****************') output = [] stack = [] for i in pol: - # print('---------------') - # print('i in pol = ',i) + # # print('---------------') + # # print('i in pol = ',i) if i in oper+['pow','log'] and i != ',': - # print(stack,'+++++++++ to pow or log') + # # print(stack,'+++++++++ to pow or log') tmp = operate(i, *stack) - # print(i,'=',tmp) + # # print(i,'=',tmp) if ',' in stack and i in ['pow', 'log']: if stack[-2]==',': @@ -418,23 +421,23 @@ def main(xpr): else: stack.pop() stack.append(tmp) - # print('stack=',stack) + # # print('stack=',stack) elif i in funclist and not i in ['pow','log']: tmp = operate(i, *stack) stack[-1] = tmp - # print('stack=',stack) + # # print('stack=',stack) # elif i in ['pow','log']: - # # print('DOBL') + # # # print('DOBL') # tmp = operate(i, *stack) # stack.pop() # stack.pop() # stack[-1] = tmp - # # print('stack=',stack) + # # # print('stack=',stack) else: stack.append(i) - # print('stack=',stack) + # # print('stack=',stack) return stack[0] @@ -448,4 +451,4 @@ def main(xpr): print(main(xpr)) -# print ('EVAL:',test, '=',eval(test)) +# # print ('EVAL:',test, '=',eval(test)) From d53cfea8b5b0335297fd592c4d5818d57d55b404 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 21 Apr 2019 15:52:29 -0400 Subject: [PATCH 053/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=202^3^4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 67051a44..7896e6bb 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -170,10 +170,13 @@ def parse(xprstr): elif xprlst[i] == '!' and xprlst[i + 1] == '=': xprlst[i] = '!=' xprlst.pop(i + 1) - elif xprlst[i] == '-' and xprlst[i - 1] in ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '=') and type(xprlst[i + 1]) == float: + elif xprlst[i] == '-' and xprlst[i - 1] in \ + ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '=')\ + and type(xprlst[i + 1]) == float: xprlst[i + 1] = xprlst[i + 1] * - 1 xprlst.pop(i) - elif (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] in('*', '^', '+', '-', '(', '<', '>', '=')): + elif (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] + in('*', '^', '+', '-', '(', '<', '>', '=')): xprlst[i] = -1 xprlst.insert(i + 1, '*') elif xprlst[i] == '-' and xprlst[i - 1] == '/': @@ -313,7 +316,8 @@ def main(xpr): if i == ',': if stack != []: - while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом + while stack[-1] in oper+funclist and prior(i, stack[-1]): + # пока наверху стека оператор с большим или равным приоритетом # # print('пока на верху стэка оператор') # # print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) output.append(stack.pop()) # переложить оператор из стека на выход @@ -340,7 +344,8 @@ def main(xpr): # # print('stack=',*stack,sep=' ') else: # # print('оператор:',i, '<=stack', stack[-1], prior(i, stack[-1])) - while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом + while stack[-1] in oper+funclist and prior(i, stack[-1]): + # пока наверху стека оператор с большим или равным приоритетом # # print('пока на верху стэка оператор') # # print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) output.append(stack.pop()) # переложить оператор из стека на выход From c9810b7de9680bbc1135c35e92d9b97f207be77b Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 21 Apr 2019 16:03:16 -0400 Subject: [PATCH 054/159] itswork! wtf max line 120 ? --- final_task/pycalc.py | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 7896e6bb..a2568bd4 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,5 +1,3 @@ -# coding=utf-8 - import argparse import math import string @@ -197,10 +195,6 @@ def parse(xprstr): exit(0) - # # # print(*xprlst,sep=' ') - - - return xprlst @@ -224,21 +218,14 @@ def operate(operator, *args): if operator in dir(math) and not operator in ['pow', 'log']: result = funcdict[operator](args[-1]) - - - elif operator == "pow": if len(args) == 3: result = pow(args[-3], args[-1]) else: print('ERROR: wrong arguments') exit(0) - - elif operator == "log": result = logargs(*args) - - elif len(args) < 2: print('ERROR: no arguments') exit(0) @@ -363,9 +350,6 @@ def main(xpr): # # print('output=',*output,sep=' ') # # print('stack=',*stack,sep=' ') - - - elif i == '(': stack.append(i) # # print('output=',*output,sep=' ') @@ -375,7 +359,8 @@ def main(xpr): # # print(i) while stack[-1] != '(': # пока верх стека не равен ( # # print ('push stack', stack[-1]) - output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке + output.append(stack.pop()) + # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке stack.pop() # удаление из стека ( # # print('output=',*output,sep=' ') # # print('stack=',*stack,sep=' ') From 6e638a113fd37d3c3180438736c7400624788cf0 Mon Sep 17 00:00:00 2001 From: novash-k Date: Mon, 22 Apr 2019 03:59:59 -0400 Subject: [PATCH 055/159] itswork! style test --- final_task/func.py | 18 ----- final_task/pycalc.py | 185 ++++++++++++++++++------------------------- final_task/test.py | 43 ---------- 3 files changed, 78 insertions(+), 168 deletions(-) delete mode 100644 final_task/func.py delete mode 100644 final_task/test.py diff --git a/final_task/func.py b/final_task/func.py deleted file mode 100644 index e2115ab8..00000000 --- a/final_task/func.py +++ /dev/null @@ -1,18 +0,0 @@ -import math -from math import * - -funcdict = {'sin':sin, 'cos':cos, 'pow':pow} - - -def func(oper,*args): - print(oper, args) - print(oper, *args) - print(funcdict[oper](*args) ) - return - -#return funcdict['pow'](a) - - -func('pow',2,3) - -func('sin',2) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index a2568bd4..8ed9ebe9 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -26,7 +26,7 @@ a = 0. b = 0. result = 0. -funcset=set(funclist) +funcset = set(funclist) oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', ','] operset = set(oper) @@ -59,7 +59,7 @@ def parse(xprstr): exit(0) xprstr = xprstr.replace(' ', ' ') - xprstr = xprstr.replace(', ', ',') + xprstr = xprstr.replace(', ', ', ') xprstr = xprstr.replace(' *', '*') xprstr = xprstr.replace('* ', '*') xprstr = xprstr.replace(' +', '+') @@ -80,48 +80,44 @@ def parse(xprstr): if xprstr.count(' ') > 0: print('ERROR: useles spaces') exit(0) - - # добавление скобок для возведения в степень 2^3^4 - l=0 - r=len(xprstr) + l = 0 + r = len(xprstr) for x in range(xprstr.count('^')): - r = xprstr.rindex('^',0,r) - # print('r=', r,' ',xprstr[:r]) - if xprstr[:r].count('^') ==0: + r = xprstr.rindex('^', 0, r) + # print('r=', r, ' ', xprstr[:r]) + if xprstr[:r].count('^') == 0: break - l = xprstr.rindex('^',0,r)+1 - # # print('l=',l,'r=',r,' ',xprstr[l:r]) + l = xprstr.rindex('^', 0, r)+1 + # # print('l=', l, 'r=', r, ' ', xprstr[l:r]) tmp = xprstr[l:r] - # # print('tmp=',tmp) + # # print('tmp=', tmp) tmpset = set(tmp) # # print('tmpset', tmpset) # # print('operset', operset) if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): # # print('нада скобки для степени') - xprstr=xprstr[:l]+'('+xprstr[l:] + xprstr = xprstr[:l]+'('+xprstr[l:] # # print(xprstr) - l=r+2 + l = r+2 # # print(xprstr[l:]) - r=len(xprstr) - for i,data in enumerate(xprstr[l:]): + r = len(xprstr) + for i, data in enumerate(xprstr[l:]): if data in split and data != '(': r = l+i break - # # print('l=',l,'r=',r,' ', xprstr[l:r]) + # # print('l=', l, 'r=', r, ' ', xprstr[l:r]) tmp = xprstr[l:r] # # print(tmp) - xprstr=xprstr[:r]+')'+xprstr[r:] + xprstr = xprstr[:r]+')'+xprstr[r:] # # print(xprstr) else: - # # print('НЕ надо скобки',l,r) + # # print('НЕ надо скобки', l, r) r = l - - # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): @@ -150,8 +146,6 @@ def parse(xprstr): # # # print(word) xprlst.pop() # удаляется добавленный пробел - - for i, data in enumerate(xprlst): if xprlst[i] == '/' and xprlst[i + 1] == '/': xprlst[i] = '//' @@ -187,15 +181,10 @@ def parse(xprstr): # # # print('ok', i) else: print('ERROR: unknown', xprlst[i], i) - - xprset = set(xprlst) if xprset.issubset(funcset) or xprset.issubset(operset): print('ERROR: только функция') exit(0) - - - return xprlst @@ -272,7 +261,7 @@ def operate(operator, *args): def prior(op1, op2): priorset = [operlowest, operlow, opermid, operhi] for i, data in enumerate(priorset): - # # # print(op1, i,data,) + # # # print(op1, i, data, ) if op1 in data: prior1 = i if op2 in data: @@ -283,103 +272,96 @@ def prior(op1, op2): # основная функция def main(xpr): - - # разбор строики в список xprlst = parse(xpr) # # print(*xprlst, sep=' ') - output=[] - stack=[] + output = [] + stack = [] for i in xprlst: # # print('-----------------------------------') - # # print('i=',i) - - + # # print('i=', i) if type(i) == float or type(i) == int: output.append(i) - # # print('output=',*output,sep=' ') - # # print('stack=',*stack,sep=' ') - + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') if i == ',': if stack != []: while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом # # print('пока на верху стэка оператор') - # # print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) - output.append(stack.pop()) # переложить оператор из стека на выход - # # print('output=',*output,sep=' ') - # # print('stack=',*stack,sep=' ') - if stack == []: break + # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) + output.append(stack.pop()) # переложить оператор из стека на выход + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + if stack == []: + break output.append(i) - # # print('output=',*output,sep=' ') - # # print('stack=',*stack,sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') - elif i in oper and i != ',': # '^', '*', '/', '+', '-' + elif i in oper and i != ',': # '^', '*', '/', '+', '-' - # # print('in oper',i) + # # print('in oper', i) # # print(oper) - if stack == []: # если стек пуст + if stack == []: # если стек пуст # # print('стек пуст. добваить оператор в стек') stack.append(i) - # # print('output=',*output,sep=' ') - # # print('stack=',*stack,sep=' ') - elif stack[-1] == '(': # если стек содержит ( + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + elif stack[-1] == '(': # если стек содержит ( # # print('( положить в стек') stack.append(i) - # # print('output=',*output,sep=' ') - # # print('stack=',*stack,sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') else: - # # print('оператор:',i, '<=stack', stack[-1], prior(i, stack[-1])) + # # print('оператор:', i, '<=stack', stack[-1], prior(i, stack[-1])) while stack[-1] in oper+funclist and prior(i, stack[-1]): - # пока наверху стека оператор с большим или равным приоритетом + # пока наверху стека оператор с большим или равным приоритетом # # print('пока на верху стэка оператор') - # # print ( 'PRIOR',i, '<=', stack[-1], prior(i, stack[-1])) - output.append(stack.pop()) # переложить оператор из стека на выход - # # print('output=',*output,sep=' ') - # # print('stack=',*stack,sep=' ') - if stack == []: break - stack.append(i) # иначе положить оператор в стек - - # if i ==',': + # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) + output.append(stack.pop()) # переложить оператор из стека на выход + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + if stack == []: + break + stack.append(i) # иначе положить оператор в стек + + # if i ==', ': # output.append(i) # если это , то на выход # else: # stack.append(i) # иначе положить оператор в стек - - - # # print('output=',*output,sep=' ') - # # print('stack=',*stack,sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') elif i == '(': stack.append(i) - # # print('output=',*output,sep=' ') - # # print('stack=',*stack,sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') elif i == ')': # # print(i) - while stack[-1] != '(': # пока верх стека не равен ( + while stack[-1] != '(': # пока верх стека не равен ( # # print ('push stack', stack[-1]) output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке - stack.pop() # удаление из стека ( - # # print('output=',*output,sep=' ') - # # print('stack=',*stack,sep=' ') + stack.pop() # удаление из стека ( + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') elif i in funclist: - # # print(i,'IN FUNCLIST помещаем в стек') + # # print(i, 'IN FUNCLIST помещаем в стек') stack.append(i) - # # print('output=',*output,sep=' ') - # # print('stack=',*stack,sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') # # print('*******') - # # print('output=',*output,sep=' ') - # # print('stack=',*stack,sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') stack.reverse() - pol = output + stack # poland + pol = output + stack # poland # # print(xpr) - # # print('POLAND:',*pol,sep=' ') - - + # # print('POLAND:', *pol, sep=' ') # # print('START CALCULATE *****************') output = [] @@ -387,19 +369,13 @@ def main(xpr): for i in pol: # # print('---------------') - # # print('i in pol = ',i) - - if i in oper+['pow','log'] and i != ',': - - - # # print(stack,'+++++++++ to pow or log') - + # # print('i in pol = ', i) + if i in oper+['pow', 'log'] and i != ',': + # # print(stack, '+++++++++ to pow or log') tmp = operate(i, *stack) - - # # print(i,'=',tmp) - + # # print(i, '=', tmp) if ',' in stack and i in ['pow', 'log']: - if stack[-2]==',': + if stack[-2] == ', ': stack.pop() stack.pop() stack.pop() @@ -411,34 +387,29 @@ def main(xpr): else: stack.pop() stack.append(tmp) - # # print('stack=',stack) - elif i in funclist and not i in ['pow','log']: + # # print('stack=', stack) + elif i in funclist and not i in ['pow', 'log']: tmp = operate(i, *stack) stack[-1] = tmp - # # print('stack=',stack) - # elif i in ['pow','log']: + # # print('stack=', stack) + # elif i in ['pow', 'log']: # # # print('DOBL') # tmp = operate(i, *stack) # stack.pop() # stack.pop() # stack[-1] = tmp - # # # print('stack=',stack) - - + # # # print('stack=', stack) else: stack.append(i) - # # print('stack=',stack) + # # print('stack=', stack) return stack[0] -#EVAL TEST + +# EVAL TEST test = xpr test = test.replace('^', '**') test = test.replace(' ', '') test = test.replace(', ', '.') -# test - print(main(xpr)) - -# # print ('EVAL:',test, '=',eval(test)) diff --git a/final_task/test.py b/final_task/test.py deleted file mode 100644 index 95983e94..00000000 --- a/final_task/test.py +++ /dev/null @@ -1,43 +0,0 @@ -op1='' -op2='' - - - - -def prior(op1, op2): - oper = ['^', '*', '/', '+', '-'] # 4 - operhi = ['^'] # 3 - opermid = ['*', '/'] # 2 - operlow = ['+', '-'] # 1 - operlowest = ['(',')'] # 0 - - priorset = [operlowest, operlow, opermid, operhi] - print(priorset) - - for i, data in enumerate(priorset): - print(op1, i,data,) - if op1 in data: - prior1 = i - if op2 in data: - prior2 = i - - - print('PRIOR', prior1, prior2) - return prior1 < prior2 - -#print(prior('+', '*')) - - - -def func(oper,*args): - print('reciv',oper,args) - print - - return - - -s = [1,2,3,4,5] - -func('sun',*s) - - From 03a80f24df7a1f083444497d8c4c9aeaa9d48059 Mon Sep 17 00:00:00 2001 From: novash-k Date: Mon, 22 Apr 2019 04:22:56 -0400 Subject: [PATCH 056/159] itswork! style test --- final_task/pycalc.py | 30 +++++++++++++++--------------- final_task/setup.py | 20 ++++++++++---------- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 8ed9ebe9..c4316470 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -80,43 +80,43 @@ def parse(xprstr): if xprstr.count(' ') > 0: print('ERROR: useles spaces') exit(0) + # добавление скобок для возведения в степень 2^3^4 - l = 0 + left = 0 r = len(xprstr) - for x in range(xprstr.count('^')): r = xprstr.rindex('^', 0, r) # print('r=', r, ' ', xprstr[:r]) if xprstr[:r].count('^') == 0: break - l = xprstr.rindex('^', 0, r)+1 - # # print('l=', l, 'r=', r, ' ', xprstr[l:r]) - tmp = xprstr[l:r] + left = xprstr.rindex('^', 0, r)+1 + # # print('left=', left, 'r=', r, ' ', xprstr[left:r]) + tmp = xprstr[left:r] # # print('tmp=', tmp) tmpset = set(tmp) # # print('tmpset', tmpset) # # print('operset', operset) if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): # # print('нада скобки для степени') - xprstr = xprstr[:l]+'('+xprstr[l:] + xprstr = xprstr[:left]+'('+xprstr[left:] # # print(xprstr) - l = r+2 + left = r+2 # # print(xprstr[l:]) r = len(xprstr) - for i, data in enumerate(xprstr[l:]): + for i, data in enumerate(xprstr[left:]): if data in split and data != '(': - r = l+i + r = left+i break - # # print('l=', l, 'r=', r, ' ', xprstr[l:r]) - tmp = xprstr[l:r] + # # print('left=', left, 'r=', r, ' ', xprstr[left:r]) + tmp = xprstr[left:r] # # print(tmp) xprstr = xprstr[:r]+')'+xprstr[r:] # # print(xprstr) else: - # # print('НЕ надо скобки', l, r) - r = l + # # print('НЕ надо скобки', left, r) + r = left # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел @@ -205,7 +205,7 @@ def operate(operator, *args): print('ERROR: operate non digits') exit(0) - if operator in dir(math) and not operator in ['pow', 'log']: + if operator in dir(math) and operator not in ['pow', 'log']: result = funcdict[operator](args[-1]) elif operator == "pow": if len(args) == 3: @@ -388,7 +388,7 @@ def main(xpr): stack.pop() stack.append(tmp) # # print('stack=', stack) - elif i in funclist and not i in ['pow', 'log']: + elif i in funclist and i not in ['pow', 'log']: tmp = operate(i, *stack) stack[-1] = tmp # # print('stack=', stack) diff --git a/final_task/setup.py b/final_task/setup.py index abacd055..1daa7a59 100644 --- a/final_task/setup.py +++ b/final_task/setup.py @@ -1,14 +1,14 @@ from setuptools import setup setup( - name='pycalc', # Required - version='1.0', # Required - description='Pure-python command-line calculator.', # Optional - url='https://github.com/novash-k/PythonHomework', # Optional - author='Konstantin Novash', # Optional - author_email='novash.ki@gmail.com', # Optional - py_modules=["pycalc"], # Required - entry_points = {'console_scripts': ['pycalc=pycalc:main',],}, - #packages=['pycalc_project'] # Required - #python_requires='>3.0, <3.7' + name = 'pycalc', # Required + version = '1.0', # Required + description = 'Pure-python command-line calculator.', # Optional + url = 'https://github.com/novash-k/PythonHomework', # Optional + author = 'Konstantin Novash', # Optional + author_email = 'novash.ki@gmail.com', # Optional + py_modules = ["pycalc"], # Required + entry_points = {'console_scripts': ['pycalc=pycalc:main', ], }, + # packages = ['pycalc_project'] # Required + # python_requires = '>3.0, <3.7' ) From 05160a0f19728d2cd1a9c86e8ddf96a965747070 Mon Sep 17 00:00:00 2001 From: novash-k Date: Mon, 22 Apr 2019 04:28:19 -0400 Subject: [PATCH 057/159] itswork! style test --- final_task/setup.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/final_task/setup.py b/final_task/setup.py index 1daa7a59..44050196 100644 --- a/final_task/setup.py +++ b/final_task/setup.py @@ -1,14 +1,14 @@ from setuptools import setup setup( - name = 'pycalc', # Required - version = '1.0', # Required - description = 'Pure-python command-line calculator.', # Optional - url = 'https://github.com/novash-k/PythonHomework', # Optional - author = 'Konstantin Novash', # Optional - author_email = 'novash.ki@gmail.com', # Optional - py_modules = ["pycalc"], # Required - entry_points = {'console_scripts': ['pycalc=pycalc:main', ], }, - # packages = ['pycalc_project'] # Required - # python_requires = '>3.0, <3.7' + name='pycalc', # Required + version='1.0', # Required + description='Pure-python command-line calculator.', # Optional + url='https://github.com/novash-k/PythonHomework', # Optional + author='Konstantin Novash', # Optional + author_email='novash.ki@gmail.com', # Optional + py_modules=["pycalc"], # Required + entry_points={'console_scripts': ['pycalc=pycalc:main', ], }, + # packages=['pycalc_project'] # Required + # python_requires='>3.0, <3.7' ) From 63de31cfd48a04325158f6fe3fe6e6ab1e2d2c95 Mon Sep 17 00:00:00 2001 From: novash-k Date: Mon, 22 Apr 2019 04:34:50 -0400 Subject: [PATCH 058/159] itswork! style test --- final_task/pycalc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index c4316470..30b77615 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -59,7 +59,7 @@ def parse(xprstr): exit(0) xprstr = xprstr.replace(' ', ' ') - xprstr = xprstr.replace(', ', ', ') + xprstr = xprstr.replace(', ', ',') xprstr = xprstr.replace(' *', '*') xprstr = xprstr.replace('* ', '*') xprstr = xprstr.replace(' +', '+') From 459921212f7db469ace6d83c343328a74d5667d6 Mon Sep 17 00:00:00 2001 From: novash-k Date: Mon, 22 Apr 2019 04:42:06 -0400 Subject: [PATCH 059/159] itswork! style test --- final_task/pycalc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 30b77615..82e93c22 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -375,7 +375,7 @@ def main(xpr): tmp = operate(i, *stack) # # print(i, '=', tmp) if ',' in stack and i in ['pow', 'log']: - if stack[-2] == ', ': + if stack[-2] == ',': stack.pop() stack.pop() stack.pop() From 96f3b3fea2dce31d3665df93d211b2f66bdeb2d1 Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 24 Apr 2019 15:13:13 -0400 Subject: [PATCH 060/159] test 1 --- final_task/pycalc.py | 1 + 1 file changed, 1 insertion(+) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 82e93c22..a74a963b 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,3 +1,4 @@ +# test import argparse import math import string From 9ed3f50a582e194bc61b834bd4a76fa1458e0948 Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 24 Apr 2019 15:21:41 -0400 Subject: [PATCH 061/159] test abs error --- final_task/pycalc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index a74a963b..c98ed9cc 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -19,7 +19,7 @@ funclist = dir(math)+['abs', 'round'] # list of math functions names funcdict = math.__dict__ # dict of math functions -funcdict['abs'] = abs +funcdict['abws'] = abs funcdict['round'] = round xprstr = '' operator = '' From d5d3b786e702fd0272068b45dd7c25e0704a0830 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 03:33:28 -0400 Subject: [PATCH 062/159] test --- final_task/_pycalc.py | 484 ++++++++++++++++++++++++++++++++++++++++++ final_task/func1.py | 5 + final_task/func2.py | 5 + final_task/myfunc2.py | 16 ++ final_task/pycalc.py | 324 ++++++++++++++-------------- 5 files changed, 679 insertions(+), 155 deletions(-) create mode 100644 final_task/_pycalc.py create mode 100644 final_task/func1.py create mode 100644 final_task/func2.py create mode 100644 final_task/myfunc2.py diff --git a/final_task/_pycalc.py b/final_task/_pycalc.py new file mode 100644 index 00000000..dace249f --- /dev/null +++ b/final_task/_pycalc.py @@ -0,0 +1,484 @@ +# test +import argparse +import math +import string +import importlib +import importlib.util +from math import * + +#import myfunc1 +# from myfunc import func1 + +ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') +ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') +ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') +args = ap.parse_args() +xpr = args.EXPRESSION +mod = args.MODULE +print ('111111111111',mod) + + + + + +funcset = {} +operset = {} +splitset = {} + +split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') +splitset = set(split) + +funclist = dir(math)+['abs', 'round', mod] # list of math functions names +funcdict = math.__dict__ # dict of math functions +funcdict['abs'] = abs +funcdict['round'] = round + +if mod is not None: # если введено имя модуля + spec = importlib.util.find_spec(mod) + print('spec=', spec) + if spec is None: # проверка возможности импорта модуля + print('ERROR: module {} not found'.format(mod)) + exit(0) + else: + newfunc = importlib.import_module(mod) # импортирование нового модуля + print(dir(newfunc)) + funcdict[mod] = newfunc.main # добавление в словарь новой функции + +xprstr = '' +operator = '' +xprlst = [] +a = 0. +b = 0. +result = 0. +funcset = set(funclist) + +oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', ','] +operset = set(oper) +operhi = ['^'] + funclist # 3 +opermid = ['*', '/', '%'] # 2 +operlow = ['+', '-'] # 1 +operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 + + +# разбор строки на элементы списка +def parse(xprstr): + word = '' + + # проверка недопустимых символов + exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} + xprset = set(xprstr) + if not exset.isdisjoint(xprset): + print('ERROR: unknown symbol') + exit(0) + # проверка скобок в строке + if xpr.count('(') != xpr.count(')'): + print('ERROR: brackets are not balanced') + exit(0) + + # проверка если состоит только из знаков пунктуации + punctset = set(string.punctuation) + xprset = set(xprstr) + if xprset.issubset(punctset) or xprset.issubset(funcset): + print('ERROR: no digits or functions') + exit(0) + + xprstr = xprstr.replace(' ', ' ') + xprstr = xprstr.replace(', ', ',') + xprstr = xprstr.replace(' *', '*') + xprstr = xprstr.replace('* ', '*') + xprstr = xprstr.replace(' +', '+') + xprstr = xprstr.replace('+ ', '+') + xprstr = xprstr.replace(' -', '-') + xprstr = xprstr.replace('- ', '-') + xprstr = xprstr.replace('--', '+') + xprstr = xprstr.replace('++', '+') + xprstr = xprstr.replace('+-', '-') + xprstr = xprstr.replace('-+', '-') + + # # print(xprstr) + + if xprstr[0] == '+': + xprstr = xprstr[1:] + + # проверка пробелов + if xprstr.count(' ') > 0: + print('ERROR: useles spaces') + exit(0) + + # добавление скобок для возведения в степень 2^3^4 + left = 0 + r = len(xprstr) + for x in range(xprstr.count('^')): + r = xprstr.rindex('^', 0, r) + # print('r=', r, ' ', xprstr[:r]) + if xprstr[:r].count('^') == 0: + break + left = xprstr.rindex('^', 0, r)+1 + # # print('left=', left, 'r=', r, ' ', xprstr[left:r]) + tmp = xprstr[left:r] + # # print('tmp=', tmp) + tmpset = set(tmp) + # # print('tmpset', tmpset) + # # print('operset', operset) + if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): + # # print('нада скобки для степени') + xprstr = xprstr[:left]+'('+xprstr[left:] + # # print(xprstr) + + left = r+2 + # # print(xprstr[l:]) + + r = len(xprstr) + for i, data in enumerate(xprstr[left:]): + if data in split and data != '(': + r = left+i + break + # # print('left=', left, 'r=', r, ' ', xprstr[left:r]) + tmp = xprstr[left:r] + # # print(tmp) + xprstr = xprstr[:r]+')'+xprstr[r:] + # # print(xprstr) + else: + # # print('НЕ надо скобки', left, r) + r = left + + # разбор строки + for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел + if sym in split or i == len(xprstr): + # # # print(word) + if word == 'pi': + xprlst.append(pi) + elif word == 'e': + xprlst.append(e) + elif word in funclist: + # # # print(word, ' in math') + xprlst.append(word) + elif word.replace('.', '').isdigit() and word.count('.') < 2: + xprlst.append(float(word)) + # elif word != '': + elif word in split or word == '': + pass + # # # print('ok', word) + else: + print('ERROR: wrong symbol "', word, '"') + exit(0) + xprlst.append(sym) + # # # print(xprlst) + word = '' + else: + word = word + sym + # # # print(word) + xprlst.pop() # удаляется добавленный пробел + + for i, data in enumerate(xprlst): + if xprlst[i] == '/' and xprlst[i + 1] == '/': + xprlst[i] = '//' + xprlst.pop(i + 1) + elif xprlst[i] == '>' and xprlst[i + 1] == '=': + xprlst[i] = '>=' + xprlst.pop(i + 1) + elif xprlst[i] == '<' and xprlst[i + 1] == '=': + xprlst[i] = '<=' + xprlst.pop(i + 1) + elif xprlst[i] == '=' and xprlst[i + 1] == '=' or xprlst[i] == '=': + xprlst[i] = '==' + xprlst.pop(i + 1) + elif xprlst[i] == '!' and xprlst[i + 1] == '=': + xprlst[i] = '!=' + xprlst.pop(i + 1) + elif xprlst[i] == '-' and xprlst[i - 1] in \ + ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '=')\ + and type(xprlst[i + 1]) == float: + xprlst[i + 1] = xprlst[i + 1] * - 1 + xprlst.pop(i) + elif (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] + in('*', '^', '+', '-', '(', '<', '>', '=')): + xprlst[i] = -1 + xprlst.insert(i + 1, '*') + elif xprlst[i] == '-' and xprlst[i - 1] == '/': + xprlst[i - 1] = '*' + xprlst[i] = -1 + xprlst.insert(i + 1, '/') + elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: + pass + + # # # print('ok', i) + else: + print('ERROR: unknown', xprlst[i], i) + xprset = set(xprlst) + if xprset.issubset(funcset) or xprset.issubset(operset): + print('ERROR: только функция') + exit(0) + return xprlst + + +def logargs(*args): + # # print('START logoargs', args) + if ',' in args: + res = log(args[-3], args[-1]) + else: + res = log(args[-1]) + # # print('RETURN logoargs', res) + return res + + +def operate(operator, *args): + print('OPERATOR=',operator,'ARGS=',args) + for i in args: + if not (type(i) == float or type(i) == int): + print('ERROR: operate non digits') + exit(0) + + if operator in dir(math): + result = funcdict[operator](*args) + + elif operator == "+": + result = args[0] + args[1] + elif operator == "-": + result = args[0] - args[1] + elif operator == "*": + result = args[0] * args[1] + elif operator == "//": + if args[1] != 0: + result = args[0] // args[1] + else: + print('ERROR: division by zero') + exit(0) + elif operator == "/": + if args[1] != 0: + result = args[0] / args[1] + else: + print('ERROR: division by zero') + exit(0) + elif operator == "%": + result = args[0] % args[1] + elif operator == "^": + result = args[0] ** args[1] + elif operator == "<=": + result = args[0] <= args[1] + elif operator == ">=": + result = args[0] >= args[1] + elif operator == "<": + result = args[0] < args[1] + elif operator == ">": + result = args[0] > args[1] + elif operator == "==": + result = args[0] == args[1] + elif operator == "!=": + result = args[0] != args[1] + else: + print('ERROR: unknown math operator', operator) + result = 0 + return result + + +def prior(op1, op2): + priorset = [operlowest, operlow, opermid, operhi] + for i, data in enumerate(priorset): + # # # print(op1, i, data, ) + if op1 in data: + prior1 = i + if op2 in data: + prior2 = i + # # # print(prior1 <= prior2) + return prior1 <= prior2 + + +def postfix(xprlst): + """ + преобразование инфиксной нотации в постфиксную + на входе список элементов выражения инфиксной нотации, на выходе список элементов постфиксной нотации + """ + print('START CONVERT TO POSTFIX *********************') + output = [] + stack = [] + for i in xprlst: + # # print('-----------------------------------') + # # print('i=', i) + if type(i) == float or type(i) == int: + output.append(i) + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + if i == ',': + if stack != []: + while stack[-1] in oper+funclist and prior(i, stack[-1]): + # пока наверху стека оператор с большим или равным приоритетом + # # print('пока на верху стэка оператор') + # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) + output.append(stack.pop()) # переложить оператор из стека на выход + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + if stack == []: + break + output.append(i) + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + + elif i in oper and i != ',': # '^', '*', '/', '+', '-' + # # print('in oper', i) + # # print(oper) + if stack == []: # если стек пуст + # # print('стек пуст. добваить оператор в стек') + stack.append(i) + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + elif stack[-1] == '(': # если стек содержит ( + # # print('( положить в стек') + stack.append(i) + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + else: + # # print('оператор:', i, '<=stack', stack[-1], prior(i, stack[-1])) + while stack[-1] in oper+funclist and prior(i, stack[-1]): + # пока наверху стека оператор с большим или равным приоритетом + # # print('пока на верху стэка оператор') + # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) + output.append(stack.pop()) # переложить оператор из стека на выход + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + if stack == []: + break + stack.append(i) # иначе положить оператор в стек + + # if i ==', ': + # output.append(i) # если это , то на выход + # else: + # stack.append(i) # иначе положить оператор в стек + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + + elif i == '(': + stack.append(i) + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + + elif i == ')': + # # print(i) + while stack[-1] != '(': # пока верх стека не равен ( + # # print ('push stack', stack[-1]) + output.append(stack.pop()) + # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке + stack.pop() # удаление из стека ( + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + elif i in funclist: + # # print(i, 'IN FUNCLIST помещаем в стек') + stack.append(i) + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + # # print('*******') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + + stack.reverse() + pol = output + stack # poland + + # # print(xpr) + # # print('POLAND:', *pol, sep=' ') + return pol + + + + +def evalpostfix(xprpstfx): + """ + вычисление выражения в постфиксной нотации + на входе список элементов выражения + """ + print('START EVALUATE POSTFIX ********************') + stack = [] + args = [] + for i in xprpstfx: + # # print('---------------') + print('EVAL i = ', i, 'STACK=',stack) + + + + if i in funclist and i != ',': + + if stack[-2] == ',': + j=len(stack)-2 + while stack[j] == ',': + args.append(stack[j-1]) + stack.pop() + stack.pop() + j=j-2 + args.reverse() + print('j=',j+1,stack[j+1:]) + print('ARGS=',args) + print('STACK',stack) + else: + args.append(stack[-1]) + + + tmp = operate(i, *args) + print('TMP=',tmp) + args=[] + stack.append(tmp) + print('STACK',stack) + + elif i in oper and i != ',': + + print('ARGS=',args) + print('STACK',stack) + tmp = operate(i, stack[-2], stack[-1]) + print('TMP=',tmp) + stack.pop() + stack.pop() + stack.append(tmp) + + print('STACK',stack) + + + + + # + # if i in oper+['pow', 'log'] and i != ',': + # print(stack, '+++++++++ to pow or log') + # tmp = operate(i, *stack) + # # # print(i, '=', tmp) + # if ',' in stack and i in ['pow', 'log']: + # if stack[-2] == ',': + # stack.pop() + # stack.pop() + # stack.pop() + # stack.append(tmp) + # elif i in oper: + # stack.pop() + # stack.pop() + # stack.append(tmp) + # else: + # stack.pop() + # stack.append(tmp) + # # # print('stack=', stack) + # elif i in funclist and i not in ['pow', 'log']: + # tmp = operate(i, *stack) + # stack[-1] = tmp + # print('stack=', stack) + + + + else: + stack.append(i) + # # print('stack=', stack) + + return stack[0] + + +# EVAL TEST +test = xpr +test = test.replace('^', '**') +test = test.replace(' ', '') +test = test.replace(', ', '.') + +# разбор строики в список +xprlst = parse(xpr) +print(*xprlst, sep=' ') + +# преобразование инфиксного списка в постфиксных список +xprlst = postfix(xprlst) +print(*xprlst, sep=' ') + +# вычисление постфиксного списка +result = evalpostfix(xprlst) +print(result) diff --git a/final_task/func1.py b/final_task/func1.py new file mode 100644 index 00000000..3e2f3065 --- /dev/null +++ b/final_task/func1.py @@ -0,0 +1,5 @@ +def main(x): + x = (x + x) * x + return x + + diff --git a/final_task/func2.py b/final_task/func2.py new file mode 100644 index 00000000..558633fc --- /dev/null +++ b/final_task/func2.py @@ -0,0 +1,5 @@ +def main(x, y): + x = (x + y) * 2 + return x + + diff --git a/final_task/myfunc2.py b/final_task/myfunc2.py new file mode 100644 index 00000000..9b2b08e7 --- /dev/null +++ b/final_task/myfunc2.py @@ -0,0 +1,16 @@ +ss=[] +s=[0,",",3,2,',',3,4,6] +s=[2,',',1] +#s=[1,2,3,4] +i=len(s)-2 +ss.append(s[-1]) +print(*s,sep=' ') +print(i,s[i]) +while s[i] == ',': + ss.append(s[i-1]) + i=i-2 + print(i, s[i]) +print('out',i) +print(*s[i+1:],sep=' ') +ss.reverse() +print(ss) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index c98ed9cc..e37706dc 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,7 +1,11 @@ -# test +# test 26 apr import argparse import math +import operator +from operator import * import string +import importlib +import importlib.util from math import * ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') @@ -9,41 +13,80 @@ ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') args = ap.parse_args() xpr = args.EXPRESSION +mod = args.MODULE -funcset = {} -operset = {} -splitset = {} -split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') -splitset = set(split) - -funclist = dir(math)+['abs', 'round'] # list of math functions names -funcdict = math.__dict__ # dict of math functions -funcdict['abws'] = abs -funcdict['round'] = round xprstr = '' operator = '' xprlst = [] a = 0. b = 0. result = 0. + + +funcset = {} +operset = {} +splitset = {} + + + +split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') +splitset = set(split) + +funclist = dir(math)+['abs', 'round', 'sum'] # list of math functions names +funcdic = math.__dict__ # dict of math functions funcset = set(funclist) +opdic = { + '+':add, + '-':sub, + '*':mul, + '/':truediv, + '//':floordiv, + '^':pow, + '%':mod, + '==':eq, + '<=': le, + '>=': ge, + '<':lt, + '>': gt, + '!=':ne, + 'abs':abs, + 'round':round, + 'sum':sum + } +funcdic.update(opdic) + oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', ','] operset = set(oper) -operhi = ['^'] + funclist # 3 -opermid = ['*', '/', '%'] # 2 -operlow = ['+', '-'] # 1 -operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 -# разбор строки на элементы списка + + +def addfunc(mod): + """ добавляет новую функцию из модуля """ + if mod is not None: # если введено имя модуля + spec = importlib.util.find_spec(mod) + if spec is None: # проверка возможности импорта модуля + print('ERROR: module {} not found'.format(mod)) + exit(0) + else: + newfunc = importlib.import_module(mod) # импортирование нового модуля + # print(dir(newfunc)) + funcdic[mod] = newfunc.main + funclist.append(mod) + funcset.add(mod) + return + + def parse(xprstr): + """ парсинг строки математического выражения. + на выходе список в инфиксной нотации""" word = '' - - # проверка недопустимых символов exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} xprset = set(xprstr) + + # проверка если строка выражения содержит недопустимые символы if not exset.isdisjoint(xprset): print('ERROR: unknown symbol') exit(0) @@ -51,11 +94,8 @@ def parse(xprstr): if xpr.count('(') != xpr.count(')'): print('ERROR: brackets are not balanced') exit(0) - - # проверка если состоит только из знаков пунктуации - punctset = set(string.punctuation) - xprset = set(xprstr) - if xprset.issubset(punctset) or xprset.issubset(funcset): + # проверка если выражение состоит только из знаков пунктуации + if xprset.issubset(string.punctuation) or xprset.issubset(funcset): print('ERROR: no digits or functions') exit(0) @@ -72,52 +112,48 @@ def parse(xprstr): xprstr = xprstr.replace('+-', '-') xprstr = xprstr.replace('-+', '-') - # # print(xprstr) - if xprstr[0] == '+': xprstr = xprstr[1:] - # проверка пробелов + # проверка лишних пробелов if xprstr.count(' ') > 0: print('ERROR: useles spaces') exit(0) # добавление скобок для возведения в степень 2^3^4 - left = 0 - r = len(xprstr) + lt = 0 + rt = len(xprstr) for x in range(xprstr.count('^')): - r = xprstr.rindex('^', 0, r) - # print('r=', r, ' ', xprstr[:r]) - if xprstr[:r].count('^') == 0: + rt = xprstr.rindex('^', 0, rt) + # print('rt=', rt, ' ', xprstr[:rt]) + if xprstr[:rt].count('^') == 0: break - left = xprstr.rindex('^', 0, r)+1 - # # print('left=', left, 'r=', r, ' ', xprstr[left:r]) - tmp = xprstr[left:r] + lt = xprstr.rindex('^', 0, rt)+1 + # # print('lt=', lt, 'rt=', rt, ' ', xprstr[lt:rt]) + tmp = xprstr[lt:rt] # # print('tmp=', tmp) tmpset = set(tmp) # # print('tmpset', tmpset) # # print('operset', operset) if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): # # print('нада скобки для степени') - xprstr = xprstr[:left]+'('+xprstr[left:] + xprstr = xprstr[:lt]+'('+xprstr[lt:] # # print(xprstr) - - left = r+2 + lt = rt+2 # # print(xprstr[l:]) - - r = len(xprstr) - for i, data in enumerate(xprstr[left:]): + rt = len(xprstr) + for i, data in enumerate(xprstr[lt:]): if data in split and data != '(': - r = left+i + rt = lt+i break - # # print('left=', left, 'r=', r, ' ', xprstr[left:r]) - tmp = xprstr[left:r] + # # print('lt=', lt, 'rt=', rt, ' ', xprstr[lt:rt]) + tmp = xprstr[lt:rt] # # print(tmp) - xprstr = xprstr[:r]+')'+xprstr[r:] + xprstr = xprstr[:rt]+')'+xprstr[rt:] # # print(xprstr) else: - # # print('НЕ надо скобки', left, r) - r = left + # # print('НЕ надо скобки', lt, rt) + rt = lt # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел @@ -137,8 +173,10 @@ def parse(xprstr): pass # # # print('ok', word) else: - print('ERROR: wrong symbol "', word, '"') - exit(0) + addfunc(word) # импортировать неизвестную функцию + xprlst.append(word) + #print('ERROR: wrong symbol "', word, '"') + #exit(0) xprlst.append(sym) # # # print(xprlst) word = '' @@ -199,84 +237,45 @@ def logargs(*args): return res -def operate(operator, *args): - - for i in args: - if not (type(i) == float or type(i) == int or i == ','): - print('ERROR: operate non digits') - exit(0) +def operate(operator, args): + # print('OPERATOR=',operator,'ARGS=',args) - if operator in dir(math) and operator not in ['pow', 'log']: - result = funcdict[operator](args[-1]) - elif operator == "pow": - if len(args) == 3: - result = pow(args[-3], args[-1]) - else: - print('ERROR: wrong arguments') - exit(0) - elif operator == "log": - result = logargs(*args) - elif len(args) < 2: - print('ERROR: no arguments') - exit(0) - elif operator == "+": - result = args[-2] + args[-1] - elif operator == "-": - result = args[-2] - args[-1] - elif operator == "*": - result = args[-2] * args[-1] - elif operator == "//": - if args[-1] != 0: - result = args[-2] // args[-1] + if operator in ['sum', 'fsum']: + # print('OPERATOR=',operator,'ARGS=',args) + result = funcdic[operator](args) + elif operator in dir(math) + dir(operator) and operator not in ['sum', 'fsum']: + # print('OPERATOR=',operator,'ARGS=',args, '*ARGS=',args) + if type(args) == float or type(args) == int or type(args) == bool : + result = funcdic[operator](args) else: - print('ERROR: division by zero') - exit(0) - elif operator == "/": - if args[-1] != 0: - result = args[-2] / args[-1] - else: - print('ERROR: division by zero') - exit(0) - elif operator == "%": - result = args[-2] % args[-1] - elif operator == "^": - result = args[-2] ** args[-1] - elif operator == "<=": - result = args[-2] <= args[-1] - elif operator == ">=": - result = args[-2] >= args[-1] - elif operator == "<": - result = args[-2] < args[-1] - elif operator == ">": - result = args[-2] > args[-1] - elif operator == "==": - result = args[-2] == args[-1] - elif operator == "!=": - result = args[-2] != args[-1] - else: - print('ERROR: unknown math operator', operator) - result = 0 + result = funcdic[operator](*args) + # else: # уже проверяется в парсинге и попыика импортировать модуль + # print('ERROR: unknown math operator', operator) + # result = 0 return result def prior(op1, op2): + """ сравнивает приоритеты математических опрераторов и функций op1 <= op2, возвращает bool """ + operhi = ['^'] + funclist # 3 + opermid = ['*', '/', '%'] # 2 + operlow = ['+', '-'] # 1 + operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 priorset = [operlowest, operlow, opermid, operhi] for i, data in enumerate(priorset): - # # # print(op1, i, data, ) if op1 in data: - prior1 = i + pr1 = i if op2 in data: - prior2 = i - # # # print(prior1 <= prior2) - return prior1 <= prior2 - + pr2 = i + return pr1 <= pr2 -# основная функция -def main(xpr): - # разбор строики в список - xprlst = parse(xpr) - # # print(*xprlst, sep=' ') +def postfix(xprlst): + """ + преобразование инфиксной нотации в постфиксную + на входе список элементов выражения инфиксной нотации, на выходе список элементов постфиксной нотации + """ + print('START CONVERT TO POSTFIX *********************') output = [] stack = [] for i in xprlst: @@ -302,7 +301,6 @@ def main(xpr): # # print('stack=', *stack, sep=' ') elif i in oper and i != ',': # '^', '*', '/', '+', '-' - # # print('in oper', i) # # print(oper) if stack == []: # если стек пуст @@ -359,58 +357,74 @@ def main(xpr): # # print('stack=', *stack, sep=' ') stack.reverse() - pol = output + stack # poland + return output + stack - # # print(xpr) - # # print('POLAND:', *pol, sep=' ') - # # print('START CALCULATE *****************') - output = [] +def evalpostfix(xprpstfx): + """ + вычисление выражения в постфиксной нотации + на входе список элементов выражения + """ + print('START EVALUATE POSTFIX ********************') stack = [] - - for i in pol: + args = [] + for i in xprpstfx: # # print('---------------') - # # print('i in pol = ', i) - if i in oper+['pow', 'log'] and i != ',': - # # print(stack, '+++++++++ to pow or log') - tmp = operate(i, *stack) - # # print(i, '=', tmp) - if ',' in stack and i in ['pow', 'log']: - if stack[-2] == ',': - stack.pop() + # print('EVAL i = ', i, 'STACK=',stack) + if i in funclist and i != ',': + if len(stack) < 2: + stack[0] = operate(i,stack[0]) + else: + j=len(stack)-2 + args.append(stack[-1]) + while stack[j] == ',': + args.append(stack[j-1]) stack.pop() stack.pop() - stack.append(tmp) - elif i in oper: - stack.pop() + j=j-2 stack.pop() + args.reverse() + tmp = operate(i,args) + print('TMP=',tmp) + args=[] stack.append(tmp) - else: - stack.pop() - stack.append(tmp) - # # print('stack=', stack) - elif i in funclist and i not in ['pow', 'log']: - tmp = operate(i, *stack) - stack[-1] = tmp - # # print('stack=', stack) - # elif i in ['pow', 'log']: - # # # print('DOBL') - # tmp = operate(i, *stack) - # stack.pop() - # stack.pop() - # stack[-1] = tmp - # # # print('stack=', stack) + + print('STACK',stack) + + elif i in oper and i != ',': + tmp = operate(i, stack[-2:]) + stack.pop() + stack.pop() + stack.append(tmp) + print('STACK',stack) + else: stack.append(i) - # # print('stack=', stack) return stack[0] # EVAL TEST -test = xpr -test = test.replace('^', '**') -test = test.replace(' ', '') -test = test.replace(', ', '.') - -print(main(xpr)) +# test = xpr +# test = test.replace('^', '**') +# test = test.replace(' ', '') +# test = test.replace(', ', '.') + +def main(): + # попытка добавления внешней функции если указана -m module + addfunc(mod) + + # разбор строики вырыжения в список + xprlst = parse(xpr) + #print(*xprlst, sep=' ') + + # преобразование инфиксного списка в постфиксных список + xprlst = postfix(xprlst) + #print(*xprlst, sep=' ') + + # вычисление постфиксного списка + print(evalpostfix(xprlst)) + return + + +main() From c9fc6ff8458a2d0618e520742ccde290823c833c Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 03:40:36 -0400 Subject: [PATCH 063/159] test --- final_task/pycalc.py | 140 +++++++++++++++++++++---------------------- 1 file changed, 70 insertions(+), 70 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index e37706dc..7073e073 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -72,7 +72,7 @@ def addfunc(mod): exit(0) else: newfunc = importlib.import_module(mod) # импортирование нового модуля - # print(dir(newfunc)) + # # print(dir(newfunc)) funcdic[mod] = newfunc.main funclist.append(mod) funcset.add(mod) @@ -125,64 +125,64 @@ def parse(xprstr): rt = len(xprstr) for x in range(xprstr.count('^')): rt = xprstr.rindex('^', 0, rt) - # print('rt=', rt, ' ', xprstr[:rt]) + # # print('rt=', rt, ' ', xprstr[:rt]) if xprstr[:rt].count('^') == 0: break lt = xprstr.rindex('^', 0, rt)+1 - # # print('lt=', lt, 'rt=', rt, ' ', xprstr[lt:rt]) + # # # print('lt=', lt, 'rt=', rt, ' ', xprstr[lt:rt]) tmp = xprstr[lt:rt] - # # print('tmp=', tmp) + # # # print('tmp=', tmp) tmpset = set(tmp) - # # print('tmpset', tmpset) - # # print('operset', operset) + # # # print('tmpset', tmpset) + # # # print('operset', operset) if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): - # # print('нада скобки для степени') + # # # print('нада скобки для степени') xprstr = xprstr[:lt]+'('+xprstr[lt:] - # # print(xprstr) + # # # print(xprstr) lt = rt+2 - # # print(xprstr[l:]) + # # # print(xprstr[l:]) rt = len(xprstr) for i, data in enumerate(xprstr[lt:]): if data in split and data != '(': rt = lt+i break - # # print('lt=', lt, 'rt=', rt, ' ', xprstr[lt:rt]) + # # # print('lt=', lt, 'rt=', rt, ' ', xprstr[lt:rt]) tmp = xprstr[lt:rt] - # # print(tmp) + # # # print(tmp) xprstr = xprstr[:rt]+')'+xprstr[rt:] - # # print(xprstr) + # # # print(xprstr) else: - # # print('НЕ надо скобки', lt, rt) + # # # print('НЕ надо скобки', lt, rt) rt = lt # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): - # # # print(word) + # # # # print(word) if word == 'pi': xprlst.append(pi) elif word == 'e': xprlst.append(e) elif word in funclist: - # # # print(word, ' in math') + # # # # print(word, ' in math') xprlst.append(word) elif word.replace('.', '').isdigit() and word.count('.') < 2: xprlst.append(float(word)) # elif word != '': elif word in split or word == '': pass - # # # print('ok', word) + # # # # print('ok', word) else: addfunc(word) # импортировать неизвестную функцию xprlst.append(word) #print('ERROR: wrong symbol "', word, '"') #exit(0) xprlst.append(sym) - # # # print(xprlst) + # # # # print(xprlst) word = '' else: word = word + sym - # # # print(word) + # # # # print(word) xprlst.pop() # удаляется добавленный пробел for i, data in enumerate(xprlst): @@ -217,7 +217,7 @@ def parse(xprstr): elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: pass - # # # print('ok', i) + # # # # print('ok', i) else: print('ERROR: unknown', xprlst[i], i) xprset = set(xprlst) @@ -228,23 +228,23 @@ def parse(xprstr): def logargs(*args): - # # print('START logoargs', args) + # # # print('START logoargs', args) if ',' in args: res = log(args[-3], args[-1]) else: res = log(args[-1]) - # # print('RETURN logoargs', res) + # # # print('RETURN logoargs', res) return res def operate(operator, args): - # print('OPERATOR=',operator,'ARGS=',args) + # # print('OPERATOR=',operator,'ARGS=',args) if operator in ['sum', 'fsum']: - # print('OPERATOR=',operator,'ARGS=',args) + # # print('OPERATOR=',operator,'ARGS=',args) result = funcdic[operator](args) elif operator in dir(math) + dir(operator) and operator not in ['sum', 'fsum']: - # print('OPERATOR=',operator,'ARGS=',args, '*ARGS=',args) + # # print('OPERATOR=',operator,'ARGS=',args, '*ARGS=',args) if type(args) == float or type(args) == int or type(args) == bool : result = funcdic[operator](args) else: @@ -275,53 +275,53 @@ def postfix(xprlst): преобразование инфиксной нотации в постфиксную на входе список элементов выражения инфиксной нотации, на выходе список элементов постфиксной нотации """ - print('START CONVERT TO POSTFIX *********************') + # print('START CONVERT TO POSTFIX *********************') output = [] stack = [] for i in xprlst: - # # print('-----------------------------------') - # # print('i=', i) + # # # print('-----------------------------------') + # # # print('i=', i) if type(i) == float or type(i) == int: output.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') if i == ',': if stack != []: while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом - # # print('пока на верху стэка оператор') - # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) + # # # print('пока на верху стэка оператор') + # # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) output.append(stack.pop()) # переложить оператор из стека на выход - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') if stack == []: break output.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') elif i in oper and i != ',': # '^', '*', '/', '+', '-' - # # print('in oper', i) - # # print(oper) + # # # print('in oper', i) + # # # print(oper) if stack == []: # если стек пуст - # # print('стек пуст. добваить оператор в стек') + # # # print('стек пуст. добваить оператор в стек') stack.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') elif stack[-1] == '(': # если стек содержит ( - # # print('( положить в стек') + # # # print('( положить в стек') stack.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') else: - # # print('оператор:', i, '<=stack', stack[-1], prior(i, stack[-1])) + # # # print('оператор:', i, '<=stack', stack[-1], prior(i, stack[-1])) while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом - # # print('пока на верху стэка оператор') - # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) + # # # print('пока на верху стэка оператор') + # # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) output.append(stack.pop()) # переложить оператор из стека на выход - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') if stack == []: break stack.append(i) # иначе положить оператор в стек @@ -330,31 +330,31 @@ def postfix(xprlst): # output.append(i) # если это , то на выход # else: # stack.append(i) # иначе положить оператор в стек - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') elif i == '(': stack.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') elif i == ')': - # # print(i) + # # # print(i) while stack[-1] != '(': # пока верх стека не равен ( - # # print ('push stack', stack[-1]) + # # # print ('push stack', stack[-1]) output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке stack.pop() # удаление из стека ( - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') elif i in funclist: - # # print(i, 'IN FUNCLIST помещаем в стек') + # # # print(i, 'IN FUNCLIST помещаем в стек') stack.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - # # print('*******') - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') + # # # print('*******') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') stack.reverse() return output + stack @@ -365,12 +365,12 @@ def evalpostfix(xprpstfx): вычисление выражения в постфиксной нотации на входе список элементов выражения """ - print('START EVALUATE POSTFIX ********************') + # print('START EVALUATE POSTFIX ********************') stack = [] args = [] for i in xprpstfx: - # # print('---------------') - # print('EVAL i = ', i, 'STACK=',stack) + # # # print('---------------') + # # print('EVAL i = ', i, 'STACK=',stack) if i in funclist and i != ',': if len(stack) < 2: stack[0] = operate(i,stack[0]) @@ -385,18 +385,18 @@ def evalpostfix(xprpstfx): stack.pop() args.reverse() tmp = operate(i,args) - print('TMP=',tmp) + # print('TMP=',tmp) args=[] stack.append(tmp) - print('STACK',stack) + # print('STACK',stack) elif i in oper and i != ',': tmp = operate(i, stack[-2:]) stack.pop() stack.pop() stack.append(tmp) - print('STACK',stack) + # print('STACK',stack) else: stack.append(i) @@ -416,11 +416,11 @@ def main(): # разбор строики вырыжения в список xprlst = parse(xpr) - #print(*xprlst, sep=' ') + ## print(*xprlst, sep=' ') # преобразование инфиксного списка в постфиксных список xprlst = postfix(xprlst) - #print(*xprlst, sep=' ') + ## print(*xprlst, sep=' ') # вычисление постфиксного списка print(evalpostfix(xprlst)) From 37e54070538562b41bff7b982beedf4efdec639f Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 03:48:30 -0400 Subject: [PATCH 064/159] test --- final_task/_pycalc.py | 484 ------------------------------------------ 1 file changed, 484 deletions(-) delete mode 100644 final_task/_pycalc.py diff --git a/final_task/_pycalc.py b/final_task/_pycalc.py deleted file mode 100644 index dace249f..00000000 --- a/final_task/_pycalc.py +++ /dev/null @@ -1,484 +0,0 @@ -# test -import argparse -import math -import string -import importlib -import importlib.util -from math import * - -#import myfunc1 -# from myfunc import func1 - -ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') -ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') -ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') -args = ap.parse_args() -xpr = args.EXPRESSION -mod = args.MODULE -print ('111111111111',mod) - - - - - -funcset = {} -operset = {} -splitset = {} - -split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') -splitset = set(split) - -funclist = dir(math)+['abs', 'round', mod] # list of math functions names -funcdict = math.__dict__ # dict of math functions -funcdict['abs'] = abs -funcdict['round'] = round - -if mod is not None: # если введено имя модуля - spec = importlib.util.find_spec(mod) - print('spec=', spec) - if spec is None: # проверка возможности импорта модуля - print('ERROR: module {} not found'.format(mod)) - exit(0) - else: - newfunc = importlib.import_module(mod) # импортирование нового модуля - print(dir(newfunc)) - funcdict[mod] = newfunc.main # добавление в словарь новой функции - -xprstr = '' -operator = '' -xprlst = [] -a = 0. -b = 0. -result = 0. -funcset = set(funclist) - -oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', ','] -operset = set(oper) -operhi = ['^'] + funclist # 3 -opermid = ['*', '/', '%'] # 2 -operlow = ['+', '-'] # 1 -operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 - - -# разбор строки на элементы списка -def parse(xprstr): - word = '' - - # проверка недопустимых символов - exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} - xprset = set(xprstr) - if not exset.isdisjoint(xprset): - print('ERROR: unknown symbol') - exit(0) - # проверка скобок в строке - if xpr.count('(') != xpr.count(')'): - print('ERROR: brackets are not balanced') - exit(0) - - # проверка если состоит только из знаков пунктуации - punctset = set(string.punctuation) - xprset = set(xprstr) - if xprset.issubset(punctset) or xprset.issubset(funcset): - print('ERROR: no digits or functions') - exit(0) - - xprstr = xprstr.replace(' ', ' ') - xprstr = xprstr.replace(', ', ',') - xprstr = xprstr.replace(' *', '*') - xprstr = xprstr.replace('* ', '*') - xprstr = xprstr.replace(' +', '+') - xprstr = xprstr.replace('+ ', '+') - xprstr = xprstr.replace(' -', '-') - xprstr = xprstr.replace('- ', '-') - xprstr = xprstr.replace('--', '+') - xprstr = xprstr.replace('++', '+') - xprstr = xprstr.replace('+-', '-') - xprstr = xprstr.replace('-+', '-') - - # # print(xprstr) - - if xprstr[0] == '+': - xprstr = xprstr[1:] - - # проверка пробелов - if xprstr.count(' ') > 0: - print('ERROR: useles spaces') - exit(0) - - # добавление скобок для возведения в степень 2^3^4 - left = 0 - r = len(xprstr) - for x in range(xprstr.count('^')): - r = xprstr.rindex('^', 0, r) - # print('r=', r, ' ', xprstr[:r]) - if xprstr[:r].count('^') == 0: - break - left = xprstr.rindex('^', 0, r)+1 - # # print('left=', left, 'r=', r, ' ', xprstr[left:r]) - tmp = xprstr[left:r] - # # print('tmp=', tmp) - tmpset = set(tmp) - # # print('tmpset', tmpset) - # # print('operset', operset) - if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): - # # print('нада скобки для степени') - xprstr = xprstr[:left]+'('+xprstr[left:] - # # print(xprstr) - - left = r+2 - # # print(xprstr[l:]) - - r = len(xprstr) - for i, data in enumerate(xprstr[left:]): - if data in split and data != '(': - r = left+i - break - # # print('left=', left, 'r=', r, ' ', xprstr[left:r]) - tmp = xprstr[left:r] - # # print(tmp) - xprstr = xprstr[:r]+')'+xprstr[r:] - # # print(xprstr) - else: - # # print('НЕ надо скобки', left, r) - r = left - - # разбор строки - for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел - if sym in split or i == len(xprstr): - # # # print(word) - if word == 'pi': - xprlst.append(pi) - elif word == 'e': - xprlst.append(e) - elif word in funclist: - # # # print(word, ' in math') - xprlst.append(word) - elif word.replace('.', '').isdigit() and word.count('.') < 2: - xprlst.append(float(word)) - # elif word != '': - elif word in split or word == '': - pass - # # # print('ok', word) - else: - print('ERROR: wrong symbol "', word, '"') - exit(0) - xprlst.append(sym) - # # # print(xprlst) - word = '' - else: - word = word + sym - # # # print(word) - xprlst.pop() # удаляется добавленный пробел - - for i, data in enumerate(xprlst): - if xprlst[i] == '/' and xprlst[i + 1] == '/': - xprlst[i] = '//' - xprlst.pop(i + 1) - elif xprlst[i] == '>' and xprlst[i + 1] == '=': - xprlst[i] = '>=' - xprlst.pop(i + 1) - elif xprlst[i] == '<' and xprlst[i + 1] == '=': - xprlst[i] = '<=' - xprlst.pop(i + 1) - elif xprlst[i] == '=' and xprlst[i + 1] == '=' or xprlst[i] == '=': - xprlst[i] = '==' - xprlst.pop(i + 1) - elif xprlst[i] == '!' and xprlst[i + 1] == '=': - xprlst[i] = '!=' - xprlst.pop(i + 1) - elif xprlst[i] == '-' and xprlst[i - 1] in \ - ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '=')\ - and type(xprlst[i + 1]) == float: - xprlst[i + 1] = xprlst[i + 1] * - 1 - xprlst.pop(i) - elif (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] - in('*', '^', '+', '-', '(', '<', '>', '=')): - xprlst[i] = -1 - xprlst.insert(i + 1, '*') - elif xprlst[i] == '-' and xprlst[i - 1] == '/': - xprlst[i - 1] = '*' - xprlst[i] = -1 - xprlst.insert(i + 1, '/') - elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: - pass - - # # # print('ok', i) - else: - print('ERROR: unknown', xprlst[i], i) - xprset = set(xprlst) - if xprset.issubset(funcset) or xprset.issubset(operset): - print('ERROR: только функция') - exit(0) - return xprlst - - -def logargs(*args): - # # print('START logoargs', args) - if ',' in args: - res = log(args[-3], args[-1]) - else: - res = log(args[-1]) - # # print('RETURN logoargs', res) - return res - - -def operate(operator, *args): - print('OPERATOR=',operator,'ARGS=',args) - for i in args: - if not (type(i) == float or type(i) == int): - print('ERROR: operate non digits') - exit(0) - - if operator in dir(math): - result = funcdict[operator](*args) - - elif operator == "+": - result = args[0] + args[1] - elif operator == "-": - result = args[0] - args[1] - elif operator == "*": - result = args[0] * args[1] - elif operator == "//": - if args[1] != 0: - result = args[0] // args[1] - else: - print('ERROR: division by zero') - exit(0) - elif operator == "/": - if args[1] != 0: - result = args[0] / args[1] - else: - print('ERROR: division by zero') - exit(0) - elif operator == "%": - result = args[0] % args[1] - elif operator == "^": - result = args[0] ** args[1] - elif operator == "<=": - result = args[0] <= args[1] - elif operator == ">=": - result = args[0] >= args[1] - elif operator == "<": - result = args[0] < args[1] - elif operator == ">": - result = args[0] > args[1] - elif operator == "==": - result = args[0] == args[1] - elif operator == "!=": - result = args[0] != args[1] - else: - print('ERROR: unknown math operator', operator) - result = 0 - return result - - -def prior(op1, op2): - priorset = [operlowest, operlow, opermid, operhi] - for i, data in enumerate(priorset): - # # # print(op1, i, data, ) - if op1 in data: - prior1 = i - if op2 in data: - prior2 = i - # # # print(prior1 <= prior2) - return prior1 <= prior2 - - -def postfix(xprlst): - """ - преобразование инфиксной нотации в постфиксную - на входе список элементов выражения инфиксной нотации, на выходе список элементов постфиксной нотации - """ - print('START CONVERT TO POSTFIX *********************') - output = [] - stack = [] - for i in xprlst: - # # print('-----------------------------------') - # # print('i=', i) - if type(i) == float or type(i) == int: - output.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - if i == ',': - if stack != []: - while stack[-1] in oper+funclist and prior(i, stack[-1]): - # пока наверху стека оператор с большим или равным приоритетом - # # print('пока на верху стэка оператор') - # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) - output.append(stack.pop()) # переложить оператор из стека на выход - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - if stack == []: - break - output.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - - elif i in oper and i != ',': # '^', '*', '/', '+', '-' - # # print('in oper', i) - # # print(oper) - if stack == []: # если стек пуст - # # print('стек пуст. добваить оператор в стек') - stack.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - elif stack[-1] == '(': # если стек содержит ( - # # print('( положить в стек') - stack.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - else: - # # print('оператор:', i, '<=stack', stack[-1], prior(i, stack[-1])) - while stack[-1] in oper+funclist and prior(i, stack[-1]): - # пока наверху стека оператор с большим или равным приоритетом - # # print('пока на верху стэка оператор') - # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) - output.append(stack.pop()) # переложить оператор из стека на выход - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - if stack == []: - break - stack.append(i) # иначе положить оператор в стек - - # if i ==', ': - # output.append(i) # если это , то на выход - # else: - # stack.append(i) # иначе положить оператор в стек - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - - elif i == '(': - stack.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - - elif i == ')': - # # print(i) - while stack[-1] != '(': # пока верх стека не равен ( - # # print ('push stack', stack[-1]) - output.append(stack.pop()) - # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке - stack.pop() # удаление из стека ( - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - elif i in funclist: - # # print(i, 'IN FUNCLIST помещаем в стек') - stack.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - # # print('*******') - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - - stack.reverse() - pol = output + stack # poland - - # # print(xpr) - # # print('POLAND:', *pol, sep=' ') - return pol - - - - -def evalpostfix(xprpstfx): - """ - вычисление выражения в постфиксной нотации - на входе список элементов выражения - """ - print('START EVALUATE POSTFIX ********************') - stack = [] - args = [] - for i in xprpstfx: - # # print('---------------') - print('EVAL i = ', i, 'STACK=',stack) - - - - if i in funclist and i != ',': - - if stack[-2] == ',': - j=len(stack)-2 - while stack[j] == ',': - args.append(stack[j-1]) - stack.pop() - stack.pop() - j=j-2 - args.reverse() - print('j=',j+1,stack[j+1:]) - print('ARGS=',args) - print('STACK',stack) - else: - args.append(stack[-1]) - - - tmp = operate(i, *args) - print('TMP=',tmp) - args=[] - stack.append(tmp) - print('STACK',stack) - - elif i in oper and i != ',': - - print('ARGS=',args) - print('STACK',stack) - tmp = operate(i, stack[-2], stack[-1]) - print('TMP=',tmp) - stack.pop() - stack.pop() - stack.append(tmp) - - print('STACK',stack) - - - - - # - # if i in oper+['pow', 'log'] and i != ',': - # print(stack, '+++++++++ to pow or log') - # tmp = operate(i, *stack) - # # # print(i, '=', tmp) - # if ',' in stack and i in ['pow', 'log']: - # if stack[-2] == ',': - # stack.pop() - # stack.pop() - # stack.pop() - # stack.append(tmp) - # elif i in oper: - # stack.pop() - # stack.pop() - # stack.append(tmp) - # else: - # stack.pop() - # stack.append(tmp) - # # # print('stack=', stack) - # elif i in funclist and i not in ['pow', 'log']: - # tmp = operate(i, *stack) - # stack[-1] = tmp - # print('stack=', stack) - - - - else: - stack.append(i) - # # print('stack=', stack) - - return stack[0] - - -# EVAL TEST -test = xpr -test = test.replace('^', '**') -test = test.replace(' ', '') -test = test.replace(', ', '.') - -# разбор строики в список -xprlst = parse(xpr) -print(*xprlst, sep=' ') - -# преобразование инфиксного списка в постфиксных список -xprlst = postfix(xprlst) -print(*xprlst, sep=' ') - -# вычисление постфиксного списка -result = evalpostfix(xprlst) -print(result) From ad2dbe279cd2185be4854ced8caa4f3ac266a512 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 04:27:44 -0400 Subject: [PATCH 065/159] test --- final_task/pycalc.py | 67 ++++++++++++++++++++++---------------------- 1 file changed, 33 insertions(+), 34 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 7073e073..feb9c83e 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -13,7 +13,7 @@ ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') args = ap.parse_args() xpr = args.EXPRESSION -mod = args.MODULE +module = args.MODULE xprstr = '' @@ -38,23 +38,21 @@ funcset = set(funclist) opdic = { - '+':add, - '-':sub, - '*':mul, - '/':truediv, - '//':floordiv, - '^':pow, - '%':mod, - '==':eq, - '<=': le, - '>=': ge, - '<':lt, - '>': gt, - '!=':ne, - 'abs':abs, - 'round':round, - 'sum':sum - } + '+':add, + '-':sub, + '*':mul, + '/':truediv, + '//':floordiv, '%':truediv, '^':pow, + '==':eq, + '<=': le, + '>=': ge, + '<':lt, + '>': gt, + '!=':ne, + 'abs':abs, + 'round':round, + 'sum':sum + } funcdic.update(opdic) oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', ','] @@ -63,19 +61,19 @@ -def addfunc(mod): +def addfunc(module): """ добавляет новую функцию из модуля """ - if mod is not None: # если введено имя модуля - spec = importlib.util.find_spec(mod) + if module is not None: # если введено имя модуля + spec = importlib.util.find_spec(module) if spec is None: # проверка возможности импорта модуля - print('ERROR: module {} not found'.format(mod)) + print('ERROR: module {} not found'.format(module)) exit(0) else: - newfunc = importlib.import_module(mod) # импортирование нового модуля + newfunc = importlib.import_module(module) # импортирование нового модуля # # print(dir(newfunc)) - funcdic[mod] = newfunc.main - funclist.append(mod) - funcset.add(mod) + funcdic[module] = newfunc.main + funclist.append(module) + funcset.add(module) return @@ -238,13 +236,13 @@ def logargs(*args): def operate(operator, args): - # # print('OPERATOR=',operator,'ARGS=',args) + # print('OPERATOR=',operator,'ARGS=',args) if operator in ['sum', 'fsum']: - # # print('OPERATOR=',operator,'ARGS=',args) + # print('OPERATOR=',operator,'ARGS=',args) result = funcdic[operator](args) - elif operator in dir(math) + dir(operator) and operator not in ['sum', 'fsum']: - # # print('OPERATOR=',operator,'ARGS=',args, '*ARGS=',args) + elif operator in dir(math) + dir(operator)+['module'] and operator not in ['sum', 'fsum']: + # print('OPERATOR=',operator,'ARGS=',args, '*ARGS=',args) if type(args) == float or type(args) == int or type(args) == bool : result = funcdic[operator](args) else: @@ -412,18 +410,19 @@ def evalpostfix(xprpstfx): def main(): # попытка добавления внешней функции если указана -m module - addfunc(mod) + addfunc(module) # разбор строики вырыжения в список xprlst = parse(xpr) - ## print(*xprlst, sep=' ') + #print(*xprlst, sep=' ') # преобразование инфиксного списка в постфиксных список xprlst = postfix(xprlst) - ## print(*xprlst, sep=' ') + #print(*xprlst, sep=' ') # вычисление постфиксного списка - print(evalpostfix(xprlst)) + res=evalpostfix(xprlst) + print(res) return From df0b1043d8386cc4935fcf672429081dc5ff57f2 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 04:32:17 -0400 Subject: [PATCH 066/159] test --- final_task/pycalc.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index feb9c83e..a0b7bc86 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -422,8 +422,8 @@ def main(): # вычисление постфиксного списка res=evalpostfix(xprlst) - print(res) - return + #print(res) + return res -main() +print(main()) From fbaf804f7d9c93aa1df0ade105ea45d695d6bb7a Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 04:38:33 -0400 Subject: [PATCH 067/159] test --- final_task/pycalc.py | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index a0b7bc86..2c7bb42b 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -408,22 +408,18 @@ def evalpostfix(xprpstfx): # test = test.replace(' ', '') # test = test.replace(', ', '.') -def main(): - # попытка добавления внешней функции если указана -m module - addfunc(module) - - # разбор строики вырыжения в список - xprlst = parse(xpr) - #print(*xprlst, sep=' ') - - # преобразование инфиксного списка в постфиксных список - xprlst = postfix(xprlst) - #print(*xprlst, sep=' ') - - # вычисление постфиксного списка - res=evalpostfix(xprlst) - #print(res) - return res +# попытка добавления внешней функции если указана -m module +addfunc(module) + +# разбор строики вырыжения в список +xprlst = parse(xpr) +#print(*xprlst, sep=' ') + +# преобразование инфиксного списка в постфиксных список +xprlst = postfix(xprlst) +#print(*xprlst, sep=' ') -print(main()) +# вычисление постфиксного списка +res=evalpostfix(xprlst) +print(res) From 79d156723b8fc52c3aa487e0830e765a4c0b656d Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 04:44:08 -0400 Subject: [PATCH 068/159] test --- final_task/pycalc.py | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 2c7bb42b..dd0ed8d2 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -42,7 +42,9 @@ '-':sub, '*':mul, '/':truediv, - '//':floordiv, '%':truediv, '^':pow, + '//':floordiv, + '%':mod, + '^':pow, '==':eq, '<=': le, '>=': ge, @@ -408,18 +410,21 @@ def evalpostfix(xprpstfx): # test = test.replace(' ', '') # test = test.replace(', ', '.') +def main(): + # попытка добавления внешней функции если указана -m module + addfunc(module) -# попытка добавления внешней функции если указана -m module -addfunc(module) + # разбор строики вырыжения в список + xprlst = parse(xpr) + #print(*xprlst, sep=' ') -# разбор строики вырыжения в список -xprlst = parse(xpr) -#print(*xprlst, sep=' ') + # преобразование инфиксного списка в постфиксных список + xprlst = postfix(xprlst) + #print(*xprlst, sep=' ') -# преобразование инфиксного списка в постфиксных список -xprlst = postfix(xprlst) -#print(*xprlst, sep=' ') + # вычисление постфиксного списка + res=evalpostfix(xprlst) + print(res) + return res -# вычисление постфиксного списка -res=evalpostfix(xprlst) -print(res) +main() From 81e54c4bb58975399fdbf3ea11827bfa87053849 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 04:47:22 -0400 Subject: [PATCH 069/159] test --- final_task/pycalc.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index dd0ed8d2..98a897a2 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -424,7 +424,9 @@ def main(): # вычисление постфиксного списка res=evalpostfix(xprlst) - print(res) + #print(res) return res -main() +res = main() +print(res) + From 0483c61ffb91952bc76c9afb75346046a13f2a69 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 15:29:22 -0400 Subject: [PATCH 070/159] test --- final_task/func1.py | 5 --- final_task/func2.py | 5 --- final_task/myfunc2.py | 16 -------- final_task/pycalc.py | 90 +++++++++++++++++++++++-------------------- 4 files changed, 48 insertions(+), 68 deletions(-) delete mode 100644 final_task/func1.py delete mode 100644 final_task/func2.py delete mode 100644 final_task/myfunc2.py diff --git a/final_task/func1.py b/final_task/func1.py deleted file mode 100644 index 3e2f3065..00000000 --- a/final_task/func1.py +++ /dev/null @@ -1,5 +0,0 @@ -def main(x): - x = (x + x) * x - return x - - diff --git a/final_task/func2.py b/final_task/func2.py deleted file mode 100644 index 558633fc..00000000 --- a/final_task/func2.py +++ /dev/null @@ -1,5 +0,0 @@ -def main(x, y): - x = (x + y) * 2 - return x - - diff --git a/final_task/myfunc2.py b/final_task/myfunc2.py deleted file mode 100644 index 9b2b08e7..00000000 --- a/final_task/myfunc2.py +++ /dev/null @@ -1,16 +0,0 @@ -ss=[] -s=[0,",",3,2,',',3,4,6] -s=[2,',',1] -#s=[1,2,3,4] -i=len(s)-2 -ss.append(s[-1]) -print(*s,sep=' ') -print(i,s[i]) -while s[i] == ',': - ss.append(s[i-1]) - i=i-2 - print(i, s[i]) -print('out',i) -print(*s[i+1:],sep=' ') -ss.reverse() -print(ss) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 98a897a2..d983833e 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -15,58 +15,51 @@ xpr = args.EXPRESSION module = args.MODULE - xprstr = '' operator = '' xprlst = [] a = 0. b = 0. result = 0. - - funcset = {} operset = {} splitset = {} - - - split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') splitset = set(split) - funclist = dir(math)+['abs', 'round', 'sum'] # list of math functions names funcdic = math.__dict__ # dict of math functions funcset = set(funclist) - opdic = { - '+':add, - '-':sub, - '*':mul, - '/':truediv, - '//':floordiv, - '%':mod, - '^':pow, - '==':eq, + '+': add, + '-': sub, + '*': mul, + '/': truediv, + '//': floordiv, + '%': mod, + '^': pow, + '==': eq, '<=': le, '>=': ge, - '<':lt, + '<': lt, '>': gt, - '!=':ne, - 'abs':abs, - 'round':round, - 'sum':sum + '!=': ne, + 'abs': abs, + 'round': round, + 'sum': sum } funcdic.update(opdic) - oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', ','] operset = set(oper) - - def addfunc(module): """ добавляет новую функцию из модуля """ if module is not None: # если введено имя модуля - spec = importlib.util.find_spec(module) + try: + spec = importlib.util.find_spec(module) + except: + print('ERROR: module ', module,'not found, or unknown symbol') + exit(0) if spec is None: # проверка возможности импорта модуля print('ERROR: module {} not found'.format(module)) exit(0) @@ -175,14 +168,14 @@ def parse(xprstr): else: addfunc(word) # импортировать неизвестную функцию xprlst.append(word) - #print('ERROR: wrong symbol "', word, '"') - #exit(0) + # print('ERROR: wrong symbol "', word, '"') + # exit(0) xprlst.append(sym) - # # # # print(xprlst) + # print(xprlst) word = '' else: word = word + sym - # # # # print(word) + # print(word) xprlst.pop() # удаляется добавленный пробел for i, data in enumerate(xprlst): @@ -242,13 +235,25 @@ def operate(operator, args): if operator in ['sum', 'fsum']: # print('OPERATOR=',operator,'ARGS=',args) - result = funcdic[operator](args) + try: + result = funcdic[operator](args) + except: + print('ERROR: invalid argument for ', operator) + exit(0) elif operator in dir(math) + dir(operator)+['module'] and operator not in ['sum', 'fsum']: # print('OPERATOR=',operator,'ARGS=',args, '*ARGS=',args) - if type(args) == float or type(args) == int or type(args) == bool : - result = funcdic[operator](args) + if type(args) == float or type(args) == int or type(args) == bool: + try: + result = funcdic[operator](args) + except: + print('ERROR: invalid argument for ', operator) + exit(0) else: - result = funcdic[operator](*args) + try: + result = funcdic[operator](*args) + except: + print('ERROR: invalid argument for ', operator) + exit(0) # else: # уже проверяется в парсинге и попыика импортировать модуль # print('ERROR: unknown math operator', operator) # result = 0 @@ -373,20 +378,20 @@ def evalpostfix(xprpstfx): # # print('EVAL i = ', i, 'STACK=',stack) if i in funclist and i != ',': if len(stack) < 2: - stack[0] = operate(i,stack[0]) + stack[0] = operate(i, stack[0]) else: - j=len(stack)-2 + j = len(stack)-2 args.append(stack[-1]) while stack[j] == ',': args.append(stack[j-1]) stack.pop() stack.pop() - j=j-2 + j = j - 2 stack.pop() args.reverse() - tmp = operate(i,args) + tmp = operate(i, args) # print('TMP=',tmp) - args=[] + args = [] stack.append(tmp) # print('STACK',stack) @@ -416,17 +421,18 @@ def main(): # разбор строики вырыжения в список xprlst = parse(xpr) - #print(*xprlst, sep=' ') + # print(*xprlst, sep=' ') # преобразование инфиксного списка в постфиксных список xprlst = postfix(xprlst) - #print(*xprlst, sep=' ') + # print(*xprlst, sep=' ') # вычисление постфиксного списка - res=evalpostfix(xprlst) - #print(res) + res = evalpostfix(xprlst) + # print(res) return res + res = main() print(res) From 3e82ca7fc1c8ae211db0c77be33cf890eb510f1d Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 15:46:38 -0400 Subject: [PATCH 071/159] test --- final_task/pycalc.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index d983833e..a1967a22 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -57,8 +57,8 @@ def addfunc(module): if module is not None: # если введено имя модуля try: spec = importlib.util.find_spec(module) - except: - print('ERROR: module ', module,'not found, or unknown symbol') + except ImportError: + print('ERROR: module ', module, 'not found, or unknown symbol') exit(0) if spec is None: # проверка возможности импорта модуля print('ERROR: module {} not found'.format(module)) @@ -237,7 +237,7 @@ def operate(operator, args): # print('OPERATOR=',operator,'ARGS=',args) try: result = funcdic[operator](args) - except: + except ArithmeticError: print('ERROR: invalid argument for ', operator) exit(0) elif operator in dir(math) + dir(operator)+['module'] and operator not in ['sum', 'fsum']: @@ -245,13 +245,19 @@ def operate(operator, args): if type(args) == float or type(args) == int or type(args) == bool: try: result = funcdic[operator](args) - except: + except ImportError: + print('ERROR: invalid argument for ', operator) + exit(0) + except ValueError: print('ERROR: invalid argument for ', operator) exit(0) else: try: result = funcdic[operator](*args) - except: + except ArithmeticError: + print('ERROR: invalid argument for ', operator) + exit(0) + except ValueError: print('ERROR: invalid argument for ', operator) exit(0) # else: # уже проверяется в парсинге и попыика импортировать модуль From 0800c7c5e349b8ce1b2d802d47fcb1c0d474a694 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 15:50:32 -0400 Subject: [PATCH 072/159] test --- final_task/pycalc.py | 1 - 1 file changed, 1 deletion(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index a1967a22..a253bd21 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -441,4 +441,3 @@ def main(): res = main() print(res) - From 9f5ab156f62d3005b9b6930e9c74e3e7539fc696 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 16:45:59 -0400 Subject: [PATCH 073/159] test --- final_task/pycalc.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index a253bd21..ede07761 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -16,7 +16,7 @@ module = args.MODULE xprstr = '' -operator = '' + xprlst = [] a = 0. b = 0. @@ -78,8 +78,7 @@ def parse(xprstr): word = '' exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} xprset = set(xprstr) - - # проверка если строка выражения содержит недопустимые символы + # проверка если строка выражения содержит недопустимые символы if not exset.isdisjoint(xprset): print('ERROR: unknown symbol') exit(0) From e1d0c0043a0837a5cb9013cfea422b9af56e25f8 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 16:54:51 -0400 Subject: [PATCH 074/159] test --- final_task/pycalc.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index ede07761..a21e5818 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -398,19 +398,13 @@ def evalpostfix(xprpstfx): # print('TMP=',tmp) args = [] stack.append(tmp) - - # print('STACK',stack) - elif i in oper and i != ',': tmp = operate(i, stack[-2:]) stack.pop() stack.pop() stack.append(tmp) - # print('STACK',stack) - else: stack.append(i) - return stack[0] From 5181ee054971ab10ce6c9f75622ba074e81a7bed Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 17:09:03 -0400 Subject: [PATCH 075/159] test --- final_task/pycalc.py | 1 - 1 file changed, 1 deletion(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index a21e5818..35f0a106 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -407,7 +407,6 @@ def evalpostfix(xprpstfx): stack.append(i) return stack[0] - # EVAL TEST # test = xpr # test = test.replace('^', '**') From a0deeed1a5fcdb3cb1471a85b3e367c18ce6d535 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 17:12:50 -0400 Subject: [PATCH 076/159] test --- final_task/pycalc.py | 442 +++++++++++++++++++++---------------------- 1 file changed, 211 insertions(+), 231 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 35f0a106..82e93c22 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,11 +1,6 @@ -# test 26 apr import argparse import math -import operator -from operator import * import string -import importlib -import importlib.util from math import * ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') @@ -13,72 +8,41 @@ ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') args = ap.parse_args() xpr = args.EXPRESSION -module = args.MODULE -xprstr = '' +funcset = {} +operset = {} +splitset = {} +split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') +splitset = set(split) + +funclist = dir(math)+['abs', 'round'] # list of math functions names +funcdict = math.__dict__ # dict of math functions +funcdict['abs'] = abs +funcdict['round'] = round +xprstr = '' +operator = '' xprlst = [] a = 0. b = 0. result = 0. -funcset = {} -operset = {} -splitset = {} -split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') -splitset = set(split) -funclist = dir(math)+['abs', 'round', 'sum'] # list of math functions names -funcdic = math.__dict__ # dict of math functions funcset = set(funclist) -opdic = { - '+': add, - '-': sub, - '*': mul, - '/': truediv, - '//': floordiv, - '%': mod, - '^': pow, - '==': eq, - '<=': le, - '>=': ge, - '<': lt, - '>': gt, - '!=': ne, - 'abs': abs, - 'round': round, - 'sum': sum - } -funcdic.update(opdic) + oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', ','] operset = set(oper) +operhi = ['^'] + funclist # 3 +opermid = ['*', '/', '%'] # 2 +operlow = ['+', '-'] # 1 +operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 -def addfunc(module): - """ добавляет новую функцию из модуля """ - if module is not None: # если введено имя модуля - try: - spec = importlib.util.find_spec(module) - except ImportError: - print('ERROR: module ', module, 'not found, or unknown symbol') - exit(0) - if spec is None: # проверка возможности импорта модуля - print('ERROR: module {} not found'.format(module)) - exit(0) - else: - newfunc = importlib.import_module(module) # импортирование нового модуля - # # print(dir(newfunc)) - funcdic[module] = newfunc.main - funclist.append(module) - funcset.add(module) - return - - +# разбор строки на элементы списка def parse(xprstr): - """ парсинг строки математического выражения. - на выходе список в инфиксной нотации""" word = '' + + # проверка недопустимых символов exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} xprset = set(xprstr) - # проверка если строка выражения содержит недопустимые символы if not exset.isdisjoint(xprset): print('ERROR: unknown symbol') exit(0) @@ -86,8 +50,11 @@ def parse(xprstr): if xpr.count('(') != xpr.count(')'): print('ERROR: brackets are not balanced') exit(0) - # проверка если выражение состоит только из знаков пунктуации - if xprset.issubset(string.punctuation) or xprset.issubset(funcset): + + # проверка если состоит только из знаков пунктуации + punctset = set(string.punctuation) + xprset = set(xprstr) + if xprset.issubset(punctset) or xprset.issubset(funcset): print('ERROR: no digits or functions') exit(0) @@ -104,77 +71,79 @@ def parse(xprstr): xprstr = xprstr.replace('+-', '-') xprstr = xprstr.replace('-+', '-') + # # print(xprstr) + if xprstr[0] == '+': xprstr = xprstr[1:] - # проверка лишних пробелов + # проверка пробелов if xprstr.count(' ') > 0: print('ERROR: useles spaces') exit(0) # добавление скобок для возведения в степень 2^3^4 - lt = 0 - rt = len(xprstr) + left = 0 + r = len(xprstr) for x in range(xprstr.count('^')): - rt = xprstr.rindex('^', 0, rt) - # # print('rt=', rt, ' ', xprstr[:rt]) - if xprstr[:rt].count('^') == 0: + r = xprstr.rindex('^', 0, r) + # print('r=', r, ' ', xprstr[:r]) + if xprstr[:r].count('^') == 0: break - lt = xprstr.rindex('^', 0, rt)+1 - # # # print('lt=', lt, 'rt=', rt, ' ', xprstr[lt:rt]) - tmp = xprstr[lt:rt] - # # # print('tmp=', tmp) + left = xprstr.rindex('^', 0, r)+1 + # # print('left=', left, 'r=', r, ' ', xprstr[left:r]) + tmp = xprstr[left:r] + # # print('tmp=', tmp) tmpset = set(tmp) - # # # print('tmpset', tmpset) - # # # print('operset', operset) + # # print('tmpset', tmpset) + # # print('operset', operset) if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): - # # # print('нада скобки для степени') - xprstr = xprstr[:lt]+'('+xprstr[lt:] - # # # print(xprstr) - lt = rt+2 - # # # print(xprstr[l:]) - rt = len(xprstr) - for i, data in enumerate(xprstr[lt:]): + # # print('нада скобки для степени') + xprstr = xprstr[:left]+'('+xprstr[left:] + # # print(xprstr) + + left = r+2 + # # print(xprstr[l:]) + + r = len(xprstr) + for i, data in enumerate(xprstr[left:]): if data in split and data != '(': - rt = lt+i + r = left+i break - # # # print('lt=', lt, 'rt=', rt, ' ', xprstr[lt:rt]) - tmp = xprstr[lt:rt] - # # # print(tmp) - xprstr = xprstr[:rt]+')'+xprstr[rt:] - # # # print(xprstr) + # # print('left=', left, 'r=', r, ' ', xprstr[left:r]) + tmp = xprstr[left:r] + # # print(tmp) + xprstr = xprstr[:r]+')'+xprstr[r:] + # # print(xprstr) else: - # # # print('НЕ надо скобки', lt, rt) - rt = lt + # # print('НЕ надо скобки', left, r) + r = left # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): - # # # # print(word) + # # # print(word) if word == 'pi': xprlst.append(pi) elif word == 'e': xprlst.append(e) elif word in funclist: - # # # # print(word, ' in math') + # # # print(word, ' in math') xprlst.append(word) elif word.replace('.', '').isdigit() and word.count('.') < 2: xprlst.append(float(word)) # elif word != '': elif word in split or word == '': pass - # # # # print('ok', word) + # # # print('ok', word) else: - addfunc(word) # импортировать неизвестную функцию - xprlst.append(word) - # print('ERROR: wrong symbol "', word, '"') - # exit(0) + print('ERROR: wrong symbol "', word, '"') + exit(0) xprlst.append(sym) - # print(xprlst) + # # # print(xprlst) word = '' else: word = word + sym - # print(word) + # # # print(word) xprlst.pop() # удаляется добавленный пробел for i, data in enumerate(xprlst): @@ -209,7 +178,7 @@ def parse(xprstr): elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: pass - # # # # print('ok', i) + # # # print('ok', i) else: print('ERROR: unknown', xprlst[i], i) xprset = set(xprlst) @@ -220,118 +189,140 @@ def parse(xprstr): def logargs(*args): - # # # print('START logoargs', args) + # # print('START logoargs', args) if ',' in args: res = log(args[-3], args[-1]) else: res = log(args[-1]) - # # # print('RETURN logoargs', res) + # # print('RETURN logoargs', res) return res -def operate(operator, args): - # print('OPERATOR=',operator,'ARGS=',args) +def operate(operator, *args): - if operator in ['sum', 'fsum']: - # print('OPERATOR=',operator,'ARGS=',args) - try: - result = funcdic[operator](args) - except ArithmeticError: - print('ERROR: invalid argument for ', operator) + for i in args: + if not (type(i) == float or type(i) == int or i == ','): + print('ERROR: operate non digits') exit(0) - elif operator in dir(math) + dir(operator)+['module'] and operator not in ['sum', 'fsum']: - # print('OPERATOR=',operator,'ARGS=',args, '*ARGS=',args) - if type(args) == float or type(args) == int or type(args) == bool: - try: - result = funcdic[operator](args) - except ImportError: - print('ERROR: invalid argument for ', operator) - exit(0) - except ValueError: - print('ERROR: invalid argument for ', operator) - exit(0) + + if operator in dir(math) and operator not in ['pow', 'log']: + result = funcdict[operator](args[-1]) + elif operator == "pow": + if len(args) == 3: + result = pow(args[-3], args[-1]) else: - try: - result = funcdic[operator](*args) - except ArithmeticError: - print('ERROR: invalid argument for ', operator) - exit(0) - except ValueError: - print('ERROR: invalid argument for ', operator) - exit(0) - # else: # уже проверяется в парсинге и попыика импортировать модуль - # print('ERROR: unknown math operator', operator) - # result = 0 + print('ERROR: wrong arguments') + exit(0) + elif operator == "log": + result = logargs(*args) + elif len(args) < 2: + print('ERROR: no arguments') + exit(0) + elif operator == "+": + result = args[-2] + args[-1] + elif operator == "-": + result = args[-2] - args[-1] + elif operator == "*": + result = args[-2] * args[-1] + elif operator == "//": + if args[-1] != 0: + result = args[-2] // args[-1] + else: + print('ERROR: division by zero') + exit(0) + elif operator == "/": + if args[-1] != 0: + result = args[-2] / args[-1] + else: + print('ERROR: division by zero') + exit(0) + elif operator == "%": + result = args[-2] % args[-1] + elif operator == "^": + result = args[-2] ** args[-1] + elif operator == "<=": + result = args[-2] <= args[-1] + elif operator == ">=": + result = args[-2] >= args[-1] + elif operator == "<": + result = args[-2] < args[-1] + elif operator == ">": + result = args[-2] > args[-1] + elif operator == "==": + result = args[-2] == args[-1] + elif operator == "!=": + result = args[-2] != args[-1] + else: + print('ERROR: unknown math operator', operator) + result = 0 return result def prior(op1, op2): - """ сравнивает приоритеты математических опрераторов и функций op1 <= op2, возвращает bool """ - operhi = ['^'] + funclist # 3 - opermid = ['*', '/', '%'] # 2 - operlow = ['+', '-'] # 1 - operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 priorset = [operlowest, operlow, opermid, operhi] for i, data in enumerate(priorset): + # # # print(op1, i, data, ) if op1 in data: - pr1 = i + prior1 = i if op2 in data: - pr2 = i - return pr1 <= pr2 + prior2 = i + # # # print(prior1 <= prior2) + return prior1 <= prior2 + +# основная функция +def main(xpr): + # разбор строики в список + xprlst = parse(xpr) + # # print(*xprlst, sep=' ') -def postfix(xprlst): - """ - преобразование инфиксной нотации в постфиксную - на входе список элементов выражения инфиксной нотации, на выходе список элементов постфиксной нотации - """ - # print('START CONVERT TO POSTFIX *********************') output = [] stack = [] for i in xprlst: - # # # print('-----------------------------------') - # # # print('i=', i) + # # print('-----------------------------------') + # # print('i=', i) if type(i) == float or type(i) == int: output.append(i) - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') if i == ',': if stack != []: while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом - # # # print('пока на верху стэка оператор') - # # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) + # # print('пока на верху стэка оператор') + # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) output.append(stack.pop()) # переложить оператор из стека на выход - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') if stack == []: break output.append(i) - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') elif i in oper and i != ',': # '^', '*', '/', '+', '-' - # # # print('in oper', i) - # # # print(oper) + + # # print('in oper', i) + # # print(oper) if stack == []: # если стек пуст - # # # print('стек пуст. добваить оператор в стек') + # # print('стек пуст. добваить оператор в стек') stack.append(i) - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') elif stack[-1] == '(': # если стек содержит ( - # # # print('( положить в стек') + # # print('( положить в стек') stack.append(i) - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') else: - # # # print('оператор:', i, '<=stack', stack[-1], prior(i, stack[-1])) + # # print('оператор:', i, '<=stack', stack[-1], prior(i, stack[-1])) while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом - # # # print('пока на верху стэка оператор') - # # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) + # # print('пока на верху стэка оператор') + # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) output.append(stack.pop()) # переложить оператор из стека на выход - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') if stack == []: break stack.append(i) # иначе положить оператор в стек @@ -340,96 +331,85 @@ def postfix(xprlst): # output.append(i) # если это , то на выход # else: # stack.append(i) # иначе положить оператор в стек - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') elif i == '(': stack.append(i) - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') elif i == ')': - # # # print(i) + # # print(i) while stack[-1] != '(': # пока верх стека не равен ( - # # # print ('push stack', stack[-1]) + # # print ('push stack', stack[-1]) output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке stack.pop() # удаление из стека ( - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') elif i in funclist: - # # # print(i, 'IN FUNCLIST помещаем в стек') + # # print(i, 'IN FUNCLIST помещаем в стек') stack.append(i) - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') - # # # print('*******') - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + # # print('*******') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') stack.reverse() - return output + stack + pol = output + stack # poland + # # print(xpr) + # # print('POLAND:', *pol, sep=' ') + # # print('START CALCULATE *****************') -def evalpostfix(xprpstfx): - """ - вычисление выражения в постфиксной нотации - на входе список элементов выражения - """ - # print('START EVALUATE POSTFIX ********************') + output = [] stack = [] - args = [] - for i in xprpstfx: - # # # print('---------------') - # # print('EVAL i = ', i, 'STACK=',stack) - if i in funclist and i != ',': - if len(stack) < 2: - stack[0] = operate(i, stack[0]) - else: - j = len(stack)-2 - args.append(stack[-1]) - while stack[j] == ',': - args.append(stack[j-1]) + + for i in pol: + # # print('---------------') + # # print('i in pol = ', i) + if i in oper+['pow', 'log'] and i != ',': + # # print(stack, '+++++++++ to pow or log') + tmp = operate(i, *stack) + # # print(i, '=', tmp) + if ',' in stack and i in ['pow', 'log']: + if stack[-2] == ',': stack.pop() stack.pop() - j = j - 2 + stack.pop() + stack.append(tmp) + elif i in oper: + stack.pop() stack.pop() - args.reverse() - tmp = operate(i, args) - # print('TMP=',tmp) - args = [] stack.append(tmp) - elif i in oper and i != ',': - tmp = operate(i, stack[-2:]) - stack.pop() - stack.pop() - stack.append(tmp) + else: + stack.pop() + stack.append(tmp) + # # print('stack=', stack) + elif i in funclist and i not in ['pow', 'log']: + tmp = operate(i, *stack) + stack[-1] = tmp + # # print('stack=', stack) + # elif i in ['pow', 'log']: + # # # print('DOBL') + # tmp = operate(i, *stack) + # stack.pop() + # stack.pop() + # stack[-1] = tmp + # # # print('stack=', stack) else: stack.append(i) - return stack[0] - -# EVAL TEST -# test = xpr -# test = test.replace('^', '**') -# test = test.replace(' ', '') -# test = test.replace(', ', '.') - -def main(): - # попытка добавления внешней функции если указана -m module - addfunc(module) - - # разбор строики вырыжения в список - xprlst = parse(xpr) - # print(*xprlst, sep=' ') + # # print('stack=', stack) - # преобразование инфиксного списка в постфиксных список - xprlst = postfix(xprlst) - # print(*xprlst, sep=' ') + return stack[0] - # вычисление постфиксного списка - res = evalpostfix(xprlst) - # print(res) - return res +# EVAL TEST +test = xpr +test = test.replace('^', '**') +test = test.replace(' ', '') +test = test.replace(', ', '.') -res = main() -print(res) +print(main(xpr)) From 602d74345afb84499292b2a3533f9caf33c2c035 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 17:25:29 -0400 Subject: [PATCH 077/159] test --- final_task/{pycalc.py => pycalc final.py} | 6 +- final_task/pycalc pol stable v1.py | 415 ++++++++++++++++++++++ 2 files changed, 417 insertions(+), 4 deletions(-) rename final_task/{pycalc.py => pycalc final.py} (99%) create mode 100644 final_task/pycalc pol stable v1.py diff --git a/final_task/pycalc.py b/final_task/pycalc final.py similarity index 99% rename from final_task/pycalc.py rename to final_task/pycalc final.py index a21e5818..fada93fe 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc final.py @@ -407,14 +407,13 @@ def evalpostfix(xprpstfx): stack.append(i) return stack[0] - # EVAL TEST # test = xpr # test = test.replace('^', '**') # test = test.replace(' ', '') # test = test.replace(', ', '.') -def main(): +def main(xpr): # попытка добавления внешней функции если указана -m module addfunc(module) @@ -432,5 +431,4 @@ def main(): return res -res = main() -print(res) +print(main(xpr)) diff --git a/final_task/pycalc pol stable v1.py b/final_task/pycalc pol stable v1.py new file mode 100644 index 00000000..82e93c22 --- /dev/null +++ b/final_task/pycalc pol stable v1.py @@ -0,0 +1,415 @@ +import argparse +import math +import string +from math import * + +ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') +ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') +ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') +args = ap.parse_args() +xpr = args.EXPRESSION + +funcset = {} +operset = {} +splitset = {} + +split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') +splitset = set(split) + +funclist = dir(math)+['abs', 'round'] # list of math functions names +funcdict = math.__dict__ # dict of math functions +funcdict['abs'] = abs +funcdict['round'] = round +xprstr = '' +operator = '' +xprlst = [] +a = 0. +b = 0. +result = 0. +funcset = set(funclist) + +oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', ','] +operset = set(oper) +operhi = ['^'] + funclist # 3 +opermid = ['*', '/', '%'] # 2 +operlow = ['+', '-'] # 1 +operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 + + +# разбор строки на элементы списка +def parse(xprstr): + word = '' + + # проверка недопустимых символов + exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} + xprset = set(xprstr) + if not exset.isdisjoint(xprset): + print('ERROR: unknown symbol') + exit(0) + # проверка скобок в строке + if xpr.count('(') != xpr.count(')'): + print('ERROR: brackets are not balanced') + exit(0) + + # проверка если состоит только из знаков пунктуации + punctset = set(string.punctuation) + xprset = set(xprstr) + if xprset.issubset(punctset) or xprset.issubset(funcset): + print('ERROR: no digits or functions') + exit(0) + + xprstr = xprstr.replace(' ', ' ') + xprstr = xprstr.replace(', ', ',') + xprstr = xprstr.replace(' *', '*') + xprstr = xprstr.replace('* ', '*') + xprstr = xprstr.replace(' +', '+') + xprstr = xprstr.replace('+ ', '+') + xprstr = xprstr.replace(' -', '-') + xprstr = xprstr.replace('- ', '-') + xprstr = xprstr.replace('--', '+') + xprstr = xprstr.replace('++', '+') + xprstr = xprstr.replace('+-', '-') + xprstr = xprstr.replace('-+', '-') + + # # print(xprstr) + + if xprstr[0] == '+': + xprstr = xprstr[1:] + + # проверка пробелов + if xprstr.count(' ') > 0: + print('ERROR: useles spaces') + exit(0) + + # добавление скобок для возведения в степень 2^3^4 + left = 0 + r = len(xprstr) + for x in range(xprstr.count('^')): + r = xprstr.rindex('^', 0, r) + # print('r=', r, ' ', xprstr[:r]) + if xprstr[:r].count('^') == 0: + break + left = xprstr.rindex('^', 0, r)+1 + # # print('left=', left, 'r=', r, ' ', xprstr[left:r]) + tmp = xprstr[left:r] + # # print('tmp=', tmp) + tmpset = set(tmp) + # # print('tmpset', tmpset) + # # print('operset', operset) + if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): + # # print('нада скобки для степени') + xprstr = xprstr[:left]+'('+xprstr[left:] + # # print(xprstr) + + left = r+2 + # # print(xprstr[l:]) + + r = len(xprstr) + for i, data in enumerate(xprstr[left:]): + if data in split and data != '(': + r = left+i + break + # # print('left=', left, 'r=', r, ' ', xprstr[left:r]) + tmp = xprstr[left:r] + # # print(tmp) + xprstr = xprstr[:r]+')'+xprstr[r:] + # # print(xprstr) + else: + # # print('НЕ надо скобки', left, r) + r = left + + # разбор строки + for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел + if sym in split or i == len(xprstr): + # # # print(word) + if word == 'pi': + xprlst.append(pi) + elif word == 'e': + xprlst.append(e) + elif word in funclist: + # # # print(word, ' in math') + xprlst.append(word) + elif word.replace('.', '').isdigit() and word.count('.') < 2: + xprlst.append(float(word)) + # elif word != '': + elif word in split or word == '': + pass + # # # print('ok', word) + else: + print('ERROR: wrong symbol "', word, '"') + exit(0) + xprlst.append(sym) + # # # print(xprlst) + word = '' + else: + word = word + sym + # # # print(word) + xprlst.pop() # удаляется добавленный пробел + + for i, data in enumerate(xprlst): + if xprlst[i] == '/' and xprlst[i + 1] == '/': + xprlst[i] = '//' + xprlst.pop(i + 1) + elif xprlst[i] == '>' and xprlst[i + 1] == '=': + xprlst[i] = '>=' + xprlst.pop(i + 1) + elif xprlst[i] == '<' and xprlst[i + 1] == '=': + xprlst[i] = '<=' + xprlst.pop(i + 1) + elif xprlst[i] == '=' and xprlst[i + 1] == '=' or xprlst[i] == '=': + xprlst[i] = '==' + xprlst.pop(i + 1) + elif xprlst[i] == '!' and xprlst[i + 1] == '=': + xprlst[i] = '!=' + xprlst.pop(i + 1) + elif xprlst[i] == '-' and xprlst[i - 1] in \ + ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '=')\ + and type(xprlst[i + 1]) == float: + xprlst[i + 1] = xprlst[i + 1] * - 1 + xprlst.pop(i) + elif (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] + in('*', '^', '+', '-', '(', '<', '>', '=')): + xprlst[i] = -1 + xprlst.insert(i + 1, '*') + elif xprlst[i] == '-' and xprlst[i - 1] == '/': + xprlst[i - 1] = '*' + xprlst[i] = -1 + xprlst.insert(i + 1, '/') + elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: + pass + + # # # print('ok', i) + else: + print('ERROR: unknown', xprlst[i], i) + xprset = set(xprlst) + if xprset.issubset(funcset) or xprset.issubset(operset): + print('ERROR: только функция') + exit(0) + return xprlst + + +def logargs(*args): + # # print('START logoargs', args) + if ',' in args: + res = log(args[-3], args[-1]) + else: + res = log(args[-1]) + # # print('RETURN logoargs', res) + return res + + +def operate(operator, *args): + + for i in args: + if not (type(i) == float or type(i) == int or i == ','): + print('ERROR: operate non digits') + exit(0) + + if operator in dir(math) and operator not in ['pow', 'log']: + result = funcdict[operator](args[-1]) + elif operator == "pow": + if len(args) == 3: + result = pow(args[-3], args[-1]) + else: + print('ERROR: wrong arguments') + exit(0) + elif operator == "log": + result = logargs(*args) + elif len(args) < 2: + print('ERROR: no arguments') + exit(0) + elif operator == "+": + result = args[-2] + args[-1] + elif operator == "-": + result = args[-2] - args[-1] + elif operator == "*": + result = args[-2] * args[-1] + elif operator == "//": + if args[-1] != 0: + result = args[-2] // args[-1] + else: + print('ERROR: division by zero') + exit(0) + elif operator == "/": + if args[-1] != 0: + result = args[-2] / args[-1] + else: + print('ERROR: division by zero') + exit(0) + elif operator == "%": + result = args[-2] % args[-1] + elif operator == "^": + result = args[-2] ** args[-1] + elif operator == "<=": + result = args[-2] <= args[-1] + elif operator == ">=": + result = args[-2] >= args[-1] + elif operator == "<": + result = args[-2] < args[-1] + elif operator == ">": + result = args[-2] > args[-1] + elif operator == "==": + result = args[-2] == args[-1] + elif operator == "!=": + result = args[-2] != args[-1] + else: + print('ERROR: unknown math operator', operator) + result = 0 + return result + + +def prior(op1, op2): + priorset = [operlowest, operlow, opermid, operhi] + for i, data in enumerate(priorset): + # # # print(op1, i, data, ) + if op1 in data: + prior1 = i + if op2 in data: + prior2 = i + # # # print(prior1 <= prior2) + return prior1 <= prior2 + + +# основная функция +def main(xpr): + # разбор строики в список + xprlst = parse(xpr) + # # print(*xprlst, sep=' ') + + output = [] + stack = [] + for i in xprlst: + # # print('-----------------------------------') + # # print('i=', i) + if type(i) == float or type(i) == int: + output.append(i) + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + if i == ',': + if stack != []: + while stack[-1] in oper+funclist and prior(i, stack[-1]): + # пока наверху стека оператор с большим или равным приоритетом + # # print('пока на верху стэка оператор') + # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) + output.append(stack.pop()) # переложить оператор из стека на выход + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + if stack == []: + break + output.append(i) + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + + elif i in oper and i != ',': # '^', '*', '/', '+', '-' + + # # print('in oper', i) + # # print(oper) + if stack == []: # если стек пуст + # # print('стек пуст. добваить оператор в стек') + stack.append(i) + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + elif stack[-1] == '(': # если стек содержит ( + # # print('( положить в стек') + stack.append(i) + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + else: + # # print('оператор:', i, '<=stack', stack[-1], prior(i, stack[-1])) + while stack[-1] in oper+funclist and prior(i, stack[-1]): + # пока наверху стека оператор с большим или равным приоритетом + # # print('пока на верху стэка оператор') + # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) + output.append(stack.pop()) # переложить оператор из стека на выход + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + if stack == []: + break + stack.append(i) # иначе положить оператор в стек + + # if i ==', ': + # output.append(i) # если это , то на выход + # else: + # stack.append(i) # иначе положить оператор в стек + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + + elif i == '(': + stack.append(i) + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + + elif i == ')': + # # print(i) + while stack[-1] != '(': # пока верх стека не равен ( + # # print ('push stack', stack[-1]) + output.append(stack.pop()) + # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке + stack.pop() # удаление из стека ( + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + elif i in funclist: + # # print(i, 'IN FUNCLIST помещаем в стек') + stack.append(i) + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + # # print('*******') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') + + stack.reverse() + pol = output + stack # poland + + # # print(xpr) + # # print('POLAND:', *pol, sep=' ') + # # print('START CALCULATE *****************') + + output = [] + stack = [] + + for i in pol: + # # print('---------------') + # # print('i in pol = ', i) + if i in oper+['pow', 'log'] and i != ',': + # # print(stack, '+++++++++ to pow or log') + tmp = operate(i, *stack) + # # print(i, '=', tmp) + if ',' in stack and i in ['pow', 'log']: + if stack[-2] == ',': + stack.pop() + stack.pop() + stack.pop() + stack.append(tmp) + elif i in oper: + stack.pop() + stack.pop() + stack.append(tmp) + else: + stack.pop() + stack.append(tmp) + # # print('stack=', stack) + elif i in funclist and i not in ['pow', 'log']: + tmp = operate(i, *stack) + stack[-1] = tmp + # # print('stack=', stack) + # elif i in ['pow', 'log']: + # # # print('DOBL') + # tmp = operate(i, *stack) + # stack.pop() + # stack.pop() + # stack[-1] = tmp + # # # print('stack=', stack) + else: + stack.append(i) + # # print('stack=', stack) + + return stack[0] + + +# EVAL TEST +test = xpr +test = test.replace('^', '**') +test = test.replace(' ', '') +test = test.replace(', ', '.') + +print(main(xpr)) From 766807a0b4f8d8872beca30acb38492af125be6c Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 17:29:42 -0400 Subject: [PATCH 078/159] test --- final_task/{pycalc final.py => pycalc.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename final_task/{pycalc final.py => pycalc.py} (100%) diff --git a/final_task/pycalc final.py b/final_task/pycalc.py similarity index 100% rename from final_task/pycalc final.py rename to final_task/pycalc.py From aa94d6abbd27fc47ed6e17a5bed9a1e78d3fced0 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 17:40:55 -0400 Subject: [PATCH 079/159] test --- final_task/pycalc pol stable v1.py | 415 ----------------------------- final_task/pycalc.py | 9 +- 2 files changed, 8 insertions(+), 416 deletions(-) delete mode 100644 final_task/pycalc pol stable v1.py diff --git a/final_task/pycalc pol stable v1.py b/final_task/pycalc pol stable v1.py deleted file mode 100644 index 82e93c22..00000000 --- a/final_task/pycalc pol stable v1.py +++ /dev/null @@ -1,415 +0,0 @@ -import argparse -import math -import string -from math import * - -ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') -ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') -ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') -args = ap.parse_args() -xpr = args.EXPRESSION - -funcset = {} -operset = {} -splitset = {} - -split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') -splitset = set(split) - -funclist = dir(math)+['abs', 'round'] # list of math functions names -funcdict = math.__dict__ # dict of math functions -funcdict['abs'] = abs -funcdict['round'] = round -xprstr = '' -operator = '' -xprlst = [] -a = 0. -b = 0. -result = 0. -funcset = set(funclist) - -oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', ','] -operset = set(oper) -operhi = ['^'] + funclist # 3 -opermid = ['*', '/', '%'] # 2 -operlow = ['+', '-'] # 1 -operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 - - -# разбор строки на элементы списка -def parse(xprstr): - word = '' - - # проверка недопустимых символов - exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} - xprset = set(xprstr) - if not exset.isdisjoint(xprset): - print('ERROR: unknown symbol') - exit(0) - # проверка скобок в строке - if xpr.count('(') != xpr.count(')'): - print('ERROR: brackets are not balanced') - exit(0) - - # проверка если состоит только из знаков пунктуации - punctset = set(string.punctuation) - xprset = set(xprstr) - if xprset.issubset(punctset) or xprset.issubset(funcset): - print('ERROR: no digits or functions') - exit(0) - - xprstr = xprstr.replace(' ', ' ') - xprstr = xprstr.replace(', ', ',') - xprstr = xprstr.replace(' *', '*') - xprstr = xprstr.replace('* ', '*') - xprstr = xprstr.replace(' +', '+') - xprstr = xprstr.replace('+ ', '+') - xprstr = xprstr.replace(' -', '-') - xprstr = xprstr.replace('- ', '-') - xprstr = xprstr.replace('--', '+') - xprstr = xprstr.replace('++', '+') - xprstr = xprstr.replace('+-', '-') - xprstr = xprstr.replace('-+', '-') - - # # print(xprstr) - - if xprstr[0] == '+': - xprstr = xprstr[1:] - - # проверка пробелов - if xprstr.count(' ') > 0: - print('ERROR: useles spaces') - exit(0) - - # добавление скобок для возведения в степень 2^3^4 - left = 0 - r = len(xprstr) - for x in range(xprstr.count('^')): - r = xprstr.rindex('^', 0, r) - # print('r=', r, ' ', xprstr[:r]) - if xprstr[:r].count('^') == 0: - break - left = xprstr.rindex('^', 0, r)+1 - # # print('left=', left, 'r=', r, ' ', xprstr[left:r]) - tmp = xprstr[left:r] - # # print('tmp=', tmp) - tmpset = set(tmp) - # # print('tmpset', tmpset) - # # print('operset', operset) - if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): - # # print('нада скобки для степени') - xprstr = xprstr[:left]+'('+xprstr[left:] - # # print(xprstr) - - left = r+2 - # # print(xprstr[l:]) - - r = len(xprstr) - for i, data in enumerate(xprstr[left:]): - if data in split and data != '(': - r = left+i - break - # # print('left=', left, 'r=', r, ' ', xprstr[left:r]) - tmp = xprstr[left:r] - # # print(tmp) - xprstr = xprstr[:r]+')'+xprstr[r:] - # # print(xprstr) - else: - # # print('НЕ надо скобки', left, r) - r = left - - # разбор строки - for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел - if sym in split or i == len(xprstr): - # # # print(word) - if word == 'pi': - xprlst.append(pi) - elif word == 'e': - xprlst.append(e) - elif word in funclist: - # # # print(word, ' in math') - xprlst.append(word) - elif word.replace('.', '').isdigit() and word.count('.') < 2: - xprlst.append(float(word)) - # elif word != '': - elif word in split or word == '': - pass - # # # print('ok', word) - else: - print('ERROR: wrong symbol "', word, '"') - exit(0) - xprlst.append(sym) - # # # print(xprlst) - word = '' - else: - word = word + sym - # # # print(word) - xprlst.pop() # удаляется добавленный пробел - - for i, data in enumerate(xprlst): - if xprlst[i] == '/' and xprlst[i + 1] == '/': - xprlst[i] = '//' - xprlst.pop(i + 1) - elif xprlst[i] == '>' and xprlst[i + 1] == '=': - xprlst[i] = '>=' - xprlst.pop(i + 1) - elif xprlst[i] == '<' and xprlst[i + 1] == '=': - xprlst[i] = '<=' - xprlst.pop(i + 1) - elif xprlst[i] == '=' and xprlst[i + 1] == '=' or xprlst[i] == '=': - xprlst[i] = '==' - xprlst.pop(i + 1) - elif xprlst[i] == '!' and xprlst[i + 1] == '=': - xprlst[i] = '!=' - xprlst.pop(i + 1) - elif xprlst[i] == '-' and xprlst[i - 1] in \ - ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '=')\ - and type(xprlst[i + 1]) == float: - xprlst[i + 1] = xprlst[i + 1] * - 1 - xprlst.pop(i) - elif (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] - in('*', '^', '+', '-', '(', '<', '>', '=')): - xprlst[i] = -1 - xprlst.insert(i + 1, '*') - elif xprlst[i] == '-' and xprlst[i - 1] == '/': - xprlst[i - 1] = '*' - xprlst[i] = -1 - xprlst.insert(i + 1, '/') - elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: - pass - - # # # print('ok', i) - else: - print('ERROR: unknown', xprlst[i], i) - xprset = set(xprlst) - if xprset.issubset(funcset) or xprset.issubset(operset): - print('ERROR: только функция') - exit(0) - return xprlst - - -def logargs(*args): - # # print('START logoargs', args) - if ',' in args: - res = log(args[-3], args[-1]) - else: - res = log(args[-1]) - # # print('RETURN logoargs', res) - return res - - -def operate(operator, *args): - - for i in args: - if not (type(i) == float or type(i) == int or i == ','): - print('ERROR: operate non digits') - exit(0) - - if operator in dir(math) and operator not in ['pow', 'log']: - result = funcdict[operator](args[-1]) - elif operator == "pow": - if len(args) == 3: - result = pow(args[-3], args[-1]) - else: - print('ERROR: wrong arguments') - exit(0) - elif operator == "log": - result = logargs(*args) - elif len(args) < 2: - print('ERROR: no arguments') - exit(0) - elif operator == "+": - result = args[-2] + args[-1] - elif operator == "-": - result = args[-2] - args[-1] - elif operator == "*": - result = args[-2] * args[-1] - elif operator == "//": - if args[-1] != 0: - result = args[-2] // args[-1] - else: - print('ERROR: division by zero') - exit(0) - elif operator == "/": - if args[-1] != 0: - result = args[-2] / args[-1] - else: - print('ERROR: division by zero') - exit(0) - elif operator == "%": - result = args[-2] % args[-1] - elif operator == "^": - result = args[-2] ** args[-1] - elif operator == "<=": - result = args[-2] <= args[-1] - elif operator == ">=": - result = args[-2] >= args[-1] - elif operator == "<": - result = args[-2] < args[-1] - elif operator == ">": - result = args[-2] > args[-1] - elif operator == "==": - result = args[-2] == args[-1] - elif operator == "!=": - result = args[-2] != args[-1] - else: - print('ERROR: unknown math operator', operator) - result = 0 - return result - - -def prior(op1, op2): - priorset = [operlowest, operlow, opermid, operhi] - for i, data in enumerate(priorset): - # # # print(op1, i, data, ) - if op1 in data: - prior1 = i - if op2 in data: - prior2 = i - # # # print(prior1 <= prior2) - return prior1 <= prior2 - - -# основная функция -def main(xpr): - # разбор строики в список - xprlst = parse(xpr) - # # print(*xprlst, sep=' ') - - output = [] - stack = [] - for i in xprlst: - # # print('-----------------------------------') - # # print('i=', i) - if type(i) == float or type(i) == int: - output.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - if i == ',': - if stack != []: - while stack[-1] in oper+funclist and prior(i, stack[-1]): - # пока наверху стека оператор с большим или равным приоритетом - # # print('пока на верху стэка оператор') - # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) - output.append(stack.pop()) # переложить оператор из стека на выход - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - if stack == []: - break - output.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - - elif i in oper and i != ',': # '^', '*', '/', '+', '-' - - # # print('in oper', i) - # # print(oper) - if stack == []: # если стек пуст - # # print('стек пуст. добваить оператор в стек') - stack.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - elif stack[-1] == '(': # если стек содержит ( - # # print('( положить в стек') - stack.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - else: - # # print('оператор:', i, '<=stack', stack[-1], prior(i, stack[-1])) - while stack[-1] in oper+funclist and prior(i, stack[-1]): - # пока наверху стека оператор с большим или равным приоритетом - # # print('пока на верху стэка оператор') - # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) - output.append(stack.pop()) # переложить оператор из стека на выход - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - if stack == []: - break - stack.append(i) # иначе положить оператор в стек - - # if i ==', ': - # output.append(i) # если это , то на выход - # else: - # stack.append(i) # иначе положить оператор в стек - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - - elif i == '(': - stack.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - - elif i == ')': - # # print(i) - while stack[-1] != '(': # пока верх стека не равен ( - # # print ('push stack', stack[-1]) - output.append(stack.pop()) - # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке - stack.pop() # удаление из стека ( - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - elif i in funclist: - # # print(i, 'IN FUNCLIST помещаем в стек') - stack.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - # # print('*******') - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - - stack.reverse() - pol = output + stack # poland - - # # print(xpr) - # # print('POLAND:', *pol, sep=' ') - # # print('START CALCULATE *****************') - - output = [] - stack = [] - - for i in pol: - # # print('---------------') - # # print('i in pol = ', i) - if i in oper+['pow', 'log'] and i != ',': - # # print(stack, '+++++++++ to pow or log') - tmp = operate(i, *stack) - # # print(i, '=', tmp) - if ',' in stack and i in ['pow', 'log']: - if stack[-2] == ',': - stack.pop() - stack.pop() - stack.pop() - stack.append(tmp) - elif i in oper: - stack.pop() - stack.pop() - stack.append(tmp) - else: - stack.pop() - stack.append(tmp) - # # print('stack=', stack) - elif i in funclist and i not in ['pow', 'log']: - tmp = operate(i, *stack) - stack[-1] = tmp - # # print('stack=', stack) - # elif i in ['pow', 'log']: - # # # print('DOBL') - # tmp = operate(i, *stack) - # stack.pop() - # stack.pop() - # stack[-1] = tmp - # # # print('stack=', stack) - else: - stack.append(i) - # # print('stack=', stack) - - return stack[0] - - -# EVAL TEST -test = xpr -test = test.replace('^', '**') -test = test.replace(' ', '') -test = test.replace(', ', '.') - -print(main(xpr)) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index fada93fe..aa8f9790 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -244,7 +244,10 @@ def operate(operator, args): if type(args) == float or type(args) == int or type(args) == bool: try: result = funcdic[operator](args) - except ImportError: + except ArithmeticError: + print('ERROR: invalid argument for ', operator) + exit(0) + except TypeError: print('ERROR: invalid argument for ', operator) exit(0) except ValueError: @@ -256,6 +259,9 @@ def operate(operator, args): except ArithmeticError: print('ERROR: invalid argument for ', operator) exit(0) + except TypeError: + print('ERROR: invalid argument for ', operator) + exit(0) except ValueError: print('ERROR: invalid argument for ', operator) exit(0) @@ -413,6 +419,7 @@ def evalpostfix(xprpstfx): # test = test.replace(' ', '') # test = test.replace(', ', '.') + def main(xpr): # попытка добавления внешней функции если указана -m module addfunc(module) From f541300e413a2bae86e917a0b950c3c4e6fdd201 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sun, 28 Apr 2019 17:53:42 -0400 Subject: [PATCH 080/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B0=20=D0=BF=D0=BE=D0=B4=D0=B4=D0=B5=D1=80?= =?UTF-8?q?=D0=B6=D0=BA=D0=B0=20=D1=81=D0=BF=D0=B8=D1=81=D0=BA=D0=B0=20?= =?UTF-8?q?=D0=B4=D0=BB=D1=8F=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D0=B9?= =?UTF-8?q?=20sum,=20fsum.=20=D0=B4=D0=BB=D1=8F=20=D0=BC=D0=B0=D1=82=D0=B5?= =?UTF-8?q?=D0=BC=D0=B0=D1=82=D0=B8=D1=87=D0=B5=D1=81=D0=BA=D0=B8=D1=85=20?= =?UTF-8?q?=D0=BE=D0=BF=D0=B5=D1=80=D0=B0=D1=86=D0=B8=D0=B9=20=D0=BF=D1=80?= =?UTF-8?q?=D0=B8=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=20=D0=BC=D0=BE=D0=B4=D1=83?= =?UTF-8?q?=D0=BB=D1=8C=20operator?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 401 ++++++++++++++++++++----------------------- 1 file changed, 185 insertions(+), 216 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 3cb18389..aa8f9790 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,6 +1,11 @@ +# test 26 apr import argparse import math +import operator +from operator import * import string +import importlib +import importlib.util from math import * ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') @@ -8,41 +13,72 @@ ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') args = ap.parse_args() xpr = args.EXPRESSION +module = args.MODULE -funcset = {} -operset = {} -splitset = {} - -split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') -splitset = set(split) - -funclist = dir(math)+['abs', 'round'] # list of math functions names -funcdict = math.__dict__ # dict of math functions -funcdict['abs'] = abs -funcdict['round'] = round xprstr = '' -operator = '' + xprlst = [] a = 0. b = 0. result = 0. +funcset = {} +operset = {} +splitset = {} +split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') +splitset = set(split) +funclist = dir(math)+['abs', 'round', 'sum'] # list of math functions names +funcdic = math.__dict__ # dict of math functions funcset = set(funclist) - +opdic = { + '+': add, + '-': sub, + '*': mul, + '/': truediv, + '//': floordiv, + '%': mod, + '^': pow, + '==': eq, + '<=': le, + '>=': ge, + '<': lt, + '>': gt, + '!=': ne, + 'abs': abs, + 'round': round, + 'sum': sum + } +funcdic.update(opdic) oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', ','] operset = set(oper) -operhi = ['^'] + funclist # 3 -opermid = ['*', '/', '%'] # 2 -operlow = ['+', '-'] # 1 -operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 -# разбор строки на элементы списка +def addfunc(module): + """ добавляет новую функцию из модуля """ + if module is not None: # если введено имя модуля + try: + spec = importlib.util.find_spec(module) + except ImportError: + print('ERROR: module ', module, 'not found, or unknown symbol') + exit(0) + if spec is None: # проверка возможности импорта модуля + print('ERROR: module {} not found'.format(module)) + exit(0) + else: + newfunc = importlib.import_module(module) # импортирование нового модуля + # # print(dir(newfunc)) + funcdic[module] = newfunc.main + funclist.append(module) + funcset.add(module) + return + + def parse(xprstr): + """ парсинг строки математического выражения. + на выходе список в инфиксной нотации""" word = '' - - # проверка недопустимых символов exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} xprset = set(xprstr) + # проверка если строка выражения содержит недопустимые символы if not exset.isdisjoint(xprset): print('ERROR: unknown symbol') exit(0) @@ -50,11 +86,8 @@ def parse(xprstr): if xpr.count('(') != xpr.count(')'): print('ERROR: brackets are not balanced') exit(0) - - # проверка если состоит только из знаков пунктуации - punctset = set(string.punctuation) - xprset = set(xprstr) - if xprset.issubset(punctset) or xprset.issubset(funcset): + # проверка если выражение состоит только из знаков пунктуации + if xprset.issubset(string.punctuation) or xprset.issubset(funcset): print('ERROR: no digits or functions') exit(0) @@ -71,79 +104,77 @@ def parse(xprstr): xprstr = xprstr.replace('+-', '-') xprstr = xprstr.replace('-+', '-') - # # print(xprstr) - if xprstr[0] == '+': xprstr = xprstr[1:] - # проверка пробелов + # проверка лишних пробелов if xprstr.count(' ') > 0: print('ERROR: useles spaces') exit(0) # добавление скобок для возведения в степень 2^3^4 - left = 0 - r = len(xprstr) + lt = 0 + rt = len(xprstr) for x in range(xprstr.count('^')): - r = xprstr.rindex('^', 0, r) - # print('r=', r, ' ', xprstr[:r]) - if xprstr[:r].count('^') == 0: + rt = xprstr.rindex('^', 0, rt) + # # print('rt=', rt, ' ', xprstr[:rt]) + if xprstr[:rt].count('^') == 0: break - left = xprstr.rindex('^', 0, r)+1 - # # print('left=', left, 'r=', r, ' ', xprstr[left:r]) - tmp = xprstr[left:r] - # # print('tmp=', tmp) + lt = xprstr.rindex('^', 0, rt)+1 + # # # print('lt=', lt, 'rt=', rt, ' ', xprstr[lt:rt]) + tmp = xprstr[lt:rt] + # # # print('tmp=', tmp) tmpset = set(tmp) - # # print('tmpset', tmpset) - # # print('operset', operset) + # # # print('tmpset', tmpset) + # # # print('operset', operset) if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): - # # print('нада скобки для степени') - xprstr = xprstr[:left]+'('+xprstr[left:] - # # print(xprstr) - - left = r+2 - # # print(xprstr[l:]) - - r = len(xprstr) - for i, data in enumerate(xprstr[left:]): + # # # print('нада скобки для степени') + xprstr = xprstr[:lt]+'('+xprstr[lt:] + # # # print(xprstr) + lt = rt+2 + # # # print(xprstr[l:]) + rt = len(xprstr) + for i, data in enumerate(xprstr[lt:]): if data in split and data != '(': - r = left+i + rt = lt+i break - # # print('left=', left, 'r=', r, ' ', xprstr[left:r]) - tmp = xprstr[left:r] - # # print(tmp) - xprstr = xprstr[:r]+')'+xprstr[r:] - # # print(xprstr) + # # # print('lt=', lt, 'rt=', rt, ' ', xprstr[lt:rt]) + tmp = xprstr[lt:rt] + # # # print(tmp) + xprstr = xprstr[:rt]+')'+xprstr[rt:] + # # # print(xprstr) else: - # # print('НЕ надо скобки', left, r) - r = left + # # # print('НЕ надо скобки', lt, rt) + rt = lt # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): - # # # print(word) + # # # # print(word) if word == 'pi': xprlst.append(pi) elif word == 'e': xprlst.append(e) elif word in funclist: - # # # print(word, ' in math') + # # # # print(word, ' in math') xprlst.append(word) elif word.replace('.', '').isdigit() and word.count('.') < 2: xprlst.append(float(word)) # elif word != '': elif word in split or word == '': pass - # # # print('ok', word) + # # # # print('ok', word) else: - print('ERROR: wrong symbol "', word, '"') - exit(0) + addfunc(word) # импортировать неизвестную функцию + xprlst.append(word) + # print('ERROR: wrong symbol "', word, '"') + # exit(0) xprlst.append(sym) - # # # print(xprlst) + # print(xprlst) word = '' else: word = word + sym - # # # print(word) + # print(word) xprlst.pop() # удаляется добавленный пробел for i, data in enumerate(xprlst): @@ -178,7 +209,7 @@ def parse(xprstr): elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: pass - # # # print('ok', i) + # # # # print('ok', i) else: print('ERROR: unknown', xprlst[i], i) xprset = set(xprlst) @@ -189,74 +220,25 @@ def parse(xprstr): def logargs(*args): - # # print('START logoargs', args) + # # # print('START logoargs', args) if ',' in args: res = log(args[-3], args[-1]) else: res = log(args[-1]) - # # print('RETURN logoargs', res) + # # # print('RETURN logoargs', res) return res -def operate(operator, *args): - - for i in args: - if not (type(i) == float or type(i) == int or i == ','): - print('ERROR: operate non digits') - exit(0) -<<<<<<< HEAD +def operate(operator, args): + # print('OPERATOR=',operator,'ARGS=',args) - if operator in dir(math) and operator not in ['pow', 'log']: - result = funcdict[operator](args[-1]) - elif operator == "pow": - if len(args) == 3: - result = pow(args[-3], args[-1]) - else: - print('ERROR: wrong arguments') - exit(0) - elif operator == "log": - result = logargs(*args) - elif len(args) < 2: - print('ERROR: no arguments') - exit(0) - elif operator == "+": - result = args[-2] + args[-1] - elif operator == "-": - result = args[-2] - args[-1] - elif operator == "*": - result = args[-2] * args[-1] - elif operator == "//": - if args[-1] != 0: - result = args[-2] // args[-1] - else: - print('ERROR: division by zero') - exit(0) - elif operator == "/": - if args[-1] != 0: - result = args[-2] / args[-1] - else: - print('ERROR: division by zero') + if operator in ['sum', 'fsum']: + # print('OPERATOR=',operator,'ARGS=',args) + try: + result = funcdic[operator](args) + except ArithmeticError: + print('ERROR: invalid argument for ', operator) exit(0) - elif operator == "%": - result = args[-2] % args[-1] - elif operator == "^": - result = args[-2] ** args[-1] - elif operator == "<=": - result = args[-2] <= args[-1] - elif operator == ">=": - result = args[-2] >= args[-1] - elif operator == "<": - result = args[-2] < args[-1] - elif operator == ">": - result = args[-2] > args[-1] - elif operator == "==": - result = args[-2] == args[-1] - elif operator == "!=": - result = args[-2] != args[-1] - else: - print('ERROR: unknown math operator', operator) - result = 0 -======= elif operator in dir(math) + dir(operator)+['module'] and operator not in ['sum', 'fsum']: # print('OPERATOR=',operator,'ARGS=',args, '*ARGS=',args) if type(args) == float or type(args) == int or type(args) == bool: @@ -286,75 +268,76 @@ def operate(operator, *args): # else: # уже проверяется в парсинге и попыика импортировать модуль # print('ERROR: unknown math operator', operator) # result = 0 ->>>>>>> test return result def prior(op1, op2): + """ сравнивает приоритеты математических опрераторов и функций op1 <= op2, возвращает bool """ + operhi = ['^'] + funclist # 3 + opermid = ['*', '/', '%'] # 2 + operlow = ['+', '-'] # 1 + operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 priorset = [operlowest, operlow, opermid, operhi] for i, data in enumerate(priorset): - # # # print(op1, i, data, ) if op1 in data: - prior1 = i + pr1 = i if op2 in data: - prior2 = i - # # # print(prior1 <= prior2) - return prior1 <= prior2 + pr2 = i + return pr1 <= pr2 -# основная функция -def main(xpr): - # разбор строики в список - xprlst = parse(xpr) - # # print(*xprlst, sep=' ') - +def postfix(xprlst): + """ + преобразование инфиксной нотации в постфиксную + на входе список элементов выражения инфиксной нотации, на выходе список элементов постфиксной нотации + """ + # print('START CONVERT TO POSTFIX *********************') output = [] stack = [] for i in xprlst: - # # print('-----------------------------------') - # # print('i=', i) + # # # print('-----------------------------------') + # # # print('i=', i) if type(i) == float or type(i) == int: output.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') if i == ',': if stack != []: while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом - # # print('пока на верху стэка оператор') - # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) + # # # print('пока на верху стэка оператор') + # # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) output.append(stack.pop()) # переложить оператор из стека на выход - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') if stack == []: break output.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') elif i in oper and i != ',': # '^', '*', '/', '+', '-' - - # # print('in oper', i) - # # print(oper) + # # # print('in oper', i) + # # # print(oper) if stack == []: # если стек пуст - # # print('стек пуст. добваить оператор в стек') + # # # print('стек пуст. добваить оператор в стек') stack.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') elif stack[-1] == '(': # если стек содержит ( - # # print('( положить в стек') + # # # print('( положить в стек') stack.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') else: - # # print('оператор:', i, '<=stack', stack[-1], prior(i, stack[-1])) + # # # print('оператор:', i, '<=stack', stack[-1], prior(i, stack[-1])) while stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом - # # print('пока на верху стэка оператор') - # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) + # # # print('пока на верху стэка оператор') + # # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) output.append(stack.pop()) # переложить оператор из стека на выход - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') if stack == []: break stack.append(i) # иначе положить оператор в стек @@ -363,87 +346,74 @@ def main(xpr): # output.append(i) # если это , то на выход # else: # stack.append(i) # иначе положить оператор в стек - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') elif i == '(': stack.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') elif i == ')': - # # print(i) + # # # print(i) while stack[-1] != '(': # пока верх стека не равен ( - # # print ('push stack', stack[-1]) + # # # print ('push stack', stack[-1]) output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке stack.pop() # удаление из стека ( - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') elif i in funclist: - # # print(i, 'IN FUNCLIST помещаем в стек') + # # # print(i, 'IN FUNCLIST помещаем в стек') stack.append(i) - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') - # # print('*******') - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') + # # # print('*******') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') stack.reverse() - pol = output + stack # poland + return output + stack - # # print(xpr) - # # print('POLAND:', *pol, sep=' ') - # # print('START CALCULATE *****************') - output = [] +def evalpostfix(xprpstfx): + """ + вычисление выражения в постфиксной нотации + на входе список элементов выражения + """ + # print('START EVALUATE POSTFIX ********************') stack = [] - - for i in pol: - # # print('---------------') - # # print('i in pol = ', i) - if i in oper+['pow', 'log'] and i != ',': - # # print(stack, '+++++++++ to pow or log') - tmp = operate(i, *stack) - # # print(i, '=', tmp) - if ',' in stack and i in ['pow', 'log']: - if stack[-2] == ',': - stack.pop() + args = [] + for i in xprpstfx: + # # # print('---------------') + # # print('EVAL i = ', i, 'STACK=',stack) + if i in funclist and i != ',': + if len(stack) < 2: + stack[0] = operate(i, stack[0]) + else: + j = len(stack)-2 + args.append(stack[-1]) + while stack[j] == ',': + args.append(stack[j-1]) stack.pop() stack.pop() - stack.append(tmp) - elif i in oper: - stack.pop() + j = j - 2 stack.pop() + args.reverse() + tmp = operate(i, args) + # print('TMP=',tmp) + args = [] stack.append(tmp) - else: - stack.pop() - stack.append(tmp) - # # print('stack=', stack) - elif i in funclist and i not in ['pow', 'log']: - tmp = operate(i, *stack) - stack[-1] = tmp - # # print('stack=', stack) - # elif i in ['pow', 'log']: - # # # print('DOBL') - # tmp = operate(i, *stack) - # stack.pop() - # stack.pop() - # stack[-1] = tmp - # # # print('stack=', stack) + elif i in oper and i != ',': + tmp = operate(i, stack[-2:]) + stack.pop() + stack.pop() + stack.append(tmp) else: stack.append(i) - # # print('stack=', stack) - return stack[0] # EVAL TEST -<<<<<<< HEAD -test = xpr -test = test.replace('^', '**') -test = test.replace(' ', '') -test = test.replace(', ', '.') -======= # test = xpr # test = test.replace('^', '**') # test = test.replace(' ', '') @@ -467,6 +437,5 @@ def main(xpr): # print(res) return res ->>>>>>> test print(main(xpr)) From 38e7837051f4367b1817140e572b0ce527d46fab Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 3 May 2019 13:35:07 -0400 Subject: [PATCH 081/159] =?UTF-8?q?=D1=83=D0=BF=D1=80=D0=BE=D1=89=D0=B5?= =?UTF-8?q?=D0=BD=20=D0=BF=D0=BE=D0=B8=D1=81=D0=BA=20=D1=81=D0=BE=D1=81?= =?UTF-8?q?=D1=82=D0=B0=D0=B2=D0=BD=D1=8B=D1=85=20=D0=BE=D0=BF=D0=B5=D1=80?= =?UTF-8?q?=D0=B0=D1=82=D0=BE=D1=80=D0=BE=D0=B2=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=20>=3D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/func1.py | 5 ++ final_task/func2.py | 5 ++ final_task/pycalc.py | 114 +++++++++++++++++++++++-------------------- 3 files changed, 70 insertions(+), 54 deletions(-) create mode 100644 final_task/func1.py create mode 100644 final_task/func2.py diff --git a/final_task/func1.py b/final_task/func1.py new file mode 100644 index 00000000..3e2f3065 --- /dev/null +++ b/final_task/func1.py @@ -0,0 +1,5 @@ +def main(x): + x = (x + x) * x + return x + + diff --git a/final_task/func2.py b/final_task/func2.py new file mode 100644 index 00000000..558633fc --- /dev/null +++ b/final_task/func2.py @@ -0,0 +1,5 @@ +def main(x, y): + x = (x + y) * 2 + return x + + diff --git a/final_task/pycalc.py b/final_task/pycalc.py index aa8f9790..123b1020 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,4 +1,4 @@ -# test 26 apr +# test 29 apr import argparse import math import operator @@ -15,15 +15,9 @@ xpr = args.EXPRESSION module = args.MODULE -xprstr = '' +#xprstr = '' xprlst = [] -a = 0. -b = 0. -result = 0. -funcset = {} -operset = {} -splitset = {} split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') splitset = set(split) funclist = dir(math)+['abs', 'round', 'sum'] # list of math functions names @@ -52,6 +46,14 @@ operset = set(oper) + + + + + + + + def addfunc(module): """ добавляет новую функцию из модуля """ if module is not None: # если введено имя модуля @@ -65,7 +67,6 @@ def addfunc(module): exit(0) else: newfunc = importlib.import_module(module) # импортирование нового модуля - # # print(dir(newfunc)) funcdic[module] = newfunc.main funclist.append(module) funcset.add(module) @@ -177,45 +178,56 @@ def parse(xprstr): # print(word) xprlst.pop() # удаляется добавленный пробел + # print('поииск операторов составных') for i, data in enumerate(xprlst): - if xprlst[i] == '/' and xprlst[i + 1] == '/': - xprlst[i] = '//' - xprlst.pop(i + 1) - elif xprlst[i] == '>' and xprlst[i + 1] == '=': - xprlst[i] = '>=' - xprlst.pop(i + 1) - elif xprlst[i] == '<' and xprlst[i + 1] == '=': - xprlst[i] = '<=' - xprlst.pop(i + 1) - elif xprlst[i] == '=' and xprlst[i + 1] == '=' or xprlst[i] == '=': - xprlst[i] = '==' - xprlst.pop(i + 1) - elif xprlst[i] == '!' and xprlst[i + 1] == '=': - xprlst[i] = '!=' - xprlst.pop(i + 1) - elif xprlst[i] == '-' and xprlst[i - 1] in \ - ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '=')\ - and type(xprlst[i + 1]) == float: - xprlst[i + 1] = xprlst[i + 1] * - 1 - xprlst.pop(i) - elif (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] - in('*', '^', '+', '-', '(', '<', '>', '=')): - xprlst[i] = -1 - xprlst.insert(i + 1, '*') - elif xprlst[i] == '-' and xprlst[i - 1] == '/': - xprlst[i - 1] = '*' - xprlst[i] = -1 - xprlst.insert(i + 1, '/') - elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: - pass - - # # # # print('ok', i) - else: - print('ERROR: unknown', xprlst[i], i) - xprset = set(xprlst) - if xprset.issubset(funcset) or xprset.issubset(operset): - print('ERROR: только функция') - exit(0) + if i == len(xprlst) - 1: + break + # print(i, data) + if str(xprlst[i]) + str(xprlst[i+1]) in operset: + # print(xprlst[i], xprlst[i+1]) + xprlst[i] = str(xprlst[i]) + str(xprlst[i+1]) + xprlst.pop(i+1) + + + + # if xprlst[i] == '/' and xprlst[i + 1] == '/': + # xprlst[i] = '//' + # xprlst.pop(i + 1) + # elif xprlst[i] == '>' and xprlst[i + 1] == '=': + # xprlst[i] = '>=' + # xprlst.pop(i + 1) + # elif xprlst[i] == '<' and xprlst[i + 1] == '=': + # xprlst[i] = '<=' + # xprlst.pop(i + 1) + # elif xprlst[i] == '=' and xprlst[i + 1] == '=' or xprlst[i] == '=': + # xprlst[i] = '==' + # xprlst.pop(i + 1) + # elif xprlst[i] == '!' and xprlst[i + 1] == '=': + # xprlst[i] = '!=' + # xprlst.pop(i + 1) + # elif xprlst[i] == '-' and xprlst[i - 1] in \ + # ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '=')\ + # and type(xprlst[i + 1]) == float: + # xprlst[i + 1] = xprlst[i + 1] * - 1 + # xprlst.pop(i) + # elif (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] + # in('*', '^', '+', '-', '(', '<', '>', '=')): + # xprlst[i] = -1 + # xprlst.insert(i + 1, '*') + # elif xprlst[i] == '-' and xprlst[i - 1] == '/': + # xprlst[i - 1] = '*' + # xprlst[i] = -1 + # xprlst.insert(i + 1, '/') + # elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: + # pass + # + # # # # # print('ok', i) + # else: + # print('ERROR: unknown', xprlst[i], i) + # xprset = set(xprlst) + # if xprset.issubset(funcset) or xprset.issubset(operset): + # print('ERROR: только функция') + # exit(0) return xprlst @@ -274,7 +286,7 @@ def operate(operator, args): def prior(op1, op2): """ сравнивает приоритеты математических опрераторов и функций op1 <= op2, возвращает bool """ operhi = ['^'] + funclist # 3 - opermid = ['*', '/', '%'] # 2 + opermid = ['*', '/', '%', '//'] # 2 operlow = ['+', '-'] # 1 operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 priorset = [operlowest, operlow, opermid, operhi] @@ -413,12 +425,6 @@ def evalpostfix(xprpstfx): stack.append(i) return stack[0] -# EVAL TEST -# test = xpr -# test = test.replace('^', '**') -# test = test.replace(' ', '') -# test = test.replace(', ', '.') - def main(xpr): # попытка добавления внешней функции если указана -m module From 121e0e239940c8a90da15afba0255135171533a5 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 3 May 2019 14:22:45 -0400 Subject: [PATCH 082/159] test --- final_task/pycalc.py | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 123b1020..1e492372 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -183,10 +183,22 @@ def parse(xprstr): if i == len(xprlst) - 1: break # print(i, data) - if str(xprlst[i]) + str(xprlst[i+1]) in operset: + if str(xprlst[i]) + str(xprlst[i+1]) in oper: # print(xprlst[i], xprlst[i+1]) - xprlst[i] = str(xprlst[i]) + str(xprlst[i+1]) - xprlst.pop(i+1) + xprlst[i+1] = str(xprlst[i]) + str(xprlst[i+1]) + xprlst.pop(i) + + if xprlst[i] == '-' and xprlst[i-1] in split and type(xprlst[i+1]) == float: + print('минус',xprlst[i-1],xprlst[i],xprlst[i+1]) + xprlst[i+1] = xprlst[i+1] * -1 + xprlst.pop(i) + print(*xprlst, sep='') + + if xprlst[i] == '-' and xprlst[i-1] == '(' and xprlst[i+1] in funclist: + print('минус',xprlst[i+1]) + xprlst[i] = -1 + xprlst.insert(i+1,'*') + print(*xprlst, sep='') @@ -205,13 +217,11 @@ def parse(xprstr): # elif xprlst[i] == '!' and xprlst[i + 1] == '=': # xprlst[i] = '!=' # xprlst.pop(i + 1) - # elif xprlst[i] == '-' and xprlst[i - 1] in \ - # ('^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', '=')\ - # and type(xprlst[i + 1]) == float: + + # if xprlst[i] == '-' and xprlst[i - 1] in oper and type(xprlst[i + 1]) == float: # xprlst[i + 1] = xprlst[i + 1] * - 1 # xprlst.pop(i) - # elif (xprlst[i] == '-' and i == 0) or(xprlst[i] == '-' and xprlst[i - 1] - # in('*', '^', '+', '-', '(', '<', '>', '=')): + # elif (xprlst[i] == '-' and i == 0) or (xprlst[i] == '-' and xprlst[i - 1] in oper): # xprlst[i] = -1 # xprlst.insert(i + 1, '*') # elif xprlst[i] == '-' and xprlst[i - 1] == '/': @@ -228,6 +238,7 @@ def parse(xprstr): # if xprset.issubset(funcset) or xprset.issubset(operset): # print('ERROR: только функция') # exit(0) + print (*xprlst, sep='') return xprlst From 68e6ec43fc9efbd52cad585c4bd23a36f0c7ba01 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 3 May 2019 14:26:25 -0400 Subject: [PATCH 083/159] test --- final_task/pycalc.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 1e492372..8c55b44d 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -189,16 +189,16 @@ def parse(xprstr): xprlst.pop(i) if xprlst[i] == '-' and xprlst[i-1] in split and type(xprlst[i+1]) == float: - print('минус',xprlst[i-1],xprlst[i],xprlst[i+1]) + # print('минус',xprlst[i-1],xprlst[i],xprlst[i+1]) xprlst[i+1] = xprlst[i+1] * -1 xprlst.pop(i) - print(*xprlst, sep='') + # print(*xprlst, sep='') if xprlst[i] == '-' and xprlst[i-1] == '(' and xprlst[i+1] in funclist: - print('минус',xprlst[i+1]) + # print('минус',xprlst[i+1]) xprlst[i] = -1 xprlst.insert(i+1,'*') - print(*xprlst, sep='') + # print(*xprlst, sep='') @@ -238,7 +238,7 @@ def parse(xprstr): # if xprset.issubset(funcset) or xprset.issubset(operset): # print('ERROR: только функция') # exit(0) - print (*xprlst, sep='') + # print (*xprlst, sep='') return xprlst From f0e2992f9a499f477b92aff372d10e0e215245a2 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 3 May 2019 14:34:36 -0400 Subject: [PATCH 084/159] test --- final_task/pycalc.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 8c55b44d..44ef4eb2 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -188,7 +188,7 @@ def parse(xprstr): xprlst[i+1] = str(xprlst[i]) + str(xprlst[i+1]) xprlst.pop(i) - if xprlst[i] == '-' and xprlst[i-1] in split and type(xprlst[i+1]) == float: + if xprlst[i] == '-' and xprlst[i-1] in oper+['('] and type(xprlst[i+1]) == float: # print('минус',xprlst[i-1],xprlst[i],xprlst[i+1]) xprlst[i+1] = xprlst[i+1] * -1 xprlst.pop(i) @@ -238,7 +238,7 @@ def parse(xprstr): # if xprset.issubset(funcset) or xprset.issubset(operset): # print('ERROR: только функция') # exit(0) - # print (*xprlst, sep='') + print (*xprlst, sep='|') return xprlst From 4b305d156e66a3877a39a67c40b35bff42ee34c4 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 3 May 2019 14:38:33 -0400 Subject: [PATCH 085/159] test --- final_task/pycalc.py | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 44ef4eb2..0838af64 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -16,7 +16,7 @@ module = args.MODULE -#xprstr = '' +# xprstr = '' xprlst = [] split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') splitset = set(split) @@ -47,13 +47,6 @@ - - - - - - - def addfunc(module): """ добавляет новую функцию из модуля """ if module is not None: # если введено имя модуля @@ -238,7 +231,7 @@ def parse(xprstr): # if xprset.issubset(funcset) or xprset.issubset(operset): # print('ERROR: только функция') # exit(0) - print (*xprlst, sep='|') + # print (*xprlst, sep='|') return xprlst From 9210d656902a8e8f116fb6547a926b06ccbdf785 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 3 May 2019 15:13:51 -0400 Subject: [PATCH 086/159] test --- final_task/pycalc.py | 58 ++++++++++---------------------------------- 1 file changed, 13 insertions(+), 45 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 0838af64..06c31831 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -81,10 +81,12 @@ def parse(xprstr): print('ERROR: brackets are not balanced') exit(0) # проверка если выражение состоит только из знаков пунктуации - if xprset.issubset(string.punctuation) or xprset.issubset(funcset): + # print('funcset', funcset) + if xprset.issubset(string.punctuation): print('ERROR: no digits or functions') exit(0) + xprstr = xprstr.replace(' ', ' ') xprstr = xprstr.replace(', ', ',') xprstr = xprstr.replace(' *', '*') @@ -171,66 +173,32 @@ def parse(xprstr): # print(word) xprlst.pop() # удаляется добавленный пробел + xprset = set(xprlst) + if xprset.issubset(funcset): + print('ERROR: function has no arguments') + exit(0) + # print('поииск операторов составных') for i, data in enumerate(xprlst): if i == len(xprlst) - 1: break # print(i, data) if str(xprlst[i]) + str(xprlst[i+1]) in oper: - # print(xprlst[i], xprlst[i+1]) xprlst[i+1] = str(xprlst[i]) + str(xprlst[i+1]) xprlst.pop(i) - if xprlst[i] == '-' and xprlst[i-1] in oper+['('] and type(xprlst[i+1]) == float: - # print('минус',xprlst[i-1],xprlst[i],xprlst[i+1]) xprlst[i+1] = xprlst[i+1] * -1 xprlst.pop(i) - # print(*xprlst, sep='') - if xprlst[i] == '-' and xprlst[i-1] == '(' and xprlst[i+1] in funclist: - # print('минус',xprlst[i+1]) xprlst[i] = -1 xprlst.insert(i+1,'*') - # print(*xprlst, sep='') - + if xprlst[0] == '-': + # print('минус',xprlst[i+1]) + xprlst[0] = -1 + xprlst.insert(1,'*') + # print(*xprlst, sep='') - # if xprlst[i] == '/' and xprlst[i + 1] == '/': - # xprlst[i] = '//' - # xprlst.pop(i + 1) - # elif xprlst[i] == '>' and xprlst[i + 1] == '=': - # xprlst[i] = '>=' - # xprlst.pop(i + 1) - # elif xprlst[i] == '<' and xprlst[i + 1] == '=': - # xprlst[i] = '<=' - # xprlst.pop(i + 1) - # elif xprlst[i] == '=' and xprlst[i + 1] == '=' or xprlst[i] == '=': - # xprlst[i] = '==' - # xprlst.pop(i + 1) - # elif xprlst[i] == '!' and xprlst[i + 1] == '=': - # xprlst[i] = '!=' - # xprlst.pop(i + 1) - - # if xprlst[i] == '-' and xprlst[i - 1] in oper and type(xprlst[i + 1]) == float: - # xprlst[i + 1] = xprlst[i + 1] * - 1 - # xprlst.pop(i) - # elif (xprlst[i] == '-' and i == 0) or (xprlst[i] == '-' and xprlst[i - 1] in oper): - # xprlst[i] = -1 - # xprlst.insert(i + 1, '*') - # elif xprlst[i] == '-' and xprlst[i - 1] == '/': - # xprlst[i - 1] = '*' - # xprlst[i] = -1 - # xprlst.insert(i + 1, '/') - # elif type(xprlst[i]) == float or xprlst[i] in funclist or xprlst[i] in oper or xprlst[i] in split: - # pass - # - # # # # # print('ok', i) - # else: - # print('ERROR: unknown', xprlst[i], i) - # xprset = set(xprlst) - # if xprset.issubset(funcset) or xprset.issubset(operset): - # print('ERROR: только функция') - # exit(0) # print (*xprlst, sep='|') return xprlst From 83b61f6d654ba759d7ec37d1b4af14043c3c9467 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 3 May 2019 16:27:14 -0400 Subject: [PATCH 087/159] test --- final_task/pycalc.py | 68 ++++++++++++++++++++++++++------------------ 1 file changed, 40 insertions(+), 28 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 06c31831..e1191361 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -8,15 +8,6 @@ import importlib.util from math import * -ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') -ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') -ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') -args = ap.parse_args() -xpr = args.EXPRESSION -module = args.MODULE - - -# xprstr = '' xprlst = [] split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') splitset = set(split) @@ -46,9 +37,22 @@ operset = set(oper) +def parsecommand(): + """ парсинг командной строки """ + global xpr, module + ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') + ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') + ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') + args = ap.parse_args() + xpr = args.EXPRESSION + module = args.MODULE + # print('def xpr', xpr) + # print('def module', module) + return + def addfunc(module): - """ добавляет новую функцию из модуля """ + """ добавление новой функцию из модуля (module)""" if module is not None: # если введено имя модуля try: spec = importlib.util.find_spec(module) @@ -87,21 +91,23 @@ def parse(xprstr): exit(0) - xprstr = xprstr.replace(' ', ' ') - xprstr = xprstr.replace(', ', ',') - xprstr = xprstr.replace(' *', '*') - xprstr = xprstr.replace('* ', '*') - xprstr = xprstr.replace(' +', '+') - xprstr = xprstr.replace('+ ', '+') - xprstr = xprstr.replace(' -', '-') - xprstr = xprstr.replace('- ', '-') - xprstr = xprstr.replace('--', '+') - xprstr = xprstr.replace('++', '+') - xprstr = xprstr.replace('+-', '-') - xprstr = xprstr.replace('-+', '-') + for i in range(3): + xprstr = xprstr.replace(' ', ' ') + xprstr = xprstr.replace(', ', ',') + xprstr = xprstr.replace(' *', '*') + xprstr = xprstr.replace('* ', '*') + xprstr = xprstr.replace(' +', '+') + xprstr = xprstr.replace('+ ', '+') + xprstr = xprstr.replace(' -', '-') + xprstr = xprstr.replace('- ', '-') + xprstr = xprstr.replace('--', '+') + xprstr = xprstr.replace('++', '+') + xprstr = xprstr.replace('+-', '-') + xprstr = xprstr.replace('-+', '-') + # print(xprstr) if xprstr[0] == '+': - xprstr = xprstr[1:] + xprstr.pop(0) # проверка лишних пробелов if xprstr.count(' ') > 0: @@ -214,6 +220,7 @@ def logargs(*args): def operate(operator, args): + """ выполняет математическое действие или функцию (operator) со списком аргументов (args) """ # print('OPERATOR=',operator,'ARGS=',args) if operator in ['sum', 'fsum']: @@ -249,9 +256,6 @@ def operate(operator, args): except ValueError: print('ERROR: invalid argument for ', operator) exit(0) - # else: # уже проверяется в парсинге и попыика импортировать модуль - # print('ERROR: unknown math operator', operator) - # result = 0 return result @@ -398,10 +402,18 @@ def evalpostfix(xprpstfx): return stack[0] -def main(xpr): +def main(): + # парсинг аргументов командной строки + parsecommand() + # попытка добавления внешней функции если указана -m module addfunc(module) + + # xpr = '-+---+-1' + + + # разбор строики вырыжения в список xprlst = parse(xpr) # print(*xprlst, sep=' ') @@ -416,4 +428,4 @@ def main(xpr): return res -print(main(xpr)) +print(main()) From 7207be188a40ffe3fe17650b115cd13d1fb25456 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 3 May 2019 17:23:30 -0400 Subject: [PATCH 088/159] test --- final_task/pycalc.py | 106 ++++++++++--------------------------------- 1 file changed, 25 insertions(+), 81 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index e1191361..4115d247 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -8,7 +8,6 @@ import importlib.util from math import * -xprlst = [] split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') splitset = set(split) funclist = dir(math)+['abs', 'round', 'sum'] # list of math functions names @@ -74,6 +73,7 @@ def parse(xprstr): """ парсинг строки математического выражения. на выходе список в инфиксной нотации""" word = '' + xprlst=[] exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} xprset = set(xprstr) # проверка если строка выражения содержит недопустимые символы @@ -209,53 +209,25 @@ def parse(xprstr): return xprlst -def logargs(*args): - # # # print('START logoargs', args) - if ',' in args: - res = log(args[-3], args[-1]) - else: - res = log(args[-1]) - # # # print('RETURN logoargs', res) - return res - - def operate(operator, args): """ выполняет математическое действие или функцию (operator) со списком аргументов (args) """ - # print('OPERATOR=',operator,'ARGS=',args) - - if operator in ['sum', 'fsum']: - # print('OPERATOR=',operator,'ARGS=',args) + try: + result = funcdic[operator](*args) + except TypeError: try: result = funcdic[operator](args) - except ArithmeticError: + except TypeError: print('ERROR: invalid argument for ', operator) exit(0) - elif operator in dir(math) + dir(operator)+['module'] and operator not in ['sum', 'fsum']: - # print('OPERATOR=',operator,'ARGS=',args, '*ARGS=',args) - if type(args) == float or type(args) == int or type(args) == bool: - try: - result = funcdic[operator](args) - except ArithmeticError: - print('ERROR: invalid argument for ', operator) - exit(0) - except TypeError: - print('ERROR: invalid argument for ', operator) - exit(0) - except ValueError: - print('ERROR: invalid argument for ', operator) - exit(0) - else: - try: - result = funcdic[operator](*args) - except ArithmeticError: - print('ERROR: invalid argument for ', operator) - exit(0) - except TypeError: - print('ERROR: invalid argument for ', operator) - exit(0) - except ValueError: - print('ERROR: invalid argument for ', operator) - exit(0) + except ValueError: + print('ERROR: invalid argument for ', operator) + exit(0) + except ArithmeticError: + print('ERROR: invalid argument for ', operator) + exit(0) + except ValueError: + print('ERROR: invalid argument for ', operator) + exit(0) return result @@ -275,20 +247,14 @@ def prior(op1, op2): def postfix(xprlst): - """ - преобразование инфиксной нотации в постфиксную - на входе список элементов выражения инфиксной нотации, на выходе список элементов постфиксной нотации - """ - # print('START CONVERT TO POSTFIX *********************') + """ преобразование инфиксной нотации в постфиксную + на входе список элементов выражения инфиксной нотации, на выходе список элементов постфиксной нотации """ output = [] stack = [] for i in xprlst: - # # # print('-----------------------------------') - # # # print('i=', i) - if type(i) == float or type(i) == int: + if type(i) == float or type(i) == int: # если цифра то положить на выход output.append(i) - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') + if i == ',': if stack != []: while stack[-1] in oper+funclist and prior(i, stack[-1]): @@ -312,11 +278,8 @@ def postfix(xprlst): stack.append(i) # # # print('output=', *output, sep=' ') # # # print('stack=', *stack, sep=' ') - elif stack[-1] == '(': # если стек содержит ( - # # # print('( положить в стек') + elif stack[-1] == '(': # если стек содержит ( положить в стек ( stack.append(i) - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') else: # # # print('оператор:', i, '<=stack', stack[-1], prior(i, stack[-1])) while stack[-1] in oper+funclist and prior(i, stack[-1]): @@ -330,18 +293,8 @@ def postfix(xprlst): break stack.append(i) # иначе положить оператор в стек - # if i ==', ': - # output.append(i) # если это , то на выход - # else: - # stack.append(i) # иначе положить оператор в стек - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') - elif i == '(': stack.append(i) - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') - elif i == ')': # # # print(i) while stack[-1] != '(': # пока верх стека не равен ( @@ -349,14 +302,10 @@ def postfix(xprlst): output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке stack.pop() # удаление из стека ( - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') - elif i in funclist: - # # # print(i, 'IN FUNCLIST помещаем в стек') + + elif i in funclist: # если функция то помещаем в стек stack.append(i) - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') - # # # print('*******') + # # # print('output=', *output, sep=' ') # # # print('stack=', *stack, sep=' ') @@ -365,10 +314,8 @@ def postfix(xprlst): def evalpostfix(xprpstfx): - """ - вычисление выражения в постфиксной нотации - на входе список элементов выражения - """ + """ вычисление выражения в постфиксной нотации + на входе список элементов выражения """ # print('START EVALUATE POSTFIX ********************') stack = [] args = [] @@ -403,17 +350,14 @@ def evalpostfix(xprpstfx): def main(): - # парсинг аргументов командной строки + # парсинг аргументов командной строки xpr выражение и module модуль функции parsecommand() # попытка добавления внешней функции если указана -m module addfunc(module) - # xpr = '-+---+-1' - - # разбор строики вырыжения в список xprlst = parse(xpr) # print(*xprlst, sep=' ') From 4c84999e82727e021af4969575a355c94134f780 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 3 May 2019 17:54:01 -0400 Subject: [PATCH 089/159] test --- final_task/pycalc.py | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 4115d247..88594d48 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -73,7 +73,7 @@ def parse(xprstr): """ парсинг строки математического выражения. на выходе список в инфиксной нотации""" word = '' - xprlst=[] + xprlst = [] exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} xprset = set(xprstr) # проверка если строка выражения содержит недопустимые символы @@ -90,7 +90,6 @@ def parse(xprstr): print('ERROR: no digits or functions') exit(0) - for i in range(3): xprstr = xprstr.replace(' ', ' ') xprstr = xprstr.replace(', ', ',') @@ -197,13 +196,12 @@ def parse(xprstr): xprlst.pop(i) if xprlst[i] == '-' and xprlst[i-1] == '(' and xprlst[i+1] in funclist: xprlst[i] = -1 - xprlst.insert(i+1,'*') + xprlst.insert(i+1, '*') if xprlst[0] == '-': - # print('минус',xprlst[i+1]) - xprlst[0] = -1 - xprlst.insert(1,'*') - # print(*xprlst, sep='') + xprlst[0] = -1 + xprlst.insert(1, '*') + # print(*xprlst, sep='') # print (*xprlst, sep='|') return xprlst @@ -283,14 +281,14 @@ def postfix(xprlst): else: # # # print('оператор:', i, '<=stack', stack[-1], prior(i, stack[-1])) while stack[-1] in oper+funclist and prior(i, stack[-1]): - # пока наверху стека оператор с большим или равным приоритетом - # # # print('пока на верху стэка оператор') - # # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) - output.append(stack.pop()) # переложить оператор из стека на выход - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') - if stack == []: - break + # пока наверху стека оператор с большим или равным приоритетом + # # # print('пока на верху стэка оператор') + # # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) + output.append(stack.pop()) # переложить оператор из стека на выход + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') + if stack == []: + break stack.append(i) # иначе положить оператор в стек elif i == '(': From ec3d0361cebd78695ee7e7f91c225770143f0031 Mon Sep 17 00:00:00 2001 From: novash-k Date: Fri, 3 May 2019 18:05:52 -0400 Subject: [PATCH 090/159] test --- final_task/func1.py | 5 ----- final_task/func2.py | 5 ----- 2 files changed, 10 deletions(-) delete mode 100644 final_task/func1.py delete mode 100644 final_task/func2.py diff --git a/final_task/func1.py b/final_task/func1.py deleted file mode 100644 index 3e2f3065..00000000 --- a/final_task/func1.py +++ /dev/null @@ -1,5 +0,0 @@ -def main(x): - x = (x + x) * x - return x - - diff --git a/final_task/func2.py b/final_task/func2.py deleted file mode 100644 index 558633fc..00000000 --- a/final_task/func2.py +++ /dev/null @@ -1,5 +0,0 @@ -def main(x, y): - x = (x + y) * 2 - return x - - From 59798cf8d9faf972711716d79a7ad0b9d5826edb Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 8 May 2019 06:49:13 -0400 Subject: [PATCH 091/159] =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=20=D0=BF=D0=B0=D1=80=D1=81=D0=B8=D0=BD=D0=B3=20=D0=BF?= =?UTF-8?q?=D0=BE=D0=B2=D1=82=D0=BE=D1=80=D1=8F=D1=8E=D1=89=D0=B8=D1=85?= =?UTF-8?q?=D1=81=D1=8F=20=D0=BE=D0=BF=D0=B5=D1=80=D0=B0=D1=82=D0=BE=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=20=D0=B2=20=D1=81=D1=82=D1=80=D0=BE=D0=BA=D0=B5=20?= =?UTF-8?q?=D0=B2=D1=8B=D1=80=D0=B0=D0=B6=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 175 +++++++++++++++---------------------------- 1 file changed, 62 insertions(+), 113 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 88594d48..d6616858 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,4 +1,3 @@ -# test 29 apr import argparse import math import operator @@ -13,7 +12,7 @@ funclist = dir(math)+['abs', 'round', 'sum'] # list of math functions names funcdic = math.__dict__ # dict of math functions funcset = set(funclist) -opdic = { +operdic = { '+': add, '-': sub, '*': mul, @@ -31,12 +30,12 @@ 'round': round, 'sum': sum } -funcdic.update(opdic) -oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!=', ','] +funcdic.update(operdic) +oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!='] operset = set(oper) +xpr = ' ' - -def parsecommand(): +def parsecmd(): """ парсинг командной строки """ global xpr, module ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') @@ -45,8 +44,6 @@ def parsecommand(): args = ap.parse_args() xpr = args.EXPRESSION module = args.MODULE - # print('def xpr', xpr) - # print('def module', module) return @@ -59,7 +56,7 @@ def addfunc(module): print('ERROR: module ', module, 'not found, or unknown symbol') exit(0) if spec is None: # проверка возможности импорта модуля - print('ERROR: module {} not found'.format(module)) + print('ERROR: module ', module, 'not found') exit(0) else: newfunc = importlib.import_module(module) # импортирование нового модуля @@ -70,8 +67,7 @@ def addfunc(module): def parse(xprstr): - """ парсинг строки математического выражения. - на выходе список в инфиксной нотации""" + """ парсинг строки математического выражения. на выходе список в инфиксной нотации""" word = '' xprlst = [] exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} @@ -85,13 +81,16 @@ def parse(xprstr): print('ERROR: brackets are not balanced') exit(0) # проверка если выражение состоит только из знаков пунктуации - # print('funcset', funcset) if xprset.issubset(string.punctuation): print('ERROR: no digits or functions') exit(0) - - for i in range(3): + # устранение пробелов с операторами и повторов операторов + while xprstr.count('++') > 0 or xprstr.count('--') > 0 or xprstr.count(' ') > 0 or xprstr.count('-+') > 0 or xprstr.count('+-') > 0: xprstr = xprstr.replace(' ', ' ') + xprstr = xprstr.replace('--', '+') + xprstr = xprstr.replace('++', '+') + xprstr = xprstr.replace('+-', '-') + xprstr = xprstr.replace('-+', '-') xprstr = xprstr.replace(', ', ',') xprstr = xprstr.replace(' *', '*') xprstr = xprstr.replace('* ', '*') @@ -99,14 +98,8 @@ def parse(xprstr): xprstr = xprstr.replace('+ ', '+') xprstr = xprstr.replace(' -', '-') xprstr = xprstr.replace('- ', '-') - xprstr = xprstr.replace('--', '+') - xprstr = xprstr.replace('++', '+') - xprstr = xprstr.replace('+-', '-') - xprstr = xprstr.replace('-+', '-') - # print(xprstr) - if xprstr[0] == '+': - xprstr.pop(0) + xprstr = xprstr[1:] # проверка лишних пробелов if xprstr.count(' ') > 0: @@ -114,62 +107,46 @@ def parse(xprstr): exit(0) # добавление скобок для возведения в степень 2^3^4 - lt = 0 - rt = len(xprstr) - for x in range(xprstr.count('^')): - rt = xprstr.rindex('^', 0, rt) - # # print('rt=', rt, ' ', xprstr[:rt]) - if xprstr[:rt].count('^') == 0: + left = 0 + right = len(xprstr) + for i in range(xprstr.count('^')): + right = xprstr.rindex('^', 0, right) + if xprstr[:right].count('^') == 0: break - lt = xprstr.rindex('^', 0, rt)+1 - # # # print('lt=', lt, 'rt=', rt, ' ', xprstr[lt:rt]) - tmp = xprstr[lt:rt] - # # # print('tmp=', tmp) + left = xprstr.rindex('^', 0, right)+1 + tmp = xprstr[left:right] tmpset = set(tmp) - # # # print('tmpset', tmpset) - # # # print('operset', operset) if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): - # # # print('нада скобки для степени') - xprstr = xprstr[:lt]+'('+xprstr[lt:] - # # # print(xprstr) - lt = rt+2 - # # # print(xprstr[l:]) - rt = len(xprstr) - for i, data in enumerate(xprstr[lt:]): + # print('надj скобки для степени') + xprstr = xprstr[:left]+'('+xprstr[left:] + left = right+2 + right = len(xprstr) + for i, data in enumerate(xprstr[left:]): if data in split and data != '(': - rt = lt+i + right = left+i break - # # # print('lt=', lt, 'rt=', rt, ' ', xprstr[lt:rt]) - tmp = xprstr[lt:rt] - # # # print(tmp) - xprstr = xprstr[:rt]+')'+xprstr[rt:] - # # # print(xprstr) + tmp = xprstr[left:right] + xprstr = xprstr[:right]+')'+xprstr[right:] else: - # # # print('НЕ надо скобки', lt, rt) - rt = lt + # print('НЕ надо скобки', left, right) + right = left # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): - # # # # print(word) if word == 'pi': xprlst.append(pi) elif word == 'e': xprlst.append(e) - elif word in funclist: - # # # # print(word, ' in math') + elif word in funclist: # если функция xprlst.append(word) - elif word.replace('.', '').isdigit() and word.count('.') < 2: + elif word.replace('.', '').isdigit() and word.count('.') < 2: # если цифра xprlst.append(float(word)) - # elif word != '': - elif word in split or word == '': + elif word in split or word == '': # если оператор или пусто pass - # # # # print('ok', word) - else: - addfunc(word) # импортировать неизвестную функцию + else: # если непонятно что, возможно это внешняя функция + addfunc(word) # попытка импортировать неизвестную функцию xprlst.append(word) - # print('ERROR: wrong symbol "', word, '"') - # exit(0) xprlst.append(sym) # print(xprlst) word = '' @@ -178,6 +155,7 @@ def parse(xprstr): # print(word) xprlst.pop() # удаляется добавленный пробел + # если выражение содержит только функции без аргументов xprset = set(xprlst) if xprset.issubset(funcset): print('ERROR: function has no arguments') @@ -253,77 +231,49 @@ def postfix(xprlst): if type(i) == float or type(i) == int: # если цифра то положить на выход output.append(i) - if i == ',': + elif i == ',': # если , то положить на выход if stack != []: - while stack[-1] in oper+funclist and prior(i, stack[-1]): - # пока наверху стека оператор с большим или равным приоритетом - # # # print('пока на верху стэка оператор') - # # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) + while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): + # пока наверху стека оператор с большим или равным приоритетом output.append(stack.pop()) # переложить оператор из стека на выход - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') - if stack == []: - break output.append(i) - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') - - elif i in oper and i != ',': # '^', '*', '/', '+', '-' - # # # print('in oper', i) - # # # print(oper) - if stack == []: # если стек пуст - # # # print('стек пуст. добваить оператор в стек') + + elif i in oper: # если оператор то положить в стек + if stack == []: # если стек пуст, оператор добавить в стек stack.append(i) - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') elif stack[-1] == '(': # если стек содержит ( положить в стек ( stack.append(i) else: - # # # print('оператор:', i, '<=stack', stack[-1], prior(i, stack[-1])) - while stack[-1] in oper+funclist and prior(i, stack[-1]): - # пока наверху стека оператор с большим или равным приоритетом - # # # print('пока на верху стэка оператор') - # # # print ( 'PRIOR', i, '<=', stack[-1], prior(i, stack[-1])) + while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): + # пока наверху стека оператор с большим или равным приоритетом output.append(stack.pop()) # переложить оператор из стека на выход - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') - if stack == []: - break stack.append(i) # иначе положить оператор в стек - elif i == '(': + elif i in funclist or i == '(': # если функция или ( то помещаем в стек stack.append(i) + elif i == ')': - # # # print(i) while stack[-1] != '(': # пока верх стека не равен ( - # # # print ('push stack', stack[-1]) output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке stack.pop() # удаление из стека ( - - elif i in funclist: # если функция то помещаем в стек - stack.append(i) - - # # # print('output=', *output, sep=' ') - # # # print('stack=', *stack, sep=' ') - + # print('output=', *output, sep=' ') + # print('stack=', *stack, sep=' ') stack.reverse() return output + stack def evalpostfix(xprpstfx): - """ вычисление выражения в постфиксной нотации - на входе список элементов выражения """ - # print('START EVALUATE POSTFIX ********************') + """ вычисление выражения в постфиксной нотации """ stack = [] args = [] + # print(xprpstfx) for i in xprpstfx: - # # # print('---------------') # # print('EVAL i = ', i, 'STACK=',stack) - if i in funclist and i != ',': - if len(stack) < 2: + if i in funclist: + if len(stack) < 2: # для функций типа sin(x) stack[0] = operate(i, stack[0]) - else: + else: # для функций типа sum(a,b,c,d...) формирование списка аргументов функции j = len(stack)-2 args.append(stack[-1]) while stack[j] == ',': @@ -334,28 +284,27 @@ def evalpostfix(xprpstfx): stack.pop() args.reverse() tmp = operate(i, args) - # print('TMP=',tmp) args = [] stack.append(tmp) - elif i in oper and i != ',': + + elif i in oper: # для операторов типа a + b tmp = operate(i, stack[-2:]) + # print(stack[-2:]) stack.pop() stack.pop() stack.append(tmp) else: - stack.append(i) + stack.append(i) # если число то добавить его в стек return stack[0] def main(): # парсинг аргументов командной строки xpr выражение и module модуль функции - parsecommand() + parsecmd() # попытка добавления внешней функции если указана -m module addfunc(module) - # xpr = '-+---+-1' - # разбор строики вырыжения в список xprlst = parse(xpr) # print(*xprlst, sep=' ') @@ -365,9 +314,9 @@ def main(): # print(*xprlst, sep=' ') # вычисление постфиксного списка - res = evalpostfix(xprlst) - # print(res) - return res + result = evalpostfix(xprlst) + + return result print(main()) From 9e220c7852f258088b50a12984e5136181c50b4b Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 8 May 2019 06:57:31 -0400 Subject: [PATCH 092/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D0=BF=D0=B0=D1=80=D1=81=D0=B8=D0=BD=D0=B3?= =?UTF-8?q?=20=D0=BF=D0=BE=D0=B2=D1=82=D0=BE=D1=80=D1=8F=D1=8E=D1=89=D0=B8?= =?UTF-8?q?=D1=85=D1=81=D1=8F=20=D0=BE=D0=BF=D0=B5=D1=80=D0=B0=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=20=D0=B2=20=D1=81=D1=82=D1=80=D0=BE=D0=BA?= =?UTF-8?q?=D0=B5=20=D0=B2=D1=8B=D1=80=D0=B0=D0=B6=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index d6616858..696ca381 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -91,16 +91,19 @@ def parse(xprstr): xprstr = xprstr.replace('++', '+') xprstr = xprstr.replace('+-', '-') xprstr = xprstr.replace('-+', '-') - xprstr = xprstr.replace(', ', ',') - xprstr = xprstr.replace(' *', '*') - xprstr = xprstr.replace('* ', '*') - xprstr = xprstr.replace(' +', '+') - xprstr = xprstr.replace('+ ', '+') - xprstr = xprstr.replace(' -', '-') - xprstr = xprstr.replace('- ', '-') + + xprstr = xprstr.replace(' *', '*') + xprstr = xprstr.replace('* ', '*') + xprstr = xprstr.replace(' +', '+') + xprstr = xprstr.replace('+ ', '+') + xprstr = xprstr.replace(' -', '-') + xprstr = xprstr.replace('- ', '-') + xprstr = xprstr.replace(', ', ',') if xprstr[0] == '+': xprstr = xprstr[1:] + print(xprstr) + # проверка лишних пробелов if xprstr.count(' ') > 0: print('ERROR: useles spaces') From f41473785de328a99fcdd21840dc8364acd741aa Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 8 May 2019 07:15:57 -0400 Subject: [PATCH 093/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D0=BF=D0=B0=D1=80=D1=81=D0=B8=D0=BD=D0=B3?= =?UTF-8?q?=20=D0=BF=D0=BE=D0=B2=D1=82=D0=BE=D1=80=D1=8F=D1=8E=D1=89=D0=B8?= =?UTF-8?q?=D1=85=D1=81=D1=8F=20=D0=BE=D0=BF=D0=B5=D1=80=D0=B0=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=20=D0=B2=20=D1=81=D1=82=D1=80=D0=BE=D0=BA?= =?UTF-8?q?=D0=B5=20=D0=B2=D1=8B=D1=80=D0=B0=D0=B6=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 696ca381..f627a725 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -102,7 +102,7 @@ def parse(xprstr): if xprstr[0] == '+': xprstr = xprstr[1:] - print(xprstr) + # print(xprstr) # проверка лишних пробелов if xprstr.count(' ') > 0: From 52a16756479bc63354c0d37c88de79327f962259 Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 8 May 2019 07:34:39 -0400 Subject: [PATCH 094/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D0=BF=D0=B0=D1=80=D1=81=D0=B8=D0=BD=D0=B3?= =?UTF-8?q?=20=D0=BF=D0=BE=D0=B2=D1=82=D0=BE=D1=80=D1=8F=D1=8E=D1=89=D0=B8?= =?UTF-8?q?=D1=85=D1=81=D1=8F=20=D0=BE=D0=BF=D0=B5=D1=80=D0=B0=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=20=D0=B2=20=D1=81=D1=82=D1=80=D0=BE=D0=BA?= =?UTF-8?q?=D0=B5=20=D0=B2=D1=8B=D1=80=D0=B0=D0=B6=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index f627a725..65d330aa 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -84,21 +84,27 @@ def parse(xprstr): if xprset.issubset(string.punctuation): print('ERROR: no digits or functions') exit(0) + + if xprstr.count('> =') > 0 or xprstr.count('< =') > 0 or xprstr.count('/ /') > 0 or xprstr.count('* *') > 0: + print('ERROR: usles spaces') + # устранение пробелов с операторами и повторов операторов - while xprstr.count('++') > 0 or xprstr.count('--') > 0 or xprstr.count(' ') > 0 or xprstr.count('-+') > 0 or xprstr.count('+-') > 0: - xprstr = xprstr.replace(' ', ' ') + xprstr = xprstr.replace(' ', '') + + # xprstr = xprstr.replace(' *', '*') + # xprstr = xprstr.replace('* ', '*') + # xprstr = xprstr.replace(' +', '+') + # xprstr = xprstr.replace('+ ', '+') + # xprstr = xprstr.replace(' -', '-') + # xprstr = xprstr.replace('- ', '-') + # xprstr = xprstr.replace(', ', ',') + + while xprstr.count('++') > 0 or xprstr.count('--') > 0 or xprstr.count('-+') > 0 or xprstr.count('+-') > 0: xprstr = xprstr.replace('--', '+') xprstr = xprstr.replace('++', '+') xprstr = xprstr.replace('+-', '-') xprstr = xprstr.replace('-+', '-') - - xprstr = xprstr.replace(' *', '*') - xprstr = xprstr.replace('* ', '*') - xprstr = xprstr.replace(' +', '+') - xprstr = xprstr.replace('+ ', '+') - xprstr = xprstr.replace(' -', '-') - xprstr = xprstr.replace('- ', '-') - xprstr = xprstr.replace(', ', ',') + if xprstr[0] == '+': xprstr = xprstr[1:] From e26e0606eb3aadaa0035467e4e9fe0fd0ad90eb0 Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 8 May 2019 08:17:24 -0400 Subject: [PATCH 095/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D0=BF=D0=B0=D1=80=D1=81=D0=B8=D0=BD=D0=B3?= =?UTF-8?q?=20=D0=BF=D0=BE=D0=B2=D1=82=D0=BE=D1=80=D1=8F=D1=8E=D1=89=D0=B8?= =?UTF-8?q?=D1=85=D1=81=D1=8F=20=D0=BE=D0=BF=D0=B5=D1=80=D0=B0=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=20=D0=B2=20=D1=81=D1=82=D1=80=D0=BE=D0=BA?= =?UTF-8?q?=D0=B5=20=D0=B2=D1=8B=D1=80=D0=B0=D0=B6=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 65d330aa..3e614bb8 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -85,30 +85,35 @@ def parse(xprstr): print('ERROR: no digits or functions') exit(0) - if xprstr.count('> =') > 0 or xprstr.count('< =') > 0 or xprstr.count('/ /') > 0 or xprstr.count('* *') > 0: - print('ERROR: usles spaces') - # устранение пробелов с операторами и повторов операторов - xprstr = xprstr.replace(' ', '') - - # xprstr = xprstr.replace(' *', '*') - # xprstr = xprstr.replace('* ', '*') - # xprstr = xprstr.replace(' +', '+') - # xprstr = xprstr.replace('+ ', '+') - # xprstr = xprstr.replace(' -', '-') - # xprstr = xprstr.replace('- ', '-') - # xprstr = xprstr.replace(', ', ',') - - while xprstr.count('++') > 0 or xprstr.count('--') > 0 or xprstr.count('-+') > 0 or xprstr.count('+-') > 0: + while xprstr.count(' ') > 0 or xprstr.count('++') > 0 or \ + xprstr.count('--') > 0 or \ + xprstr.count('-+') > 0 or \ + xprstr.count('+-') > 0 or \ + xprstr.count(' *') > 0 or \ + xprstr.count('* ') > 0 or \ + xprstr.count(' +') > 0 or \ + xprstr.count('+ ') > 0 or \ + xprstr.count(' -') > 0 or \ + xprstr.count('- ') > 0 or \ + xprstr.count(', ') > 0: + xprstr = xprstr.replace(' ', ' ') xprstr = xprstr.replace('--', '+') xprstr = xprstr.replace('++', '+') xprstr = xprstr.replace('+-', '-') xprstr = xprstr.replace('-+', '-') - + xprstr = xprstr.replace(' *', '*') + xprstr = xprstr.replace('* ', '*') + xprstr = xprstr.replace(' +', '+') + xprstr = xprstr.replace('+ ', '+') + xprstr = xprstr.replace(' -', '-') + xprstr = xprstr.replace('- ', '-') + xprstr = xprstr.replace(', ', ',') + if xprstr[0] == '+': xprstr = xprstr[1:] - # print(xprstr) + #print(xprstr) # проверка лишних пробелов if xprstr.count(' ') > 0: From 3dd76bf1e543f05b05381e440dd7dc13819de90f Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 8 May 2019 08:24:52 -0400 Subject: [PATCH 096/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D0=BF=D0=B0=D1=80=D1=81=D0=B8=D0=BD=D0=B3?= =?UTF-8?q?=20=D0=BF=D0=BE=D0=B2=D1=82=D0=BE=D1=80=D1=8F=D1=8E=D1=89=D0=B8?= =?UTF-8?q?=D1=85=D1=81=D1=8F=20=D0=BE=D0=BF=D0=B5=D1=80=D0=B0=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=20=D0=B2=20=D1=81=D1=82=D1=80=D0=BE=D0=BA?= =?UTF-8?q?=D0=B5=20=D0=B2=D1=8B=D1=80=D0=B0=D0=B6=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 3e614bb8..de4378ce 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -35,6 +35,7 @@ operset = set(oper) xpr = ' ' + def parsecmd(): """ парсинг командной строки """ global xpr, module @@ -86,7 +87,7 @@ def parse(xprstr): exit(0) # устранение пробелов с операторами и повторов операторов - while xprstr.count(' ') > 0 or xprstr.count('++') > 0 or \ + while xprstr.count(' ') > 0 or xprstr.count('++') > 0 or \ xprstr.count('--') > 0 or \ xprstr.count('-+') > 0 or \ xprstr.count('+-') > 0 or \ @@ -113,7 +114,7 @@ def parse(xprstr): if xprstr[0] == '+': xprstr = xprstr[1:] - #print(xprstr) + # print(xprstr) # проверка лишних пробелов if xprstr.count(' ') > 0: @@ -248,7 +249,7 @@ def postfix(xprlst): elif i == ',': # если , то положить на выход if stack != []: while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): - # пока наверху стека оператор с большим или равным приоритетом + # пока наверху стека оператор с большим или равным приоритетом output.append(stack.pop()) # переложить оператор из стека на выход output.append(i) @@ -259,7 +260,7 @@ def postfix(xprlst): stack.append(i) else: while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): - # пока наверху стека оператор с большим или равным приоритетом + # пока наверху стека оператор с большим или равным приоритетом output.append(stack.pop()) # переложить оператор из стека на выход stack.append(i) # иначе положить оператор в стек From 609a80c1704a8f464f947a24a5125b66fb245e64 Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 8 May 2019 08:38:54 -0400 Subject: [PATCH 097/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D0=BF=D0=B0=D1=80=D1=81=D0=B8=D0=BD=D0=B3?= =?UTF-8?q?=20=D0=BF=D0=BE=D0=B2=D1=82=D0=BE=D1=80=D1=8F=D1=8E=D1=89=D0=B8?= =?UTF-8?q?=D1=85=D1=81=D1=8F=20=D0=BE=D0=BF=D0=B5=D1=80=D0=B0=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=20=D0=B2=20=D1=81=D1=82=D1=80=D0=BE=D0=BA?= =?UTF-8?q?=D0=B5=20=D0=B2=D1=8B=D1=80=D0=B0=D0=B6=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index de4378ce..37387033 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -301,7 +301,7 @@ def evalpostfix(xprpstfx): tmp = operate(i, args) args = [] stack.append(tmp) - + elif i in oper: # для операторов типа a + b tmp = operate(i, stack[-2:]) # print(stack[-2:]) From fea50f0f3a9388226cce94a12d60df5ff483c8ca Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 8 May 2019 08:40:52 -0400 Subject: [PATCH 098/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D0=BF=D0=B0=D1=80=D1=81=D0=B8=D0=BD=D0=B3?= =?UTF-8?q?=20=D0=BF=D0=BE=D0=B2=D1=82=D0=BE=D1=80=D1=8F=D1=8E=D1=89=D0=B8?= =?UTF-8?q?=D1=85=D1=81=D1=8F=20=D0=BE=D0=BF=D0=B5=D1=80=D0=B0=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=20=D0=B2=20=D1=81=D1=82=D1=80=D0=BE=D0=BA?= =?UTF-8?q?=D0=B5=20=D0=B2=D1=8B=D1=80=D0=B0=D0=B6=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 37387033..4a6baaa3 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -330,7 +330,7 @@ def main(): # вычисление постфиксного списка result = evalpostfix(xprlst) - + return result From fbc661aa59d7e818d410242639c03f4e7a9d9bd2 Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 8 May 2019 11:31:42 -0400 Subject: [PATCH 099/159] test --- final_task/pycalc.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 4a6baaa3..1a9e674c 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -57,7 +57,7 @@ def addfunc(module): print('ERROR: module ', module, 'not found, or unknown symbol') exit(0) if spec is None: # проверка возможности импорта модуля - print('ERROR: module ', module, 'not found') + print('ERROR: unknown function or module ', module, 'not found') exit(0) else: newfunc = importlib.import_module(module) # импортирование нового модуля @@ -67,27 +67,29 @@ def addfunc(module): return + def parse(xprstr): """ парсинг строки математического выражения. на выходе список в инфиксной нотации""" word = '' xprlst = [] - exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} + #exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} xprset = set(xprstr) # проверка если строка выражения содержит недопустимые символы - if not exset.isdisjoint(xprset): - print('ERROR: unknown symbol') - exit(0) + # if not exset.isdisjoint(xprset): + # print('ERROR: unknown symbol') + # exit(0) # проверка скобок в строке if xpr.count('(') != xpr.count(')'): print('ERROR: brackets are not balanced') exit(0) # проверка если выражение состоит только из знаков пунктуации - if xprset.issubset(string.punctuation): - print('ERROR: no digits or functions') - exit(0) + #if xprset.issubset(string.punctuation): + # print('ERROR: no digits or functions') + # exit(0) # устранение пробелов с операторами и повторов операторов - while xprstr.count(' ') > 0 or xprstr.count('++') > 0 or \ + while xprstr.count(' ') > 0 or \ + xprstr.count('++') > 0 or \ xprstr.count('--') > 0 or \ xprstr.count('-+') > 0 or \ xprstr.count('+-') > 0 or \ @@ -282,7 +284,6 @@ def evalpostfix(xprpstfx): """ вычисление выражения в постфиксной нотации """ stack = [] args = [] - # print(xprpstfx) for i in xprpstfx: # # print('EVAL i = ', i, 'STACK=',stack) if i in funclist: @@ -301,7 +302,6 @@ def evalpostfix(xprpstfx): tmp = operate(i, args) args = [] stack.append(tmp) - elif i in oper: # для операторов типа a + b tmp = operate(i, stack[-2:]) # print(stack[-2:]) @@ -320,7 +320,7 @@ def main(): # попытка добавления внешней функции если указана -m module addfunc(module) - # разбор строики вырыжения в список + # разбор строки вырыжения в список xprlst = parse(xpr) # print(*xprlst, sep=' ') From ca1b6ab6dcb0b25e3cdd614a1156c728a67a6b5a Mon Sep 17 00:00:00 2001 From: novash-k Date: Wed, 8 May 2019 11:41:14 -0400 Subject: [PATCH 100/159] test --- final_task/pycalc.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 1a9e674c..7d1adad6 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -79,7 +79,10 @@ def parse(xprstr): # print('ERROR: unknown symbol') # exit(0) # проверка скобок в строке - if xpr.count('(') != xpr.count(')'): + + + + if xpr.count('(') != xpr.count(')') or len(xpr) == 0: print('ERROR: brackets are not balanced') exit(0) # проверка если выражение состоит только из знаков пунктуации From b331a2c1f652379e721889559f01bbce0d25235f Mon Sep 17 00:00:00 2001 From: novash-k Date: Sat, 11 May 2019 08:37:42 -0400 Subject: [PATCH 101/159] test --- final_task/pycalc (another copy).py | 366 ++++++++++++++++++++++++++++ final_task/pycalc (copy).py | 353 +++++++++++++++++++++++++++ final_task/pycalc.py | 154 +++++++----- 3 files changed, 809 insertions(+), 64 deletions(-) create mode 100644 final_task/pycalc (another copy).py create mode 100644 final_task/pycalc (copy).py diff --git a/final_task/pycalc (another copy).py b/final_task/pycalc (another copy).py new file mode 100644 index 00000000..f5f31bc3 --- /dev/null +++ b/final_task/pycalc (another copy).py @@ -0,0 +1,366 @@ +import argparse +import math +import operator +from operator import * +import string +import importlib +import importlib.util +from math import * + +split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') +splitset = set(split) +funclist = dir(math)+['abs', 'round', 'sum'] # list of math functions names +funcdic = math.__dict__ # dict of math functions +funcset = set(funclist) +operdic = { + '+': add, + '-': sub, + '*': mul, + '/': truediv, + '//': floordiv, + '%': mod, + '^': pow, + '==': eq, + '<=': le, + '>=': ge, + '<': lt, + '>': gt, + '!=': ne, + 'abs': abs, + 'round': round, + 'sum': sum + } +funcdic.update(operdic) +oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!='] +operset = set(oper) +xpr = ' ' + + +def parsecmd(): + """ парсинг командной строки """ + global xpr, module + ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') + ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') + ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') + args = ap.parse_args() + xpr = args.EXPRESSION + module = args.MODULE + return + + +def addfunc(module): + """ добавление новой функцию из модуля (module)""" + if module is not None: # если введено имя модуля + try: + spec = importlib.util.find_spec(module) + except ImportError: + print('ERROR: module ', module, 'not found, or unknown symbol') + exit(0) + if spec is None: # проверка возможности импорта модуля + print('ERROR: unknown function or module ', module, 'not found') + exit(0) + else: + newfunc = importlib.import_module(module) # импортирование нового модуля + funcdic[module] = newfunc.main + funclist.append(module) + funcset.add(module) + return + + +def parse(xprstr): + """ парсинг строки математического выражения. на выходе список в инфиксной нотации""" + word = '' + xprlst = [] + # проверка скобок в строке + if xpr.count('(') != xpr.count(')') or len(xpr) == 0: + print('ERROR: brackets are not balanced') + exit(0) + # устранение пробелов с операторами и повторов операторов + while xprstr.count(' ') > 0 or \ + xprstr.count('++') > 0 or \ + xprstr.count('--') > 0 or \ + xprstr.count('-+') > 0 or \ + xprstr.count('+-') > 0 or \ + xprstr.count(' *') > 0 or \ + xprstr.count('* ') > 0 or \ + xprstr.count(' +') > 0 or \ + xprstr.count('+ ') > 0 or \ + xprstr.count(' -') > 0 or \ + xprstr.count('- ') > 0 or \ + xprstr.count(', ') > 0: + xprstr = xprstr.replace(' ', ' ') + xprstr = xprstr.replace('--', '+') + xprstr = xprstr.replace('++', '+') + xprstr = xprstr.replace('+-', '-') + xprstr = xprstr.replace('-+', '-') + xprstr = xprstr.replace(' *', '*') + xprstr = xprstr.replace('* ', '*') + xprstr = xprstr.replace(' +', '+') + xprstr = xprstr.replace('+ ', '+') + xprstr = xprstr.replace(' -', '-') + xprstr = xprstr.replace('- ', '-') + xprstr = xprstr.replace(', ', ',') + if xprstr[0] == '+': + xprstr = xprstr[1:] + + if xprstr.count(' ') > 0: # проверка лишних пробелов + print('ERROR: useles spaces') + exit(0) + + # добавление скобок для возведения в степень 2^3^4 + right = len(xprstr) + for i in range(xprstr.count('^')): + right = xprstr.rindex('^', 0, right) + if xprstr[:right].count('^') == 0: + break + left = xprstr.rindex('^', 0, right)+1 + tmp = xprstr[left:right] + tmpset = set(tmp) + if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): + # print('надо скобки для степени') + xprstr = xprstr[:left]+'('+xprstr[left:] + left = right+2 + right = len(xprstr) + for i, data in enumerate(xprstr[left:]): + if data in split and data != '(': + right = left+i + break + tmp = xprstr[left:right] + xprstr = xprstr[:right]+')'+xprstr[right:] + else: + # print('НЕ надо скобки', left, right) + right = left + + # разбор строки + for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел + if sym in split or i == len(xprstr): + if word == 'pi': + xprlst.append('pi') + elif word == 'e': + xprlst.append(e) + elif word in funclist: # если функция + xprlst.append(word) + elif word.replace('.', '').isdigit() and word.count('.') < 2: # если цифра + xprlst.append(float(word)) + elif word != '': # если не пусто и непонятно что, возможно это внешняя функция + addfunc(word) # попытка импортировать неизвестную функцию + xprlst.append(word) + xprlst.append(sym) + word = '' + else: + word = word + sym + xprlst.pop() # удаляется добавленный пробел + + # если выражение содержит только функции без аргументов + # xprset = set(xprlst) + # if xprset.issubset(funcset): + # print('ERROR: function has no arguments') + # exit(0) + + # print('поииск операторов составных') + for i, data in enumerate(xprlst): + if i == len(xprlst) - 1: + break + # print(i, data) + if str(xprlst[i]) + str(xprlst[i+1]) in oper: + xprlst[i+1] = str(xprlst[i]) + str(xprlst[i+1]) + xprlst.pop(i) + if xprlst[i] == '-' and xprlst[i-1] in oper+['('] and type(xprlst[i+1]) == float: + xprlst[i+1] = xprlst[i+1] * -1 + xprlst.pop(i) + if xprlst[i] == '-' and xprlst[i-1] == '(' and xprlst[i+1] in funclist: + xprlst[i] = -1 + xprlst.insert(i+1, '*') + + if xprlst[0] == '-': + xprlst[0] = -1 + xprlst.insert(1, '*') + # print(*xprlst, sep='') + + print (*xprlst, sep='|') + return xprlst + + + + + +def prior(op1, op2): + """ сравнивает приоритеты математических опрераторов и функций op1 <= op2, возвращает bool """ + operhi = ['^'] + funclist # 3 + opermid = ['*', '/', '%', '//'] # 2 + operlow = ['+', '-'] # 1 + operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 + priorset = [operlowest, operlow, opermid, operhi] + for i, data in enumerate(priorset): + if op1 in data: + pr1 = i + if op2 in data: + pr2 = i + return pr1 <= pr2 + + +def postfix(xprlst): + """ преобразование инфиксной нотации в постфиксную + на входе список элементов выражения инфиксной нотации, на выходе список элементов постфиксной нотации """ + output = [] + stack = [] + for i in xprlst: + if type(i) == float or type(i) == int: # если цифра то положить на выход + output.append(i) + + elif i == ',': # если , то положить на выход + if stack != []: + while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): + # пока наверху стека оператор с большим или равным приоритетом + output.append(stack.pop()) # переложить оператор из стека на выход + output.append(i) + + elif i in oper: # если оператор то положить в стек + if stack == []: # если стек пуст, оператор добавить в стек + stack.append(i) + elif stack[-1] == '(': # если стек содержит ( положить в стек ( + stack.append(i) + else: + while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): + # пока наверху стека оператор с большим или равным приоритетом + output.append(stack.pop()) # переложить оператор из стека на выход + stack.append(i) # иначе положить оператор в стек + + elif i in funclist or i == '(': # если функция или ( то помещаем в стек + stack.append(i) + + elif i == ')': + while stack[-1] != '(': # пока верх стека не равен ( + output.append(stack.pop()) + # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке + stack.pop() # удаление из стека ( + # print('output=', *output, sep=' ') + # print('stack=', *stack, sep=' ') + stack.reverse() + print(output + stack) + + + # xprset = set(output + stack) + # if xprset.issubset(funcset): # проверка если функция без аргументов + # print('ERROR: function has no arguments') + # exit(0) + + + + return output + stack + + +def operate(operator, args): + """ выполняет математическое действие или функцию (operator) со списком аргументов (args) """ + global stack + global flag + + print('OPERATE', operator, 'ARGS', args, 'STACK', stack) + try: + result = funcdic[operator](*args) + stack.pop() + print('FUNC *args') + except TypeError: + try: + result = funcdic[operator](args) + stack.pop() + print('FUNC list args') + except TypeError: + # print('ERROR: invalid argument for ', operator) + # exit(0) + try: + result = funcdic[operator] + flag = 1 + print('FUNC no args') + except TypeError: + print('ERROR: invalid argument for ', operator) + exit(0) + + except ValueError: + print('ERROR: invalid argument for ', operator) + exit(0) + except ArithmeticError: + print('ERROR: invalid argument for ', operator) + exit(0) + except ValueError: + print('ERROR: invalid argument for ', operator) + exit(0) + print('RESULT', result) + return result + + + + +def evalpostfix(xprpstfx): + """ вычисление выражения в постфиксной нотации """ + global stack + global flag + stack = [] + args = [] + flag = 0 + for i in xprpstfx: + print('i = ', i, 'stack', stack) + if i in funclist: + + + if len(stack) == 0: + args = 0 + if len(stack) == 1: + args = stack[0] + if len(stack) > 1: # для функций типа sum(a,b,c,d...) формирование списка аргументов функции + print('stack > 2') + j = len(stack)-2 + args.append(stack[-1]) + while stack[j] == ',': + args.append(stack[j-1]) + stack.pop() + stack.pop() + j = j - 2 + #stack.pop() + args.reverse() + print('STACK', stack) + + tmp = operate(i, args) + args = [] + + stack.append(tmp) + + + + + elif i in oper: # для операторов типа a + b + print('OPERATE', i,*stack[-2:]) + tmp = funcdic[i](*stack[-2:]) + #tmp = operate(i, stack[-2:]) + # print(stack[-2:]) + stack.pop() + stack.pop() + stack.append(tmp) + else: + stack.append(i) # если число то добавить его в стек + print('STACK',stack) + return stack[0] + + +def main(): + # парсинг аргументов командной строки xpr выражение и module модуль функции + parsecmd() + + # попытка добавления внешней функции если указана -m module + addfunc(module) + + # разбор строки вырыжения в список + xprlst = parse(xpr) + print('PARSE ', *xprlst, sep=' ') + + # преобразование инфиксного списка в постфиксных список + xprlst = postfix(xprlst) + print('POSTFIX ', *xprlst, sep=' ') + + # вычисление постфиксного списка + result = evalpostfix(xprlst) + + return result + + +print(main()) diff --git a/final_task/pycalc (copy).py b/final_task/pycalc (copy).py new file mode 100644 index 00000000..a06d13a8 --- /dev/null +++ b/final_task/pycalc (copy).py @@ -0,0 +1,353 @@ +import argparse +import math +import operator +from operator import * +import string +import importlib +import importlib.util +from math import * + +split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') +splitset = set(split) +funclist = dir(math)+['abs', 'round', 'sum'] # list of math functions names +funcdic = math.__dict__ # dict of math functions +funcset = set(funclist) +operdic = { + '+': add, + '-': sub, + '*': mul, + '/': truediv, + '//': floordiv, + '%': mod, + '^': pow, + '==': eq, + '<=': le, + '>=': ge, + '<': lt, + '>': gt, + '!=': ne, + 'abs': abs, + 'round': round, + 'sum': sum + } +funcdic.update(operdic) +oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!='] +operset = set(oper) +xpr = ' ' + + +def parsecmd(): + """ парсинг командной строки """ + global xpr, module + ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') + ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') + ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') + args = ap.parse_args() + xpr = args.EXPRESSION + module = args.MODULE + return + + +def addfunc(module): + """ добавление новой функцию из модуля (module)""" + if module is not None: # если введено имя модуля + try: + spec = importlib.util.find_spec(module) + except ImportError: + print('ERROR: module ', module, 'not found, or unknown symbol') + exit(0) + if spec is None: # проверка возможности импорта модуля + print('ERROR: unknown function or module ', module, 'not found') + exit(0) + else: + newfunc = importlib.import_module(module) # импортирование нового модуля + funcdic[module] = newfunc.main + funclist.append(module) + funcset.add(module) + return + + +def parse(xprstr): + """ парсинг строки математического выражения. на выходе список в инфиксной нотации""" + word = '' + xprlst = [] + # проверка скобок в строке + if xpr.count('(') != xpr.count(')') or len(xpr) == 0: + print('ERROR: brackets are not balanced') + exit(0) + # устранение пробелов с операторами и повторов операторов + while xprstr.count(' ') > 0 or \ + xprstr.count('++') > 0 or \ + xprstr.count('--') > 0 or \ + xprstr.count('-+') > 0 or \ + xprstr.count('+-') > 0 or \ + xprstr.count(' *') > 0 or \ + xprstr.count('* ') > 0 or \ + xprstr.count(' +') > 0 or \ + xprstr.count('+ ') > 0 or \ + xprstr.count(' -') > 0 or \ + xprstr.count('- ') > 0 or \ + xprstr.count(', ') > 0: + xprstr = xprstr.replace(' ', ' ') + xprstr = xprstr.replace('--', '+') + xprstr = xprstr.replace('++', '+') + xprstr = xprstr.replace('+-', '-') + xprstr = xprstr.replace('-+', '-') + xprstr = xprstr.replace(' *', '*') + xprstr = xprstr.replace('* ', '*') + xprstr = xprstr.replace(' +', '+') + xprstr = xprstr.replace('+ ', '+') + xprstr = xprstr.replace(' -', '-') + xprstr = xprstr.replace('- ', '-') + xprstr = xprstr.replace(', ', ',') + if xprstr[0] == '+': + xprstr = xprstr[1:] + + if xprstr.count(' ') > 0: # проверка лишних пробелов + print('ERROR: useles spaces') + exit(0) + + # добавление скобок для возведения в степень 2^3^4 + right = len(xprstr) + for i in range(xprstr.count('^')): + right = xprstr.rindex('^', 0, right) + if xprstr[:right].count('^') == 0: + break + left = xprstr.rindex('^', 0, right)+1 + tmp = xprstr[left:right] + tmpset = set(tmp) + if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): + # print('надо скобки для степени') + xprstr = xprstr[:left]+'('+xprstr[left:] + left = right+2 + right = len(xprstr) + for i, data in enumerate(xprstr[left:]): + if data in split and data != '(': + right = left+i + break + tmp = xprstr[left:right] + xprstr = xprstr[:right]+')'+xprstr[right:] + else: + # print('НЕ надо скобки', left, right) + right = left + + # разбор строки + for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел + if sym in split or i == len(xprstr): + if word == 'pi': + xprlst.append(pi) + elif word == 'e': + xprlst.append(e) + elif word in funclist: # если функция + xprlst.append(word) + elif word.replace('.', '').isdigit() and word.count('.') < 2: # если цифра + xprlst.append(float(word)) + elif word != '': # если не пусто и непонятно что, возможно это внешняя функция + addfunc(word) # попытка импортировать неизвестную функцию + xprlst.append(word) + xprlst.append(sym) + word = '' + else: + word = word + sym + xprlst.pop() # удаляется добавленный пробел + + # если выражение содержит только функции без аргументов + # xprset = set(xprlst) + # if xprset.issubset(funcset): + # print('ERROR: function has no arguments') + # exit(0) + + # print('поииск операторов составных') + for i, data in enumerate(xprlst): + if i == len(xprlst) - 1: + break + # print(i, data) + if str(xprlst[i]) + str(xprlst[i+1]) in oper: + xprlst[i+1] = str(xprlst[i]) + str(xprlst[i+1]) + xprlst.pop(i) + if xprlst[i] == '-' and xprlst[i-1] in oper+['('] and type(xprlst[i+1]) == float: + xprlst[i+1] = xprlst[i+1] * -1 + xprlst.pop(i) + if xprlst[i] == '-' and xprlst[i-1] == '(' and xprlst[i+1] in funclist: + xprlst[i] = -1 + xprlst.insert(i+1, '*') + + if xprlst[0] == '-': + xprlst[0] = -1 + xprlst.insert(1, '*') + # print(*xprlst, sep='') + + print (*xprlst, sep='|') + return xprlst + + + + + +def prior(op1, op2): + """ сравнивает приоритеты математических опрераторов и функций op1 <= op2, возвращает bool """ + operhi = ['^'] + funclist # 3 + opermid = ['*', '/', '%', '//'] # 2 + operlow = ['+', '-'] # 1 + operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 + priorset = [operlowest, operlow, opermid, operhi] + for i, data in enumerate(priorset): + if op1 in data: + pr1 = i + if op2 in data: + pr2 = i + return pr1 <= pr2 + + +def postfix(xprlst): + """ преобразование инфиксной нотации в постфиксную + на входе список элементов выражения инфиксной нотации, на выходе список элементов постфиксной нотации """ + output = [] + stack = [] + for i in xprlst: + if type(i) == float or type(i) == int: # если цифра то положить на выход + output.append(i) + + elif i == ',': # если , то положить на выход + if stack != []: + while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): + # пока наверху стека оператор с большим или равным приоритетом + output.append(stack.pop()) # переложить оператор из стека на выход + output.append(i) + + elif i in oper: # если оператор то положить в стек + if stack == []: # если стек пуст, оператор добавить в стек + stack.append(i) + elif stack[-1] == '(': # если стек содержит ( положить в стек ( + stack.append(i) + else: + while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): + # пока наверху стека оператор с большим или равным приоритетом + output.append(stack.pop()) # переложить оператор из стека на выход + stack.append(i) # иначе положить оператор в стек + + elif i in funclist or i == '(': # если функция или ( то помещаем в стек + stack.append(i) + + elif i == ')': + while stack[-1] != '(': # пока верх стека не равен ( + output.append(stack.pop()) + # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке + stack.pop() # удаление из стека ( + # print('output=', *output, sep=' ') + # print('stack=', *stack, sep=' ') + stack.reverse() + print(output + stack) + + + # xprset = set(output + stack) + # if xprset.issubset(funcset): # проверка если функция без аргументов + # print('ERROR: function has no arguments') + # exit(0) + + + + return output + stack + + +def operate(operator, args): + """ выполняет математическое действие или функцию (operator) со списком аргументов (args) """ + global stack + + print('OPERATE', operator, 'ARGS', args, stack) + try: + result = funcdic[operator](*args) + print('FUNC *args') + except TypeError: + try: + result = funcdic[operator](args) + print('FUNC list args') + except TypeError: + + + try: + result = funcdic[operator] + print('FUNC no args') + except TypeError: + print('ERROR: invalid argument for ', operator) + exit(0) + + except ValueError: + print('ERROR: invalid argument for ', operator) + exit(0) + except ArithmeticError: + print('ERROR: invalid argument for ', operator) + exit(0) + except ValueError: + print('ERROR: invalid argument for ', operator) + exit(0) + print('RESULT', result) + return result + + + + +def evalpostfix(xprpstfx): + """ вычисление выражения в постфиксной нотации """ + global stack + stack = [] + args = [] + for i in xprpstfx: + #print('i = ', i) + if i in funclist: + + if len(stack) == 0: # для функций типа sin(x) + print(' STACK = 0') + stack.append(operate(i)) + + + if len(stack) == 1: # для функций типа sin(x) + print(' STACK = 1') + stack[0] = operate(i, stack[0]) + elif len(stack) > 1: # для функций типа sum(a,b,c,d...) формирование списка аргументов функции + j = len(stack)-2 + args.append(stack[-1]) + while stack[j] == ',': + args.append(stack[j-1]) + stack.pop() + stack.pop() + j = j - 2 + stack.pop() + args.reverse() + tmp = operate(i, args) + args = [] + stack.append(tmp) + elif i in oper: # для операторов типа a + b + tmp = operate(i, stack[-2:]) + # print(stack[-2:]) + stack.pop() + stack.pop() + stack.append(tmp) + else: + stack.append(i) # если число то добавить его в стек + print('STACK',stack) + return stack[0] + + +def main(): + # парсинг аргументов командной строки xpr выражение и module модуль функции + parsecmd() + + # попытка добавления внешней функции если указана -m module + addfunc(module) + + # разбор строки вырыжения в список + xprlst = parse(xpr) + print('PARSE ', *xprlst, sep=' ') + + # преобразование инфиксного списка в постфиксных список + xprlst = postfix(xprlst) + print('POSTFIX ', *xprlst, sep=' ') + + # вычисление постфиксного списка + result = evalpostfix(xprlst) + + return result + + +print(main()) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 7d1adad6..f5f31bc3 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -67,29 +67,14 @@ def addfunc(module): return - def parse(xprstr): """ парсинг строки математического выражения. на выходе список в инфиксной нотации""" word = '' xprlst = [] - #exset = {'"', '#', '$', '&', "'", ':', ';', '?', '@', '[', ']', '_', '`', '{', '|', '}', '~', '\\'} - xprset = set(xprstr) - # проверка если строка выражения содержит недопустимые символы - # if not exset.isdisjoint(xprset): - # print('ERROR: unknown symbol') - # exit(0) # проверка скобок в строке - - - if xpr.count('(') != xpr.count(')') or len(xpr) == 0: print('ERROR: brackets are not balanced') exit(0) - # проверка если выражение состоит только из знаков пунктуации - #if xprset.issubset(string.punctuation): - # print('ERROR: no digits or functions') - # exit(0) - # устранение пробелов с операторами и повторов операторов while xprstr.count(' ') > 0 or \ xprstr.count('++') > 0 or \ @@ -115,19 +100,14 @@ def parse(xprstr): xprstr = xprstr.replace(' -', '-') xprstr = xprstr.replace('- ', '-') xprstr = xprstr.replace(', ', ',') - if xprstr[0] == '+': xprstr = xprstr[1:] - # print(xprstr) - - # проверка лишних пробелов - if xprstr.count(' ') > 0: + if xprstr.count(' ') > 0: # проверка лишних пробелов print('ERROR: useles spaces') exit(0) # добавление скобок для возведения в степень 2^3^4 - left = 0 right = len(xprstr) for i in range(xprstr.count('^')): right = xprstr.rindex('^', 0, right) @@ -137,7 +117,7 @@ def parse(xprstr): tmp = xprstr[left:right] tmpset = set(tmp) if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): - # print('надj скобки для степени') + # print('надо скобки для степени') xprstr = xprstr[:left]+'('+xprstr[left:] left = right+2 right = len(xprstr) @@ -155,31 +135,27 @@ def parse(xprstr): for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): if word == 'pi': - xprlst.append(pi) + xprlst.append('pi') elif word == 'e': xprlst.append(e) elif word in funclist: # если функция xprlst.append(word) elif word.replace('.', '').isdigit() and word.count('.') < 2: # если цифра xprlst.append(float(word)) - elif word in split or word == '': # если оператор или пусто - pass - else: # если непонятно что, возможно это внешняя функция + elif word != '': # если не пусто и непонятно что, возможно это внешняя функция addfunc(word) # попытка импортировать неизвестную функцию xprlst.append(word) xprlst.append(sym) - # print(xprlst) word = '' else: word = word + sym - # print(word) xprlst.pop() # удаляется добавленный пробел # если выражение содержит только функции без аргументов - xprset = set(xprlst) - if xprset.issubset(funcset): - print('ERROR: function has no arguments') - exit(0) + # xprset = set(xprlst) + # if xprset.issubset(funcset): + # print('ERROR: function has no arguments') + # exit(0) # print('поииск операторов составных') for i, data in enumerate(xprlst): @@ -201,30 +177,11 @@ def parse(xprstr): xprlst.insert(1, '*') # print(*xprlst, sep='') - # print (*xprlst, sep='|') + print (*xprlst, sep='|') return xprlst -def operate(operator, args): - """ выполняет математическое действие или функцию (operator) со списком аргументов (args) """ - try: - result = funcdic[operator](*args) - except TypeError: - try: - result = funcdic[operator](args) - except TypeError: - print('ERROR: invalid argument for ', operator) - exit(0) - except ValueError: - print('ERROR: invalid argument for ', operator) - exit(0) - except ArithmeticError: - print('ERROR: invalid argument for ', operator) - exit(0) - except ValueError: - print('ERROR: invalid argument for ', operator) - exit(0) - return result + def prior(op1, op2): @@ -280,19 +237,78 @@ def postfix(xprlst): # print('output=', *output, sep=' ') # print('stack=', *stack, sep=' ') stack.reverse() + print(output + stack) + + + # xprset = set(output + stack) + # if xprset.issubset(funcset): # проверка если функция без аргументов + # print('ERROR: function has no arguments') + # exit(0) + + + return output + stack +def operate(operator, args): + """ выполняет математическое действие или функцию (operator) со списком аргументов (args) """ + global stack + global flag + + print('OPERATE', operator, 'ARGS', args, 'STACK', stack) + try: + result = funcdic[operator](*args) + stack.pop() + print('FUNC *args') + except TypeError: + try: + result = funcdic[operator](args) + stack.pop() + print('FUNC list args') + except TypeError: + # print('ERROR: invalid argument for ', operator) + # exit(0) + try: + result = funcdic[operator] + flag = 1 + print('FUNC no args') + except TypeError: + print('ERROR: invalid argument for ', operator) + exit(0) + + except ValueError: + print('ERROR: invalid argument for ', operator) + exit(0) + except ArithmeticError: + print('ERROR: invalid argument for ', operator) + exit(0) + except ValueError: + print('ERROR: invalid argument for ', operator) + exit(0) + print('RESULT', result) + return result + + + + def evalpostfix(xprpstfx): """ вычисление выражения в постфиксной нотации """ + global stack + global flag stack = [] args = [] + flag = 0 for i in xprpstfx: - # # print('EVAL i = ', i, 'STACK=',stack) + print('i = ', i, 'stack', stack) if i in funclist: - if len(stack) < 2: # для функций типа sin(x) - stack[0] = operate(i, stack[0]) - else: # для функций типа sum(a,b,c,d...) формирование списка аргументов функции + + + if len(stack) == 0: + args = 0 + if len(stack) == 1: + args = stack[0] + if len(stack) > 1: # для функций типа sum(a,b,c,d...) формирование списка аргументов функции + print('stack > 2') j = len(stack)-2 args.append(stack[-1]) while stack[j] == ',': @@ -300,19 +316,29 @@ def evalpostfix(xprpstfx): stack.pop() stack.pop() j = j - 2 - stack.pop() + #stack.pop() args.reverse() - tmp = operate(i, args) - args = [] - stack.append(tmp) + print('STACK', stack) + + tmp = operate(i, args) + args = [] + + stack.append(tmp) + + + + elif i in oper: # для операторов типа a + b - tmp = operate(i, stack[-2:]) + print('OPERATE', i,*stack[-2:]) + tmp = funcdic[i](*stack[-2:]) + #tmp = operate(i, stack[-2:]) # print(stack[-2:]) stack.pop() stack.pop() stack.append(tmp) else: stack.append(i) # если число то добавить его в стек + print('STACK',stack) return stack[0] @@ -325,11 +351,11 @@ def main(): # разбор строки вырыжения в список xprlst = parse(xpr) - # print(*xprlst, sep=' ') + print('PARSE ', *xprlst, sep=' ') # преобразование инфиксного списка в постфиксных список xprlst = postfix(xprlst) - # print(*xprlst, sep=' ') + print('POSTFIX ', *xprlst, sep=' ') # вычисление постфиксного списка result = evalpostfix(xprlst) From 28288dfc21a8feaaf94f5cfb499ead30c4512dfd Mon Sep 17 00:00:00 2001 From: novash-k Date: Sat, 11 May 2019 08:43:12 -0400 Subject: [PATCH 102/159] test --- final_task/pycalc.py | 45 ++++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index f5f31bc3..a2a79b2a 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -117,7 +117,7 @@ def parse(xprstr): tmp = xprstr[left:right] tmpset = set(tmp) if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): - # print('надо скобки для степени') + # # print('надо скобки для степени') xprstr = xprstr[:left]+'('+xprstr[left:] left = right+2 right = len(xprstr) @@ -128,7 +128,7 @@ def parse(xprstr): tmp = xprstr[left:right] xprstr = xprstr[:right]+')'+xprstr[right:] else: - # print('НЕ надо скобки', left, right) + # # print('НЕ надо скобки', left, right) right = left # разбор строки @@ -157,11 +157,11 @@ def parse(xprstr): # print('ERROR: function has no arguments') # exit(0) - # print('поииск операторов составных') + # # print('поииск операторов составных') for i, data in enumerate(xprlst): if i == len(xprlst) - 1: break - # print(i, data) + # # print(i, data) if str(xprlst[i]) + str(xprlst[i+1]) in oper: xprlst[i+1] = str(xprlst[i]) + str(xprlst[i+1]) xprlst.pop(i) @@ -175,9 +175,9 @@ def parse(xprstr): if xprlst[0] == '-': xprlst[0] = -1 xprlst.insert(1, '*') - # print(*xprlst, sep='') + # # print(*xprlst, sep='') - print (*xprlst, sep='|') + # print (*xprlst, sep='|') return xprlst @@ -234,10 +234,10 @@ def postfix(xprlst): output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке stack.pop() # удаление из стека ( - # print('output=', *output, sep=' ') - # print('stack=', *stack, sep=' ') + # # print('output=', *output, sep=' ') + # # print('stack=', *stack, sep=' ') stack.reverse() - print(output + stack) + # print(output + stack) # xprset = set(output + stack) @@ -255,23 +255,23 @@ def operate(operator, args): global stack global flag - print('OPERATE', operator, 'ARGS', args, 'STACK', stack) + # print('OPERATE', operator, 'ARGS', args, 'STACK', stack) try: result = funcdic[operator](*args) stack.pop() - print('FUNC *args') + # print('FUNC *args') except TypeError: try: result = funcdic[operator](args) stack.pop() - print('FUNC list args') + # print('FUNC list args') except TypeError: # print('ERROR: invalid argument for ', operator) # exit(0) try: result = funcdic[operator] flag = 1 - print('FUNC no args') + # print('FUNC no args') except TypeError: print('ERROR: invalid argument for ', operator) exit(0) @@ -285,7 +285,7 @@ def operate(operator, args): except ValueError: print('ERROR: invalid argument for ', operator) exit(0) - print('RESULT', result) + # print('RESULT', result) return result @@ -299,7 +299,7 @@ def evalpostfix(xprpstfx): args = [] flag = 0 for i in xprpstfx: - print('i = ', i, 'stack', stack) + # print('i = ', i, 'stack', stack) if i in funclist: @@ -308,7 +308,7 @@ def evalpostfix(xprpstfx): if len(stack) == 1: args = stack[0] if len(stack) > 1: # для функций типа sum(a,b,c,d...) формирование списка аргументов функции - print('stack > 2') + # print('stack > 2') j = len(stack)-2 args.append(stack[-1]) while stack[j] == ',': @@ -318,7 +318,7 @@ def evalpostfix(xprpstfx): j = j - 2 #stack.pop() args.reverse() - print('STACK', stack) + # print('STACK', stack) tmp = operate(i, args) args = [] @@ -329,16 +329,16 @@ def evalpostfix(xprpstfx): elif i in oper: # для операторов типа a + b - print('OPERATE', i,*stack[-2:]) + # print('OPERATE', i,*stack[-2:]) tmp = funcdic[i](*stack[-2:]) #tmp = operate(i, stack[-2:]) - # print(stack[-2:]) + # # print(stack[-2:]) stack.pop() stack.pop() stack.append(tmp) else: stack.append(i) # если число то добавить его в стек - print('STACK',stack) + # print('STACK',stack) return stack[0] @@ -351,11 +351,11 @@ def main(): # разбор строки вырыжения в список xprlst = parse(xpr) - print('PARSE ', *xprlst, sep=' ') + # print('PARSE ', *xprlst, sep=' ') # преобразование инфиксного списка в постфиксных список xprlst = postfix(xprlst) - print('POSTFIX ', *xprlst, sep=' ') + # print('POSTFIX ', *xprlst, sep=' ') # вычисление постфиксного списка result = evalpostfix(xprlst) @@ -363,4 +363,5 @@ def main(): return result + print(main()) From 4e507bd3ec529d0cc8a453fa0de9137771f7b75e Mon Sep 17 00:00:00 2001 From: novash-k Date: Sat, 11 May 2019 09:31:37 -0400 Subject: [PATCH 103/159] test --- final_task/funcx.py | 5 +++ final_task/funcxy.py | 5 +++ final_task/pycalc.py | 88 ++++++++++++++++---------------------------- 3 files changed, 42 insertions(+), 56 deletions(-) create mode 100644 final_task/funcx.py create mode 100644 final_task/funcxy.py diff --git a/final_task/funcx.py b/final_task/funcx.py new file mode 100644 index 00000000..0c089845 --- /dev/null +++ b/final_task/funcx.py @@ -0,0 +1,5 @@ +def main(x): + x = (x + x) * x + return x + + diff --git a/final_task/funcxy.py b/final_task/funcxy.py new file mode 100644 index 00000000..381b37cd --- /dev/null +++ b/final_task/funcxy.py @@ -0,0 +1,5 @@ +def main(x, y): + x = (x + y) * 2 + return x + + diff --git a/final_task/pycalc.py b/final_task/pycalc.py index a2a79b2a..af527a5a 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -33,7 +33,7 @@ funcdic.update(operdic) oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!='] operset = set(oper) -xpr = ' ' +xpr = '' def parsecmd(): @@ -175,15 +175,11 @@ def parse(xprstr): if xprlst[0] == '-': xprlst[0] = -1 xprlst.insert(1, '*') - # # print(*xprlst, sep='') # print (*xprlst, sep='|') return xprlst - - - def prior(op1, op2): """ сравнивает приоритеты математических опрераторов и функций op1 <= op2, возвращает bool """ operhi = ['^'] + funclist # 3 @@ -239,39 +235,27 @@ def postfix(xprlst): stack.reverse() # print(output + stack) - # xprset = set(output + stack) # if xprset.issubset(funcset): # проверка если функция без аргументов # print('ERROR: function has no arguments') # exit(0) - - - return output + stack def operate(operator, args): """ выполняет математическое действие или функцию (operator) со списком аргументов (args) """ global stack - global flag - - # print('OPERATE', operator, 'ARGS', args, 'STACK', stack) + print('OPERATE', operator, 'ARGS', args, 'STACK', stack) try: - result = funcdic[operator](*args) + result = funcdic[operator](*args) # если функция с одним или двумя аргументами типа sin(x), pow(x,y) stack.pop() - # print('FUNC *args') except TypeError: try: - result = funcdic[operator](args) + result = funcdic[operator](args) # если функция с аргументом типа список sum(x,y,z,...) stack.pop() - # print('FUNC list args') except TypeError: - # print('ERROR: invalid argument for ', operator) - # exit(0) try: - result = funcdic[operator] - flag = 1 - # print('FUNC no args') + result = funcdic[operator] # если функция без аргументов типа pi, e, tau except TypeError: print('ERROR: invalid argument for ', operator) exit(0) @@ -285,60 +269,52 @@ def operate(operator, args): except ValueError: print('ERROR: invalid argument for ', operator) exit(0) - # print('RESULT', result) + print('RESULT', result) return result - - def evalpostfix(xprpstfx): """ вычисление выражения в постфиксной нотации """ global stack - global flag stack = [] args = [] - flag = 0 for i in xprpstfx: - # print('i = ', i, 'stack', stack) - if i in funclist: - - + print('evalpostfix i=',i) + if i in funclist: # если функция типа sin, pow, sum, tau if len(stack) == 0: - args = 0 + args = 0 # функция без аргументов типа pi, e, tau if len(stack) == 1: - args = stack[0] - if len(stack) > 1: # для функций типа sum(a,b,c,d...) формирование списка аргументов функции - # print('stack > 2') + args = stack[0] # один аргумент функции типа sin(x) + if len(stack) > 1: j = len(stack)-2 - args.append(stack[-1]) - while stack[j] == ',': - args.append(stack[j-1]) - stack.pop() - stack.pop() + args.append(stack[-1]) # один аргумент функции типа sin(x) + while stack[j] == ',': # если в стэке список аргументов разделенных запятой , + args.append(stack[j-1]) # добавить в список агрументов функции типа pow(x,y), sum(x,y,z,...) + stack.pop() # удалить из стэка , + stack.pop() # удалить из стэка аргумент j = j - 2 - #stack.pop() args.reverse() # print('STACK', stack) - - tmp = operate(i, args) + stack.append(operate(i, args)) # удаление аргумента из стэка произойдет в функции operate args = [] - stack.append(tmp) - - + elif i in oper: # если оператор типа a + b + print('OPERATE', i, 'ARGS', *stack[-2:], 'STACK', stack) + try: + tmp = funcdic[i](*stack[-2:]) + except TypeError: + print('ERROR: invalid argument for ', i) + exit(0) + - elif i in oper: # для операторов типа a + b - # print('OPERATE', i,*stack[-2:]) - tmp = funcdic[i](*stack[-2:]) - #tmp = operate(i, stack[-2:]) - # # print(stack[-2:]) - stack.pop() - stack.pop() + stack.pop() # удалить из стэка аргумент a + stack.pop() # удалить из стэка аргумент b stack.append(tmp) + print('RESULT', tmp) else: - stack.append(i) # если число то добавить его в стек - # print('STACK',stack) + stack.append(i) # если число то добавить его в стэк + print('STACK',stack) return stack[0] @@ -351,11 +327,11 @@ def main(): # разбор строки вырыжения в список xprlst = parse(xpr) - # print('PARSE ', *xprlst, sep=' ') + print('PARSE ', *xprlst, sep=' ') # преобразование инфиксного списка в постфиксных список xprlst = postfix(xprlst) - # print('POSTFIX ', *xprlst, sep=' ') + print('POSTFIX ', *xprlst, sep=' ') # вычисление постфиксного списка result = evalpostfix(xprlst) From ce4920efbf1c12a99bfa418a3669b61d0d73df94 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sat, 11 May 2019 09:38:45 -0400 Subject: [PATCH 104/159] test --- final_task/pycalc.py | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index af527a5a..0441cfb8 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -117,7 +117,7 @@ def parse(xprstr): tmp = xprstr[left:right] tmpset = set(tmp) if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): - # # print('надо скобки для степени') + # # # print('надо скобки для степени') xprstr = xprstr[:left]+'('+xprstr[left:] left = right+2 right = len(xprstr) @@ -128,7 +128,7 @@ def parse(xprstr): tmp = xprstr[left:right] xprstr = xprstr[:right]+')'+xprstr[right:] else: - # # print('НЕ надо скобки', left, right) + # # # print('НЕ надо скобки', left, right) right = left # разбор строки @@ -157,11 +157,11 @@ def parse(xprstr): # print('ERROR: function has no arguments') # exit(0) - # # print('поииск операторов составных') + # # # print('поииск операторов составных') for i, data in enumerate(xprlst): if i == len(xprlst) - 1: break - # # print(i, data) + # # # print(i, data) if str(xprlst[i]) + str(xprlst[i+1]) in oper: xprlst[i+1] = str(xprlst[i]) + str(xprlst[i+1]) xprlst.pop(i) @@ -176,7 +176,7 @@ def parse(xprstr): xprlst[0] = -1 xprlst.insert(1, '*') - # print (*xprlst, sep='|') + # # print (*xprlst, sep='|') return xprlst @@ -230,10 +230,10 @@ def postfix(xprlst): output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке stack.pop() # удаление из стека ( - # # print('output=', *output, sep=' ') - # # print('stack=', *stack, sep=' ') + # # # print('output=', *output, sep=' ') + # # # print('stack=', *stack, sep=' ') stack.reverse() - # print(output + stack) + # # print(output + stack) # xprset = set(output + stack) # if xprset.issubset(funcset): # проверка если функция без аргументов @@ -245,7 +245,7 @@ def postfix(xprlst): def operate(operator, args): """ выполняет математическое действие или функцию (operator) со списком аргументов (args) """ global stack - print('OPERATE', operator, 'ARGS', args, 'STACK', stack) + # print('OPERATE', operator, 'ARGS', args, 'STACK', stack) try: result = funcdic[operator](*args) # если функция с одним или двумя аргументами типа sin(x), pow(x,y) stack.pop() @@ -269,7 +269,7 @@ def operate(operator, args): except ValueError: print('ERROR: invalid argument for ', operator) exit(0) - print('RESULT', result) + # print('RESULT', result) return result @@ -279,7 +279,7 @@ def evalpostfix(xprpstfx): stack = [] args = [] for i in xprpstfx: - print('evalpostfix i=',i) + # print('evalpostfix i=',i) if i in funclist: # если функция типа sin, pow, sum, tau if len(stack) == 0: args = 0 # функция без аргументов типа pi, e, tau @@ -294,12 +294,12 @@ def evalpostfix(xprpstfx): stack.pop() # удалить из стэка аргумент j = j - 2 args.reverse() - # print('STACK', stack) + # # print('STACK', stack) stack.append(operate(i, args)) # удаление аргумента из стэка произойдет в функции operate args = [] elif i in oper: # если оператор типа a + b - print('OPERATE', i, 'ARGS', *stack[-2:], 'STACK', stack) + # print('OPERATE', i, 'ARGS', *stack[-2:], 'STACK', stack) try: tmp = funcdic[i](*stack[-2:]) @@ -311,10 +311,10 @@ def evalpostfix(xprpstfx): stack.pop() # удалить из стэка аргумент a stack.pop() # удалить из стэка аргумент b stack.append(tmp) - print('RESULT', tmp) + # print('RESULT', tmp) else: stack.append(i) # если число то добавить его в стэк - print('STACK',stack) + # print('STACK',stack) return stack[0] @@ -327,11 +327,11 @@ def main(): # разбор строки вырыжения в список xprlst = parse(xpr) - print('PARSE ', *xprlst, sep=' ') + # print('PARSE ', *xprlst, sep=' ') # преобразование инфиксного списка в постфиксных список xprlst = postfix(xprlst) - print('POSTFIX ', *xprlst, sep=' ') + # print('POSTFIX ', *xprlst, sep=' ') # вычисление постфиксного списка result = evalpostfix(xprlst) @@ -340,4 +340,4 @@ def main(): -print(main()) +# print(main()) From 0a8691d8beb8a979d40027f2d8209d7ed7873f47 Mon Sep 17 00:00:00 2001 From: novash-k Date: Sat, 11 May 2019 09:49:39 -0400 Subject: [PATCH 105/159] test --- final_task/pycalc.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 0441cfb8..c51573de 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -340,4 +340,4 @@ def main(): -# print(main()) +print(main()) From 7c4731608cf544b6e057f8b5734337999d823e5e Mon Sep 17 00:00:00 2001 From: Konastantin Novash Date: Sun, 12 May 2019 00:19:35 +0300 Subject: [PATCH 106/159] test --- final_task/.idea/final_task.iml | 11 ++ .../inspectionProfiles/Project_Default.xml | 100 +++++++++++++ final_task/.idea/misc.xml | 4 + final_task/.idea/modules.xml | 8 ++ final_task/.idea/vcs.xml | 6 + final_task/.idea/workspace.xml | 135 ++++++++++++++++++ final_task/pycalc.py | 31 ++-- 7 files changed, 285 insertions(+), 10 deletions(-) create mode 100644 final_task/.idea/final_task.iml create mode 100644 final_task/.idea/inspectionProfiles/Project_Default.xml create mode 100644 final_task/.idea/misc.xml create mode 100644 final_task/.idea/modules.xml create mode 100644 final_task/.idea/vcs.xml create mode 100644 final_task/.idea/workspace.xml diff --git a/final_task/.idea/final_task.iml b/final_task/.idea/final_task.iml new file mode 100644 index 00000000..67116063 --- /dev/null +++ b/final_task/.idea/final_task.iml @@ -0,0 +1,11 @@ + + + + + + + + + + \ No newline at end of file diff --git a/final_task/.idea/inspectionProfiles/Project_Default.xml b/final_task/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 00000000..40f60dfc --- /dev/null +++ b/final_task/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,100 @@ + + + + \ No newline at end of file diff --git a/final_task/.idea/misc.xml b/final_task/.idea/misc.xml new file mode 100644 index 00000000..a43ec93e --- /dev/null +++ b/final_task/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/final_task/.idea/modules.xml b/final_task/.idea/modules.xml new file mode 100644 index 00000000..50b3aa4b --- /dev/null +++ b/final_task/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/final_task/.idea/vcs.xml b/final_task/.idea/vcs.xml new file mode 100644 index 00000000..6c0b8635 --- /dev/null +++ b/final_task/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/final_task/.idea/workspace.xml b/final_task/.idea/workspace.xml new file mode 100644 index 00000000..421453b9 --- /dev/null +++ b/final_task/.idea/workspace.xml @@ -0,0 +1,135 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + - + - + - - - - - - @@ -116,21 +179,51 @@ + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + \ No newline at end of file diff --git a/final_task/_pycalc.py b/final_task/_pycalc.py deleted file mode 100644 index 91b5f62a..00000000 --- a/final_task/_pycalc.py +++ /dev/null @@ -1,364 +0,0 @@ -import argparse -import math -import operator -from operator import * -import string -import importlib -import importlib.util -from math import * - -split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') -splitset = set(split) -funclist = dir(math)+['abs', 'round', 'sum'] # list of math functions names -funcdic = math.__dict__ # dict of math functions -funcset = set(funclist) -operdic = { - '+': add, - '-': sub, - '*': mul, - '/': truediv, - '//': floordiv, - '%': mod, - '^': pow, - '==': eq, - '<=': le, - '>=': ge, - '<': lt, - '>': gt, - '!=': ne, - 'abs': abs, - 'round': round, - 'sum': sum - } -funcdic.update(operdic) -oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!='] -operset = set(oper) -xpr = '' - - -def parsecmd(): - """ парсинг командной строки """ - global xpr, module - ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') - ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') - ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') - args = ap.parse_args() - xpr = args.EXPRESSION - module = args.MODULE - return - - -def addfunc(module): - """ добавление новой функцию из модуля (module)""" - if module is not None: # если введено имя модуля - try: - spec = importlib.util.find_spec(module) - except ImportError: - print('ERROR: module ', module, 'not found, or unknown symbol') - exit(0) - if spec is None: # проверка возможности импорта модуля - print('ERROR: unknown function or module ', module, 'not found') - exit(0) - else: - newfunc = importlib.import_module(module) # импортирование нового модуля - funcdic[module] = newfunc.main - funclist.append(module) - funcset.add(module) - return - - -def parse(xprstr): - """ парсинг строки математического выражения. на выходе список в инфиксной нотации""" - word = '' - xprlst = [] - xprset = set(xpr) - - operset.add(' ') - if xprset.issubset(operset): # проверка если выражение сосотоит только из операторов или пробелов - print('ERROR: no digits or funcs in expr') - exit(0) - - if xpr.count('(') != xpr.count(')') or len(xpr) == 0: # проверка скобок в строке - print('ERROR: brackets are not balanced') - exit(0) - - # устранение пробелов с операторами и повторов операторов - while xprstr.count(' ') > 0 or \ - xprstr.count('++') > 0 or \ - xprstr.count('--') > 0 or \ - xprstr.count('-+') > 0 or \ - xprstr.count('+-') > 0 or \ - xprstr.count(' *') > 0 or \ - xprstr.count('* ') > 0 or \ - xprstr.count(' +') > 0 or \ - xprstr.count('+ ') > 0 or \ - xprstr.count(' -') > 0 or \ - xprstr.count('- ') > 0 or \ - xprstr.count(', ') > 0: - xprstr = xprstr.replace(' ', ' ') - xprstr = xprstr.replace('--', '+') - xprstr = xprstr.replace('++', '+') - xprstr = xprstr.replace('+-', '-') - xprstr = xprstr.replace('-+', '-') - xprstr = xprstr.replace(' *', '*') - xprstr = xprstr.replace('* ', '*') - xprstr = xprstr.replace(' +', '+') - xprstr = xprstr.replace('+ ', '+') - xprstr = xprstr.replace(' -', '-') - xprstr = xprstr.replace('- ', '-') - xprstr = xprstr.replace(', ', ',') - if xprstr[0] == '+': - xprstr = xprstr[1:] - - if xprstr.count(' ') > 0: # проверка лишних пробелов - print('ERROR: useles spaces') - exit(0) - - # добавление скобок для возведения в степень в степени типа 2^3^4 - right = len(xprstr) - for i in range(xprstr.count('^')): - right = xprstr.rindex('^', 0, right) - if xprstr[:right].count('^') == 0: - break - left = xprstr.rindex('^', 0, right)+1 - tmp = xprstr[left:right] - tmpset = set(tmp) - if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): - # print('надо скобки') - xprstr = xprstr[:left]+'('+xprstr[left:] - left = right+2 - right = len(xprstr) - for j, data in enumerate(xprstr[left:]): - if data in split and data != '(': - right = left+j - break - tmp = xprstr[left:right] - xprstr = xprstr[:right]+')'+xprstr[right:] - else: - # print('НЕ надо скобки', left, right) - right = left - - # разбор строки - for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел - - # проверка digit( , )digit без оператора - if i < len(xprstr)-1: - if xprstr[i].isdigit() and xprstr[i+1] == '(': - print('ERROR: digit ', xprstr[i], 'and ( without operator') - exit(0) - if xprstr[i] == ')' and xprstr[i+1].isdigit(): - print('ERROR: ) and digit without operator') - exit(0) - - if sym in split or i == len(xprstr): - if word == 'pi': - xprlst.append('pi') - elif word == 'e': - xprlst.append(e) - elif word in funclist: # если функция - xprlst.append(word) - elif word.replace('.', '').isdigit() and word.count('.') < 2: # если цифра - xprlst.append(float(word)) - elif word != '': # если не пусто и непонятно что, возможно это внешняя функция - addfunc(word) # попытка импортировать неизвестную функцию - xprlst.append(word) - xprlst.append(sym) - word = '' - else: - word = word + sym - xprlst.pop() # удаляется добавленный пробел - - # поииск операторов составных типа <= >= == != содержащихся в списке oper - for i, data in enumerate(xprlst): - if i == len(xprlst) - 1: - break - # print(i, data) - if str(xprlst[i]) + str(xprlst[i+1]) in oper: - xprlst[i+1] = str(xprlst[i]) + str(xprlst[i+1]) - xprlst.pop(i) - if xprlst[i] == '-' and xprlst[i-1] in oper+['('] and type(xprlst[i+1]) == float: - xprlst[i+1] = xprlst[i+1] * -1 - xprlst.pop(i) - if xprlst[i] == '-' and xprlst[i-1] == '(' and xprlst[i+1] in funclist: - xprlst[i] = -1 - xprlst.insert(i+1, '*') - - if xprlst[0] == '-': - xprlst[0] = -1 - xprlst.insert(1, '*') - - # print (*xprlst, sep='|') - return xprlst - - -def prior(op1, op2): - """ сравнивает приоритеты математических опрераторов и функций op1 <= op2, возвращает bool """ - operhi = ['^'] + funclist # 3 - opermid = ['*', '/', '%', '//'] # 2 - operlow = ['+', '-'] # 1 - operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 - priorset = [operlowest, operlow, opermid, operhi] - for i, data in enumerate(priorset): - if op1 in data: - pr1 = i - if op2 in data: - pr2 = i - return pr1 <= pr2 - - -def postfix(xprlst): - """ преобразование инфиксной нотации в постфиксную - на входе список элементов выражения инфиксной нотации, на выходе список элементов постфиксной нотации """ - output = [] - stack = [] - for i in xprlst: - if type(i) == float or type(i) == int: # если цифра то положить на выход - output.append(i) - - elif i == ',': # если , то положить на выход - if stack != []: - while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): - # пока наверху стека оператор с большим или равным приоритетом - output.append(stack.pop()) # переложить оператор из стека на выход - output.append(i) - - elif i in oper: # если оператор то положить в стек - if stack == []: # если стек пуст, оператор добавить в стек - stack.append(i) - elif stack[-1] == '(': # если стек содержит ( положить в стек ( - stack.append(i) - else: - while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): - # пока наверху стека оператор с большим или равным приоритетом - output.append(stack.pop()) # переложить оператор из стека на выход - stack.append(i) # иначе положить оператор в стек - - elif i in funclist or i == '(': # если функция или ( то помещаем в стек - stack.append(i) - - elif i == ')': - while stack[-1] != '(': # пока верх стека не равен ( - output.append(stack.pop()) - # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке - stack.pop() # удаление из стека ( - # print('output=', *output, sep=' ') - # print('stack=', *stack, sep=' ') - stack.reverse() - # print(output + stack) - - # xprset = set(output + stack) - # if xprset.issubset(funcset): # проверка если функция без аргументов - # print('ERROR: function has no arguments') - # exit(0) - return output + stack - - -def operate(operator, args): - """ выполняет математическое действие или функцию (operator) со списком аргументов (args) """ - global stack - print('OPERATE', operator, 'ARGS', args, 'STACK', stack) - try: - # print('TRY *args', operator, *args) - result = funcdic[operator](*args) # если функция с одним или двумя аргументами типа sin(x), pow(x,y) - # print('ok') - stack.pop() - except TypeError: - try: - # print('TRY args', operator, args) - result = funcdic[operator](args) # если функция с аргументом типа список sum(x,y,z,...) - # print('ok') - try: - stack.pop() - except IndexError: - print('ERROR: invalid argument for ', operator) - exit(0) - except TypeError: - try: - # print('TRY no args', operator, args) - result = funcdic[operator] # если функция без аргументов типа pi, e, tau - if type(result) != float: - print('ERROR: invalid argument for ', operator) - exit(0) - # print('ok') - except TypeError: - print('ERROR: invalid argument for ', operator) - exit(0) - - except ValueError: - print('ERROR: invalid argument for ', operator) - exit(0) - except ArithmeticError: - print('ERROR: invalid argument for ', operator) - exit(0) - except ValueError: - print('ERROR: invalid argument for ', operator) - exit(0) - print('RESULT', result) - return result - - -def evalpostfix(xprpstfx): - """ вычисление выражения в постфиксной нотации """ - global stack - stack = [] - args = [] - for i in xprpstfx: - # print('evalpostfix i=',i) - if i in funclist: # если функция типа sin, pow, sum, tau - if len(stack) == 0: - args = 0 # функция без аргументов типа pi, e, tau - if len(stack) == 1: - args = stack[0] # один аргумент функции типа sin(x) - if len(stack) > 1: - j = len(stack)-2 - args.append(stack[-1]) # один аргумент функции типа sin(x) - while stack[j] == ',': # если в стэке список аргументов разделенных запятой , - args.append(stack[j-1]) # добавить в список агрументов функции типа pow(x,y), sum(x,y,z,...) - stack.pop() # удалить из стэка , - stack.pop() # удалить из стэка аргумент - j = j - 2 - args.reverse() - # print('STACK', stack) - stack.append(operate(i, args)) # удаление аргумента из стэка произойдет в функции operate - args = [] - - elif i in oper: # если оператор типа a + b - # print('OPERATE', i, 'ARGS', *stack[-2:], 'STACK', stack) - - try: - tmp = funcdic[i](*stack[-2:]) - except TypeError: - print('ERROR: invalid argument for ', i) - exit(0) - stack.pop() # удалить из стэка аргумент a - stack.pop() # удалить из стэка аргумент b - stack.append(tmp) - # print('RESULT', tmp) - else: - stack.append(i) # если число то добавить его в стэк - # print('STACK',stack) - return stack[0] - - -def main(): - # парсинг аргументов командной строки xpr выражение и module модуль функции - parsecmd() - - # попытка добавления внешней функции если указана -m module - addfunc(module) - - # разбор строки вырыжения в список - xprlst = parse(xpr) - print('PARSE ', *xprlst, sep=' ') - - # преобразование инфиксного списка в постфиксных список - xprlst = postfix(xprlst) - print('POSTFIX ', *xprlst, sep=' ') - - # вычисление постфиксного списка - result = evalpostfix(xprlst) - - return result - - -print(main()) diff --git a/final_task/func.py b/final_task/func.py index 84068806..b121e2ee 100644 --- a/final_task/func.py +++ b/final_task/func.py @@ -1,3 +1,2 @@ def main(): - - return 666 + return 666 \ No newline at end of file diff --git a/final_task/pycalc.py b/final_task/pycalc.py index c53872e8..07c05e27 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -12,24 +12,8 @@ funclist = dir(math)+['abs', 'round', 'sum'] # list of math functions names funcdic = math.__dict__ # dict of math functions funcset = set(funclist) -operdic = { - '+': add, - '-': sub, - '*': mul, - '/': truediv, - '//': floordiv, - '%': mod, - '^': pow, - '==': eq, - '<=': le, - '>=': ge, - '<': lt, - '>': gt, - '!=': ne, - 'abs': abs, - 'round': round, - 'sum': sum - } +operdic = {'+': add, '-': sub, '*': mul, '/': truediv, '//': floordiv, '%': mod, '^': pow, '==': eq, +'<=': le, '>=': ge, '<': lt, '>': gt, '!=': ne, 'abs': abs, 'round': round, 'sum': sum} funcdic.update(operdic) oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!='] operset = set(oper) @@ -47,23 +31,17 @@ def parsecmd(): module = args.MODULE return - def addfunc(module): """ добавление новой функцию из модуля (module)""" - if module is not None: # если введено имя модуля - try: - spec = importlib.util.find_spec(module) - except ImportError: - print('ERROR: module ', module, 'not found, or unknown symbol') - exit(0) - if spec is None: # проверка возможности импорта модуля - print('ERROR: unknown function or module ', module, 'not found') - exit(0) - else: - newfunc = importlib.import_module(module) # импортирование нового модуля - funcdic[module] = newfunc.main - funclist.append(module) - funcset.add(module) + try: + newfunc = importlib.import_module(module) # импортирование нового модуля + funcdic[module] = newfunc.main + funclist.append(module) + funcset.add(module) + except AttributeError: # module is None + pass + except ModuleNotFoundError: + raise ModuleNotFoundError('ERROR: module not found') return @@ -71,17 +49,12 @@ def parse(xprstr): """ парсинг строки математического выражения. на выходе список в инфиксной нотации""" word = '' xprlst = [] - xprset = set(xpr) - + xprset = set(xprstr) operset.add(' ') if xprset.issubset(operset): # проверка если выражение сосотоит только из операторов или пробелов - print('ERROR: no digits or funcs in expr') - exit(0) - - if xpr.count('(') != xpr.count(')') or len(xpr) == 0: # проверка скобок в строке - print('ERROR: brackets are not balanced') - exit(0) - + raise ValueError('ERROR: no digits or functions in expression') + if xprstr.count('(') != xprstr.count(')') or len(xprstr) == 0: # проверка скобок в строке + raise ValueError('ERROR: brackets are not balanced') # устранение пробелов с операторами и повторов операторов while xprstr.count(' ') > 0 or \ xprstr.count('++') > 0 or \ @@ -109,13 +82,9 @@ def parse(xprstr): xprstr = xprstr.replace(', ', ',') if xprstr[0] == '+': xprstr = xprstr[1:] - if xprstr.count(' ') > 0: # проверка лишних пробелов - print('ERROR: useles spaces') - exit(0) - - # добавление скобок для возведения в степень в степени типа 2^3^4 - right = len(xprstr) + raise ValueError('ERROR: useles spaces') + right = len(xprstr) # добавление скобок для возведения в степень в степени типа 2^3^4 for i in range(xprstr.count('^')): right = xprstr.rindex('^', 0, right) if xprstr[:right].count('^') == 0: @@ -123,8 +92,7 @@ def parse(xprstr): left = xprstr.rindex('^', 0, right)+1 tmp = xprstr[left:right] tmpset = set(tmp) - if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): - # print('надо скобки') + if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): # надо скобки xprstr = xprstr[:left]+'('+xprstr[left:] left = right+2 right = len(xprstr) @@ -134,18 +102,12 @@ def parse(xprstr): break tmp = xprstr[left:right] xprstr = xprstr[:right]+')'+xprstr[right:] - else: - # print('НЕ надо скобки', left, right) + else: # НЕ надо скобки right = left - # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): - if word == 'pi': - xprlst.append('pi') - elif word == 'e': - xprlst.append(e) - elif word in funclist: # если функция + if word in funclist: # если функция xprlst.append(word) elif word.replace('.', '').isdigit() and word.count('.') < 2: # если цифра xprlst.append(float(word)) @@ -158,19 +120,14 @@ def parse(xprstr): word = word + sym xprlst.pop() # удаляется добавленный пробел - # поииск операторов составных типа <= >= == != содержащихся в списке oper - for i, data in enumerate(xprlst): + for i, data in enumerate(xprlst): # поииск операторов составных типа <= >= == != содержащихся в списке oper if i < len(xprlst)-1: if type(xprlst[i]) == float and xprlst[i+1] == '(': # елсли перед скобкой цифра без оператора - print('ERROR: digit & ( wihout operator') - exit(0) + raise ValueError('ERROR: digit & ( wihout operator') if xprlst[i] == ')' and type(xprlst[i+1]) == float: # елсли после скобки цифра без оператора - print('ERROR: ) & digit wihout operator') - exit(0) - + raise ValueError('ERROR: ) & digit wihout operator') if i == len(xprlst) - 1: break - # print(i, data) if str(xprlst[i]) + str(xprlst[i+1]) in oper: xprlst[i+1] = str(xprlst[i]) + str(xprlst[i+1]) xprlst.pop(i) @@ -180,12 +137,9 @@ def parse(xprstr): if xprlst[i] == '-' and xprlst[i-1] == '(' and xprlst[i+1] in funclist: xprlst[i] = -1 xprlst.insert(i+1, '*') - if xprlst[0] == '-': xprlst[0] = -1 xprlst.insert(1, '*') - - # print (*xprlst, sep='|') return xprlst @@ -212,14 +166,12 @@ def postfix(xprlst): for i in xprlst: if type(i) == float or type(i) == int: # если цифра то положить на выход output.append(i) - elif i == ',': # если , то положить на выход if stack != []: while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом output.append(stack.pop()) # переложить оператор из стека на выход output.append(i) - elif i in oper: # если оператор то положить в стек if stack == []: # если стек пуст, оператор добавить в стек stack.append(i) @@ -230,19 +182,13 @@ def postfix(xprlst): # пока наверху стека оператор с большим или равным приоритетом output.append(stack.pop()) # переложить оператор из стека на выход stack.append(i) # иначе положить оператор в стек - elif i in funclist or i == '(': # если функция или ( то помещаем в стек stack.append(i) - elif i == ')': while stack[-1] != '(': # пока верх стека не равен ( - output.append(stack.pop()) - # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке + output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке stack.pop() # удаление из стека ( - # print('output=', *output, sep=' ') - # print('stack=', *stack, sep=' ') stack.reverse() - # print(output + stack) return output + stack @@ -251,44 +197,25 @@ def operate(operator, args): global stack # print('OPERATE', operator, 'ARGS', args, 'STACK', stack) try: - # print('TRY *args', operator, *args) result = funcdic[operator](*args) # если функция с одним или двумя аргументами типа sin(x), pow(x,y) stack.pop() except TypeError: try: - # print('TRY args', operator, args) result = funcdic[operator](args) # если функция с аргументом типа список sum(x,y,z,...) - try: - stack.pop() - except IndexError: - print('ERROR: invalid argument for ', operator) - exit(0) + stack.pop() except TypeError: try: - # print('TRY no args ()', operator, args) result = funcdic[operator]() # если функция без аргументов типа pi, e, tau except TypeError: - # print('ERROR: invalid arguxxxment for ', operator) try: - # print('TRY no args', operator, args) - result = funcdic[operator] # если функция без аргументов типа pi, e, tau - # print(result) + result = funcdic[operator] # если внешняя функция без аргументов типа pi, e, tau + print('try noargs res=', result) if type(result) != float: - print('ERROR: invxxxalid argument for ', operator) - exit(0) + raise ValueError('ERROR: not float argument for ', operator) except TypeError: - print('ERROR: invalid argument for ', operator, '()') - exit(0) - except ValueError: - print('ERROR: invalid argument for ', operator) - exit(0) - except ArithmeticError: - print('ERROR: invalid argument for ', operator) - exit(0) + raise ValueError('ERROR: invalid argument for ', operator) except ValueError: - print('ERROR: invalid argument for ', operator) - exit(0) - # print('RESULT', result) + print('неправильный аргумент для sin') return result @@ -298,7 +225,6 @@ def evalpostfix(xprpstfx): stack = [] args = [] for i in xprpstfx: - # print('evalpostfix i=',i) if i in funclist: # если функция типа sin, pow, sum, tau if len(stack) == 0: args = 0 # функция без аргументов типа pi, e, tau @@ -313,7 +239,6 @@ def evalpostfix(xprpstfx): stack.pop() # удалить из стэка аргумент j = j - 2 args.reverse() - # print('STACK', stack) stack.append(operate(i, args)) # удаление аргумента из стэка произойдет в функции operate args = [] @@ -322,37 +247,35 @@ def evalpostfix(xprpstfx): try: tmp = funcdic[i](*stack[-2:]) except TypeError: - print('ERROR: invalid argument for ', i) - exit(0) + raise ValueError('ERROR: invalid argument for operator', i) stack.pop() # удалить из стэка аргумент a stack.pop() # удалить из стэка аргумент b stack.append(tmp) - # print('RESULT', tmp) + # # print('RESULT', tmp) else: stack.append(i) # если число то добавить его в стэк - # print('STACK',stack) + # # print('STACK',stack) return stack[0] -def main(): - # парсинг аргументов командной строки xpr выражение и module модуль функции - parsecmd() - - # попытка добавления внешней функции если указана -m module - addfunc(module) - - # разбор строки вырыжения в список - xprlst = parse(xpr) - # print('PARSE ', *xprlst, sep=' ') - - # преобразование инфиксного списка в постфиксных список - xprlst = postfix(xprlst) - # print('POSTFIX ', *xprlst, sep=' ') +def calc(xpr): + xprlst = parse(xpr) # разбор строки вырыжения в список + xprlst = postfix(xprlst) # преобразование инфиксного списка в постфиксных список + result = evalpostfix(xprlst) # вычисление постфиксного списка + print(result) + return result - # вычисление постфиксного списка - result = evalpostfix(xprlst) - return result +def main(): + global xpr, module + try: + parsecmd() # парсинг аргументов командной строки xpr выражение и module модуль функции + addfunc(module) # попытка добавления внешней функции если указана -m module + calc(xpr) # калькулятор. вычисление выражения в строке xpr + except Exception as error: + print(error) + return -print(main()) +if __name__ == '__main__': + main() From bba5b8d00c4e3e06145c68d34388137fcc745038 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Wed, 15 May 2019 23:31:27 +0300 Subject: [PATCH 137/159] test --- final_task/.idea/workspace.xml | 24 ++++++------------------ final_task/pycalc.py | 3 +-- 2 files changed, 7 insertions(+), 20 deletions(-) diff --git a/final_task/.idea/workspace.xml b/final_task/.idea/workspace.xml index 05d0d758..f57a4f86 100644 --- a/final_task/.idea/workspace.xml +++ b/final_task/.idea/workspace.xml @@ -5,10 +5,6 @@ - - - - @@ -63,6 +50,7 @@ invalid invalid ar + print pycalc.main @@ -170,7 +158,7 @@ - + @@ -210,8 +198,8 @@ - - + + diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 07c05e27..3447269d 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -209,13 +209,12 @@ def operate(operator, args): except TypeError: try: result = funcdic[operator] # если внешняя функция без аргументов типа pi, e, tau - print('try noargs res=', result) if type(result) != float: raise ValueError('ERROR: not float argument for ', operator) except TypeError: raise ValueError('ERROR: invalid argument for ', operator) except ValueError: - print('неправильный аргумент для sin') + raise ValueError('ERROR: invalid argument for ', operator) return result From 4f50197ca60ea707ad7761dfda876f74588b07d3 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Thu, 16 May 2019 09:29:22 +0300 Subject: [PATCH 138/159] test --- final_task/.idea/workspace.xml | 22 +++++++------- final_task/pycalc.py | 52 ++++++++++++++++++++++++++++------ 2 files changed, 54 insertions(+), 20 deletions(-) diff --git a/final_task/.idea/workspace.xml b/final_task/.idea/workspace.xml index f57a4f86..126195c9 100644 --- a/final_task/.idea/workspace.xml +++ b/final_task/.idea/workspace.xml @@ -18,8 +18,8 @@ - - + + @@ -196,20 +196,20 @@ - + - - - - - + + - + - - + + + + + diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 3447269d..26386126 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -84,9 +84,30 @@ def parse(xprstr): xprstr = xprstr[1:] if xprstr.count(' ') > 0: # проверка лишних пробелов raise ValueError('ERROR: useles spaces') + + + right = len(xprstr) # добавление скобок для возведения в степень в степени типа 2^3^4 for i in range(xprstr.count('^')): right = xprstr.rindex('^', 0, right) + + # print('right', right) + if xprstr[right] == '^' and xprstr[right+1] == '-': # если возведение в степень типа ^-pi добавить скобки + xprstr = xprstr[:right+1]+'('+xprstr[right+1:] + # print('IF ^- (', 'right=',right,'len=',len(xprstr), xprstr) + j = right+3 + while j < len(xprstr): + # print('j=',j,xprstr[j]) + if xprstr[j] in oper+[')']: + # print('break',j) + break + # print('j+1',j) + j = j + 1 + # print(j) + xprstr = xprstr[:j]+')'+xprstr[j:] + # print('IF ^- )', xprstr) + + if xprstr[:right].count('^') == 0: break left = xprstr.rindex('^', 0, right)+1 @@ -104,6 +125,9 @@ def parse(xprstr): xprstr = xprstr[:right]+')'+xprstr[right:] else: # НЕ надо скобки right = left + + + # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): @@ -122,21 +146,26 @@ def parse(xprstr): for i, data in enumerate(xprlst): # поииск операторов составных типа <= >= == != содержащихся в списке oper if i < len(xprlst)-1: + + #if xprlst[i] == '^' and xprlst[i+1] == '-' + + + if type(xprlst[i]) == float and xprlst[i+1] == '(': # елсли перед скобкой цифра без оператора raise ValueError('ERROR: digit & ( wihout operator') if xprlst[i] == ')' and type(xprlst[i+1]) == float: # елсли после скобки цифра без оператора raise ValueError('ERROR: ) & digit wihout operator') if i == len(xprlst) - 1: break - if str(xprlst[i]) + str(xprlst[i+1]) in oper: - xprlst[i+1] = str(xprlst[i]) + str(xprlst[i+1]) + if str(xprlst[i]) + str(xprlst[i+1]) in oper: # '>' + '=' + xprlst[i+1] = str(xprlst[i]) + str(xprlst[i+1]) # '>=' xprlst.pop(i) - if xprlst[i] == '-' and xprlst[i-1] in oper+['('] and type(xprlst[i+1]) == float: - xprlst[i+1] = xprlst[i+1] * -1 + if xprlst[i] == '-' and xprlst[i-1] in oper+['('] and type(xprlst[i+1]) == float: # (-digit + xprlst[i+1] = xprlst[i+1] * -1 # (digit*(-1) xprlst.pop(i) - if xprlst[i] == '-' and xprlst[i-1] == '(' and xprlst[i+1] in funclist: + if xprlst[i] == '-' and xprlst[i-1] in oper+['('] and xprlst[i+1] in funclist: # (-func xprlst[i] = -1 - xprlst.insert(i+1, '*') + xprlst.insert(i+1, '*') # (-1*func if xprlst[0] == '-': xprlst[0] = -1 xprlst.insert(1, '*') @@ -195,7 +224,7 @@ def postfix(xprlst): def operate(operator, args): """ выполняет математическое действие или функцию (operator) со списком аргументов (args) """ global stack - # print('OPERATE', operator, 'ARGS', args, 'STACK', stack) + # # print('OPERATE', operator, 'ARGS', args, 'STACK', stack) try: result = funcdic[operator](*args) # если функция с одним или двумя аргументами типа sin(x), pow(x,y) stack.pop() @@ -215,6 +244,7 @@ def operate(operator, args): raise ValueError('ERROR: invalid argument for ', operator) except ValueError: raise ValueError('ERROR: invalid argument for ', operator) + # print('RESULT', result) return result @@ -238,6 +268,7 @@ def evalpostfix(xprpstfx): stack.pop() # удалить из стэка аргумент j = j - 2 args.reverse() + # print('OPERATE', i, 'ARGS', args, 'STACK', stack) stack.append(operate(i, args)) # удаление аргумента из стэка произойдет в функции operate args = [] @@ -250,16 +281,19 @@ def evalpostfix(xprpstfx): stack.pop() # удалить из стэка аргумент a stack.pop() # удалить из стэка аргумент b stack.append(tmp) - # # print('RESULT', tmp) + # print('RESULT', tmp) else: stack.append(i) # если число то добавить его в стэк - # # print('STACK',stack) + + # print('STACK',stack) return stack[0] def calc(xpr): xprlst = parse(xpr) # разбор строки вырыжения в список + # print(*xprlst, sep=' ') xprlst = postfix(xprlst) # преобразование инфиксного списка в постфиксных список + # print(*xprlst, sep=' ') result = evalpostfix(xprlst) # вычисление постфиксного списка print(result) return result From b1f3cca4783f52115077dc64ec264c1065e5e34b Mon Sep 17 00:00:00 2001 From: Konstantin Date: Thu, 16 May 2019 10:14:06 +0300 Subject: [PATCH 139/159] test --- final_task/.idea/workspace.xml | 10 ++++++---- final_task/pycalc.py | 8 +++----- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/final_task/.idea/workspace.xml b/final_task/.idea/workspace.xml index 126195c9..07c88bd9 100644 --- a/final_task/.idea/workspace.xml +++ b/final_task/.idea/workspace.xml @@ -18,8 +18,8 @@ - - + + @@ -51,12 +51,14 @@ invalid ar print + except TypeError pycalc.main print('ER pycalc.calc + # print @@ -205,8 +207,8 @@ - - + + diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 26386126..291da11f 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -274,10 +274,7 @@ def evalpostfix(xprpstfx): elif i in oper: # если оператор типа a + b # print('OPERATE', i, 'ARGS', *stack[-2:], 'STACK', stack) - try: - tmp = funcdic[i](*stack[-2:]) - except TypeError: - raise ValueError('ERROR: invalid argument for operator', i) + tmp = funcdic[i](*stack[-2:]) stack.pop() # удалить из стэка аргумент a stack.pop() # удалить из стэка аргумент b stack.append(tmp) @@ -306,7 +303,8 @@ def main(): addfunc(module) # попытка добавления внешней функции если указана -m module calc(xpr) # калькулятор. вычисление выражения в строке xpr except Exception as error: - print(error) + #except OSError: + print('ERROR:', error) return From 91af7c7e400f33288bf8edbeb58d3f376a8c191b Mon Sep 17 00:00:00 2001 From: Konstantin Date: Thu, 16 May 2019 10:19:44 +0300 Subject: [PATCH 140/159] test --- final_task/.idea/workspace.xml | 29 ++++++++++++++++++++++++----- final_task/func.py | 2 +- final_task/pycalc.py | 19 ++++--------------- 3 files changed, 29 insertions(+), 21 deletions(-) diff --git a/final_task/.idea/workspace.xml b/final_task/.idea/workspace.xml index 07c88bd9..402c4aa9 100644 --- a/final_task/.idea/workspace.xml +++ b/final_task/.idea/workspace.xml @@ -5,6 +5,7 @@ + @@ -52,6 +62,7 @@ print except TypeError + try pycalc.main @@ -73,6 +84,7 @@ @@ -170,7 +182,7 @@ - + @@ -205,10 +217,17 @@ + + + + + + + - - + + diff --git a/final_task/func.py b/final_task/func.py index b121e2ee..27c02152 100644 --- a/final_task/func.py +++ b/final_task/func.py @@ -1,2 +1,2 @@ def main(): - return 666 \ No newline at end of file + return 666 diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 291da11f..deae5198 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -12,8 +12,7 @@ funclist = dir(math)+['abs', 'round', 'sum'] # list of math functions names funcdic = math.__dict__ # dict of math functions funcset = set(funclist) -operdic = {'+': add, '-': sub, '*': mul, '/': truediv, '//': floordiv, '%': mod, '^': pow, '==': eq, -'<=': le, '>=': ge, '<': lt, '>': gt, '!=': ne, 'abs': abs, 'round': round, 'sum': sum} +operdic = {'+': add, '-': sub, '*': mul, '/': truediv, '//': floordiv, '%': mod, '^': pow, '==': eq, '<=': le, '>=': ge, '<': lt, '>': gt, '!=': ne, 'abs': abs, 'round': round, 'sum': sum} funcdic.update(operdic) oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!='] operset = set(oper) @@ -31,6 +30,7 @@ def parsecmd(): module = args.MODULE return + def addfunc(module): """ добавление новой функцию из модуля (module)""" try: @@ -85,12 +85,9 @@ def parse(xprstr): if xprstr.count(' ') > 0: # проверка лишних пробелов raise ValueError('ERROR: useles spaces') - - right = len(xprstr) # добавление скобок для возведения в степень в степени типа 2^3^4 for i in range(xprstr.count('^')): right = xprstr.rindex('^', 0, right) - # print('right', right) if xprstr[right] == '^' and xprstr[right+1] == '-': # если возведение в степень типа ^-pi добавить скобки xprstr = xprstr[:right+1]+'('+xprstr[right+1:] @@ -107,8 +104,7 @@ def parse(xprstr): xprstr = xprstr[:j]+')'+xprstr[j:] # print('IF ^- )', xprstr) - - if xprstr[:right].count('^') == 0: + if xprstr[:right].count('^') == 0: # добавление скобок для возведения в степень в степени типа 2^3^4 break left = xprstr.rindex('^', 0, right)+1 tmp = xprstr[left:right] @@ -126,8 +122,6 @@ def parse(xprstr): else: # НЕ надо скобки right = left - - # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): @@ -146,11 +140,6 @@ def parse(xprstr): for i, data in enumerate(xprlst): # поииск операторов составных типа <= >= == != содержащихся в списке oper if i < len(xprlst)-1: - - #if xprlst[i] == '^' and xprlst[i+1] == '-' - - - if type(xprlst[i]) == float and xprlst[i+1] == '(': # елсли перед скобкой цифра без оператора raise ValueError('ERROR: digit & ( wihout operator') if xprlst[i] == ')' and type(xprlst[i+1]) == float: # елсли после скобки цифра без оператора @@ -303,7 +292,7 @@ def main(): addfunc(module) # попытка добавления внешней функции если указана -m module calc(xpr) # калькулятор. вычисление выражения в строке xpr except Exception as error: - #except OSError: + #except OSError: print('ERROR:', error) return From 11c66e7951de90db8682e6c89b5616901bd37ee7 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Thu, 16 May 2019 10:33:56 +0300 Subject: [PATCH 141/159] test --- final_task/.idea/workspace.xml | 45 +-- final_task/pycalc 16may stable exept e-e.py | 317 ++++++++++++++++++++ final_task/pycalc.py | 21 +- 3 files changed, 347 insertions(+), 36 deletions(-) create mode 100644 final_task/pycalc 16may stable exept e-e.py diff --git a/final_task/.idea/workspace.xml b/final_task/.idea/workspace.xml index 402c4aa9..47ac949c 100644 --- a/final_task/.idea/workspace.xml +++ b/final_task/.idea/workspace.xml @@ -5,7 +5,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - + - @@ -217,22 +194,22 @@ - - - - - - - - - + + + + + + + + + \ No newline at end of file diff --git a/final_task/pycalc 16may stable exept e-e.py b/final_task/pycalc 16may stable exept e-e.py new file mode 100644 index 00000000..eb567ad0 --- /dev/null +++ b/final_task/pycalc 16may stable exept e-e.py @@ -0,0 +1,317 @@ +import argparse +import math +import operator +from operator import * +import string +import importlib +import importlib.util +from math import * + +split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') +splitset = set(split) +funclist = dir(math)+['abs', 'round', 'sum'] # list of math functions names +funcdic = math.__dict__ # dict of math functions +funcset = set(funclist) +operdic = { + '+': add, + '-': sub, + '*': mul, + '/': truediv, + '//': floordiv, + '%': mod, + '^': pow, + '==': eq, + '<=': le, + '>=': ge, + '<': lt, + '>': gt, + '!=': ne, + 'abs': abs, + 'round': round, + 'sum': sum + } +funcdic.update(operdic) +oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!='] +operset = set(oper) +xpr = '' + + +def parsecmd(): + """ парсинг командной строки """ + global xpr, module + ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') + ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') + ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') + args = ap.parse_args() + xpr = args.EXPRESSION + module = args.MODULE + return + + +def addfunc(module): + """ добавление новой функцию из модуля (module)""" + try: + newfunc = importlib.import_module(module) # импортирование нового модуля + funcdic[module] = newfunc.main + funclist.append(module) + funcset.add(module) + except AttributeError: # module is None + pass + except ModuleNotFoundError: + raise ModuleNotFoundError('ERROR: module not found') + return + + +def parse(xprstr): + """ парсинг строки математического выражения. на выходе список в инфиксной нотации""" + word = '' + xprlst = [] + xprset = set(xprstr) + operset.add(' ') + if xprset.issubset(operset): # проверка если выражение сосотоит только из операторов или пробелов + raise ValueError('ERROR: no digits or functions in expression') + if xprstr.count('(') != xprstr.count(')') or len(xprstr) == 0: # проверка скобок в строке + raise ValueError('ERROR: brackets are not balanced') + # устранение пробелов с операторами и повторов операторов + while xprstr.count(' ') > 0 or \ + xprstr.count('++') > 0 or \ + xprstr.count('--') > 0 or \ + xprstr.count('-+') > 0 or \ + xprstr.count('+-') > 0 or \ + xprstr.count(' *') > 0 or \ + xprstr.count('* ') > 0 or \ + xprstr.count(' +') > 0 or \ + xprstr.count('+ ') > 0 or \ + xprstr.count(' -') > 0 or \ + xprstr.count('- ') > 0 or \ + xprstr.count(', ') > 0: + xprstr = xprstr.replace(' ', ' ') + xprstr = xprstr.replace('--', '+') + xprstr = xprstr.replace('++', '+') + xprstr = xprstr.replace('+-', '-') + xprstr = xprstr.replace('-+', '-') + xprstr = xprstr.replace(' *', '*') + xprstr = xprstr.replace('* ', '*') + xprstr = xprstr.replace(' +', '+') + xprstr = xprstr.replace('+ ', '+') + xprstr = xprstr.replace(' -', '-') + xprstr = xprstr.replace('- ', '-') + xprstr = xprstr.replace(', ', ',') + if xprstr[0] == '+': + xprstr = xprstr[1:] + if xprstr.count(' ') > 0: # проверка лишних пробелов + raise ValueError('ERROR: useles spaces') + + right = len(xprstr) # добавление скобок для возведения в степень в степени типа 2^3^4 + for i in range(xprstr.count('^')): + right = xprstr.rindex('^', 0, right) + # print('right', right) + if xprstr[right] == '^' and xprstr[right+1] == '-': # если возведение в степень типа ^-pi добавить скобки + xprstr = xprstr[:right+1]+'('+xprstr[right+1:] + # print('IF ^- (', 'right=',right,'len=',len(xprstr), xprstr) + j = right+3 + while j < len(xprstr): + # print('j=',j,xprstr[j]) + if xprstr[j] in oper+[')']: + # print('break',j) + break + # print('j+1',j) + j = j + 1 + # print(j) + xprstr = xprstr[:j]+')'+xprstr[j:] + # print('IF ^- )', xprstr) + + if xprstr[:right].count('^') == 0: # добавление скобок для возведения в степень в степени типа 2^3^4 + break + left = xprstr.rindex('^', 0, right)+1 + tmp = xprstr[left:right] + tmpset = set(tmp) + if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): # надо скобки + xprstr = xprstr[:left]+'('+xprstr[left:] + left = right+2 + right = len(xprstr) + for j, data in enumerate(xprstr[left:]): + if data in split and data != '(': + right = left+j + break + tmp = xprstr[left:right] + xprstr = xprstr[:right]+')'+xprstr[right:] + else: # НЕ надо скобки + right = left + + # разбор строки + for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел + if sym in split or i == len(xprstr): + if word in funclist: # если функция + xprlst.append(word) + elif word.replace('.', '').isdigit() and word.count('.') < 2: # если цифра + xprlst.append(float(word)) + elif word != '': # если не пусто и непонятно что, возможно это внешняя функция + addfunc(word) # попытка импортировать неизвестную функцию + xprlst.append(word) + xprlst.append(sym) + word = '' + else: + word = word + sym + xprlst.pop() # удаляется добавленный пробел + + for i, data in enumerate(xprlst): # поииск операторов составных типа <= >= == != содержащихся в списке oper + if i < len(xprlst)-1: + if type(xprlst[i]) == float and xprlst[i+1] == '(': # елсли перед скобкой цифра без оператора + raise ValueError('ERROR: digit & ( wihout operator') + if xprlst[i] == ')' and type(xprlst[i+1]) == float: # елсли после скобки цифра без оператора + raise ValueError('ERROR: ) & digit wihout operator') + if i == len(xprlst) - 1: + break + if str(xprlst[i]) + str(xprlst[i+1]) in oper: # '>' + '=' + xprlst[i+1] = str(xprlst[i]) + str(xprlst[i+1]) # '>=' + xprlst.pop(i) + if xprlst[i] == '-' and xprlst[i-1] in oper+['('] and type(xprlst[i+1]) == float: # (-digit + xprlst[i+1] = xprlst[i+1] * -1 # (digit*(-1) + xprlst.pop(i) + if xprlst[i] == '-' and xprlst[i-1] in oper+['('] and xprlst[i+1] in funclist: # (-func + xprlst[i] = -1 + xprlst.insert(i+1, '*') # (-1*func + if xprlst[0] == '-': + xprlst[0] = -1 + xprlst.insert(1, '*') + return xprlst + + +def prior(op1, op2): + """ сравнивает приоритеты математических опрераторов и функций op1 <= op2, возвращает bool """ + operhi = ['^'] + funclist # 3 + opermid = ['*', '/', '%', '//'] # 2 + operlow = ['+', '-'] # 1 + operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 + priorset = [operlowest, operlow, opermid, operhi] + for i, data in enumerate(priorset): + if op1 in data: + pr1 = i + if op2 in data: + pr2 = i + return pr1 <= pr2 + + +def postfix(xprlst): + """ преобразование инфиксной нотации в постфиксную + на входе список элементов выражения инфиксной нотации, на выходе список элементов постфиксной нотации """ + output = [] + stack = [] + for i in xprlst: + if type(i) == float or type(i) == int: # если цифра то положить на выход + output.append(i) + elif i == ',': # если , то положить на выход + if stack != []: + while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): + # пока наверху стека оператор с большим или равным приоритетом + output.append(stack.pop()) # переложить оператор из стека на выход + output.append(i) + elif i in oper: # если оператор то положить в стек + if stack == []: # если стек пуст, оператор добавить в стек + stack.append(i) + elif stack[-1] == '(': # если стек содержит ( положить в стек ( + stack.append(i) + else: + while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): + # пока наверху стека оператор с большим или равным приоритетом + output.append(stack.pop()) # переложить оператор из стека на выход + stack.append(i) # иначе положить оператор в стек + elif i in funclist or i == '(': # если функция или ( то помещаем в стек + stack.append(i) + elif i == ')': + while stack[-1] != '(': # пока верх стека не равен ( + output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке + stack.pop() # удаление из стека ( + stack.reverse() + return output + stack + + +def operate(operator, args): + """ выполняет математическое действие или функцию (operator) со списком аргументов (args) """ + global stack + # # print('OPERATE', operator, 'ARGS', args, 'STACK', stack) + try: + result = funcdic[operator](*args) # если функция с одним или двумя аргументами типа sin(x), pow(x,y) + stack.pop() + except TypeError: + try: + result = funcdic[operator](args) # если функция с аргументом типа список sum(x,y,z,...) + stack.pop() + except TypeError: + try: + result = funcdic[operator]() # если функция без аргументов типа pi, e, tau + except TypeError: + try: + result = funcdic[operator] # если внешняя функция без аргументов типа pi, e, tau + if type(result) != float: + raise ValueError('ERROR: not float argument for ', operator) + except TypeError: + raise ValueError('ERROR: invalid argument for ', operator) + except ValueError: + raise ValueError('ERROR: invalid argument for ', operator) + # print('RESULT', result) + return result + + +def evalpostfix(xprpstfx): + """ вычисление выражения в постфиксной нотации """ + global stack + stack = [] + args = [] + for i in xprpstfx: + if i in funclist: # если функция типа sin, pow, sum, tau + if len(stack) == 0: + args = 0 # функция без аргументов типа pi, e, tau + if len(stack) == 1: + args = stack[0] # один аргумент функции типа sin(x) + if len(stack) > 1: + j = len(stack)-2 + args.append(stack[-1]) # один аргумент функции типа sin(x) + while stack[j] == ',': # если в стэке список аргументов разделенных запятой , + args.append(stack[j-1]) # добавить в список агрументов функции типа pow(x,y), sum(x,y,z,...) + stack.pop() # удалить из стэка , + stack.pop() # удалить из стэка аргумент + j = j - 2 + args.reverse() + # print('OPERATE', i, 'ARGS', args, 'STACK', stack) + stack.append(operate(i, args)) # удаление аргумента из стэка произойдет в функции operate + args = [] + + elif i in oper: # если оператор типа a + b + # print('OPERATE', i, 'ARGS', *stack[-2:], 'STACK', stack) + tmp = funcdic[i](*stack[-2:]) + stack.pop() # удалить из стэка аргумент a + stack.pop() # удалить из стэка аргумент b + stack.append(tmp) + # print('RESULT', tmp) + else: + stack.append(i) # если число то добавить его в стэк + + # print('STACK',stack) + return stack[0] + + +def calc(xpr): + xprlst = parse(xpr) # разбор строки вырыжения в список + # print(*xprlst, sep=' ') + xprlst = postfix(xprlst) # преобразование инфиксного списка в постфиксных список + # print(*xprlst, sep=' ') + result = evalpostfix(xprlst) # вычисление постфиксного списка + print(result) + return result + + +def main(): + global xpr, module + try: + parsecmd() # парсинг аргументов командной строки xpr выражение и module модуль функции + addfunc(module) # попытка добавления внешней функции если указана -m module + calc(xpr) # калькулятор. вычисление выражения в строке xpr + except Exception as error: + print('ERROR:', error) + return + + +if __name__ == '__main__': + main() diff --git a/final_task/pycalc.py b/final_task/pycalc.py index deae5198..d68df798 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,3 +1,4 @@ +# 16 may stable. exep, e^-e import argparse import math import operator @@ -12,7 +13,24 @@ funclist = dir(math)+['abs', 'round', 'sum'] # list of math functions names funcdic = math.__dict__ # dict of math functions funcset = set(funclist) -operdic = {'+': add, '-': sub, '*': mul, '/': truediv, '//': floordiv, '%': mod, '^': pow, '==': eq, '<=': le, '>=': ge, '<': lt, '>': gt, '!=': ne, 'abs': abs, 'round': round, 'sum': sum} +operdic = { + '+': add, + '-': sub, + '*': mul, + '/': truediv, + '//': floordiv, + '%': mod, + '^': pow, + '==': eq, + '<=': le, + '>=': ge, + '<': lt, + '>': gt, + '!=': ne, + 'abs': abs, + 'round': round, + 'sum': sum + } funcdic.update(operdic) oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!='] operset = set(oper) @@ -292,7 +310,6 @@ def main(): addfunc(module) # попытка добавления внешней функции если указана -m module calc(xpr) # калькулятор. вычисление выражения в строке xpr except Exception as error: - #except OSError: print('ERROR:', error) return From b8a815d4005eef36e0ff5bdded62971220d3e878 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Thu, 16 May 2019 11:09:33 +0300 Subject: [PATCH 142/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=BE=20=D0=B2=D0=BE=D0=B7=D0=B2=D0=B5=D0=B4?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B2=20-=D1=81=D1=82=D0=B5=D0=BF?= =?UTF-8?q?=D0=B5=D0=BD=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc 16may stable exept e-e.py | 317 -------------------- final_task/pycalc.py | 9 - 2 files changed, 326 deletions(-) delete mode 100644 final_task/pycalc 16may stable exept e-e.py diff --git a/final_task/pycalc 16may stable exept e-e.py b/final_task/pycalc 16may stable exept e-e.py deleted file mode 100644 index eb567ad0..00000000 --- a/final_task/pycalc 16may stable exept e-e.py +++ /dev/null @@ -1,317 +0,0 @@ -import argparse -import math -import operator -from operator import * -import string -import importlib -import importlib.util -from math import * - -split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') -splitset = set(split) -funclist = dir(math)+['abs', 'round', 'sum'] # list of math functions names -funcdic = math.__dict__ # dict of math functions -funcset = set(funclist) -operdic = { - '+': add, - '-': sub, - '*': mul, - '/': truediv, - '//': floordiv, - '%': mod, - '^': pow, - '==': eq, - '<=': le, - '>=': ge, - '<': lt, - '>': gt, - '!=': ne, - 'abs': abs, - 'round': round, - 'sum': sum - } -funcdic.update(operdic) -oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!='] -operset = set(oper) -xpr = '' - - -def parsecmd(): - """ парсинг командной строки """ - global xpr, module - ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') - ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') - ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') - args = ap.parse_args() - xpr = args.EXPRESSION - module = args.MODULE - return - - -def addfunc(module): - """ добавление новой функцию из модуля (module)""" - try: - newfunc = importlib.import_module(module) # импортирование нового модуля - funcdic[module] = newfunc.main - funclist.append(module) - funcset.add(module) - except AttributeError: # module is None - pass - except ModuleNotFoundError: - raise ModuleNotFoundError('ERROR: module not found') - return - - -def parse(xprstr): - """ парсинг строки математического выражения. на выходе список в инфиксной нотации""" - word = '' - xprlst = [] - xprset = set(xprstr) - operset.add(' ') - if xprset.issubset(operset): # проверка если выражение сосотоит только из операторов или пробелов - raise ValueError('ERROR: no digits or functions in expression') - if xprstr.count('(') != xprstr.count(')') or len(xprstr) == 0: # проверка скобок в строке - raise ValueError('ERROR: brackets are not balanced') - # устранение пробелов с операторами и повторов операторов - while xprstr.count(' ') > 0 or \ - xprstr.count('++') > 0 or \ - xprstr.count('--') > 0 or \ - xprstr.count('-+') > 0 or \ - xprstr.count('+-') > 0 or \ - xprstr.count(' *') > 0 or \ - xprstr.count('* ') > 0 or \ - xprstr.count(' +') > 0 or \ - xprstr.count('+ ') > 0 or \ - xprstr.count(' -') > 0 or \ - xprstr.count('- ') > 0 or \ - xprstr.count(', ') > 0: - xprstr = xprstr.replace(' ', ' ') - xprstr = xprstr.replace('--', '+') - xprstr = xprstr.replace('++', '+') - xprstr = xprstr.replace('+-', '-') - xprstr = xprstr.replace('-+', '-') - xprstr = xprstr.replace(' *', '*') - xprstr = xprstr.replace('* ', '*') - xprstr = xprstr.replace(' +', '+') - xprstr = xprstr.replace('+ ', '+') - xprstr = xprstr.replace(' -', '-') - xprstr = xprstr.replace('- ', '-') - xprstr = xprstr.replace(', ', ',') - if xprstr[0] == '+': - xprstr = xprstr[1:] - if xprstr.count(' ') > 0: # проверка лишних пробелов - raise ValueError('ERROR: useles spaces') - - right = len(xprstr) # добавление скобок для возведения в степень в степени типа 2^3^4 - for i in range(xprstr.count('^')): - right = xprstr.rindex('^', 0, right) - # print('right', right) - if xprstr[right] == '^' and xprstr[right+1] == '-': # если возведение в степень типа ^-pi добавить скобки - xprstr = xprstr[:right+1]+'('+xprstr[right+1:] - # print('IF ^- (', 'right=',right,'len=',len(xprstr), xprstr) - j = right+3 - while j < len(xprstr): - # print('j=',j,xprstr[j]) - if xprstr[j] in oper+[')']: - # print('break',j) - break - # print('j+1',j) - j = j + 1 - # print(j) - xprstr = xprstr[:j]+')'+xprstr[j:] - # print('IF ^- )', xprstr) - - if xprstr[:right].count('^') == 0: # добавление скобок для возведения в степень в степени типа 2^3^4 - break - left = xprstr.rindex('^', 0, right)+1 - tmp = xprstr[left:right] - tmpset = set(tmp) - if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): # надо скобки - xprstr = xprstr[:left]+'('+xprstr[left:] - left = right+2 - right = len(xprstr) - for j, data in enumerate(xprstr[left:]): - if data in split and data != '(': - right = left+j - break - tmp = xprstr[left:right] - xprstr = xprstr[:right]+')'+xprstr[right:] - else: # НЕ надо скобки - right = left - - # разбор строки - for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел - if sym in split or i == len(xprstr): - if word in funclist: # если функция - xprlst.append(word) - elif word.replace('.', '').isdigit() and word.count('.') < 2: # если цифра - xprlst.append(float(word)) - elif word != '': # если не пусто и непонятно что, возможно это внешняя функция - addfunc(word) # попытка импортировать неизвестную функцию - xprlst.append(word) - xprlst.append(sym) - word = '' - else: - word = word + sym - xprlst.pop() # удаляется добавленный пробел - - for i, data in enumerate(xprlst): # поииск операторов составных типа <= >= == != содержащихся в списке oper - if i < len(xprlst)-1: - if type(xprlst[i]) == float and xprlst[i+1] == '(': # елсли перед скобкой цифра без оператора - raise ValueError('ERROR: digit & ( wihout operator') - if xprlst[i] == ')' and type(xprlst[i+1]) == float: # елсли после скобки цифра без оператора - raise ValueError('ERROR: ) & digit wihout operator') - if i == len(xprlst) - 1: - break - if str(xprlst[i]) + str(xprlst[i+1]) in oper: # '>' + '=' - xprlst[i+1] = str(xprlst[i]) + str(xprlst[i+1]) # '>=' - xprlst.pop(i) - if xprlst[i] == '-' and xprlst[i-1] in oper+['('] and type(xprlst[i+1]) == float: # (-digit - xprlst[i+1] = xprlst[i+1] * -1 # (digit*(-1) - xprlst.pop(i) - if xprlst[i] == '-' and xprlst[i-1] in oper+['('] and xprlst[i+1] in funclist: # (-func - xprlst[i] = -1 - xprlst.insert(i+1, '*') # (-1*func - if xprlst[0] == '-': - xprlst[0] = -1 - xprlst.insert(1, '*') - return xprlst - - -def prior(op1, op2): - """ сравнивает приоритеты математических опрераторов и функций op1 <= op2, возвращает bool """ - operhi = ['^'] + funclist # 3 - opermid = ['*', '/', '%', '//'] # 2 - operlow = ['+', '-'] # 1 - operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 - priorset = [operlowest, operlow, opermid, operhi] - for i, data in enumerate(priorset): - if op1 in data: - pr1 = i - if op2 in data: - pr2 = i - return pr1 <= pr2 - - -def postfix(xprlst): - """ преобразование инфиксной нотации в постфиксную - на входе список элементов выражения инфиксной нотации, на выходе список элементов постфиксной нотации """ - output = [] - stack = [] - for i in xprlst: - if type(i) == float or type(i) == int: # если цифра то положить на выход - output.append(i) - elif i == ',': # если , то положить на выход - if stack != []: - while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): - # пока наверху стека оператор с большим или равным приоритетом - output.append(stack.pop()) # переложить оператор из стека на выход - output.append(i) - elif i in oper: # если оператор то положить в стек - if stack == []: # если стек пуст, оператор добавить в стек - stack.append(i) - elif stack[-1] == '(': # если стек содержит ( положить в стек ( - stack.append(i) - else: - while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): - # пока наверху стека оператор с большим или равным приоритетом - output.append(stack.pop()) # переложить оператор из стека на выход - stack.append(i) # иначе положить оператор в стек - elif i in funclist or i == '(': # если функция или ( то помещаем в стек - stack.append(i) - elif i == ')': - while stack[-1] != '(': # пока верх стека не равен ( - output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке - stack.pop() # удаление из стека ( - stack.reverse() - return output + stack - - -def operate(operator, args): - """ выполняет математическое действие или функцию (operator) со списком аргументов (args) """ - global stack - # # print('OPERATE', operator, 'ARGS', args, 'STACK', stack) - try: - result = funcdic[operator](*args) # если функция с одним или двумя аргументами типа sin(x), pow(x,y) - stack.pop() - except TypeError: - try: - result = funcdic[operator](args) # если функция с аргументом типа список sum(x,y,z,...) - stack.pop() - except TypeError: - try: - result = funcdic[operator]() # если функция без аргументов типа pi, e, tau - except TypeError: - try: - result = funcdic[operator] # если внешняя функция без аргументов типа pi, e, tau - if type(result) != float: - raise ValueError('ERROR: not float argument for ', operator) - except TypeError: - raise ValueError('ERROR: invalid argument for ', operator) - except ValueError: - raise ValueError('ERROR: invalid argument for ', operator) - # print('RESULT', result) - return result - - -def evalpostfix(xprpstfx): - """ вычисление выражения в постфиксной нотации """ - global stack - stack = [] - args = [] - for i in xprpstfx: - if i in funclist: # если функция типа sin, pow, sum, tau - if len(stack) == 0: - args = 0 # функция без аргументов типа pi, e, tau - if len(stack) == 1: - args = stack[0] # один аргумент функции типа sin(x) - if len(stack) > 1: - j = len(stack)-2 - args.append(stack[-1]) # один аргумент функции типа sin(x) - while stack[j] == ',': # если в стэке список аргументов разделенных запятой , - args.append(stack[j-1]) # добавить в список агрументов функции типа pow(x,y), sum(x,y,z,...) - stack.pop() # удалить из стэка , - stack.pop() # удалить из стэка аргумент - j = j - 2 - args.reverse() - # print('OPERATE', i, 'ARGS', args, 'STACK', stack) - stack.append(operate(i, args)) # удаление аргумента из стэка произойдет в функции operate - args = [] - - elif i in oper: # если оператор типа a + b - # print('OPERATE', i, 'ARGS', *stack[-2:], 'STACK', stack) - tmp = funcdic[i](*stack[-2:]) - stack.pop() # удалить из стэка аргумент a - stack.pop() # удалить из стэка аргумент b - stack.append(tmp) - # print('RESULT', tmp) - else: - stack.append(i) # если число то добавить его в стэк - - # print('STACK',stack) - return stack[0] - - -def calc(xpr): - xprlst = parse(xpr) # разбор строки вырыжения в список - # print(*xprlst, sep=' ') - xprlst = postfix(xprlst) # преобразование инфиксного списка в постфиксных список - # print(*xprlst, sep=' ') - result = evalpostfix(xprlst) # вычисление постфиксного списка - print(result) - return result - - -def main(): - global xpr, module - try: - parsecmd() # парсинг аргументов командной строки xpr выражение и module модуль функции - addfunc(module) # попытка добавления внешней функции если указана -m module - calc(xpr) # калькулятор. вычисление выражения в строке xpr - except Exception as error: - print('ERROR:', error) - return - - -if __name__ == '__main__': - main() diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 74eb788d..eb567ad0 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,4 +1,3 @@ -# 16 may stable. exep, e^-e import argparse import math import operator @@ -238,15 +237,7 @@ def operate(operator, args): except TypeError: try: result = funcdic[operator](args) # если функция с аргументом типа список sum(x,y,z,...) -<<<<<<< HEAD - try: - stack.pop() - except IndexError: - print('ERROR: invalid argument for ', operator) - exit(0) -======= stack.pop() ->>>>>>> test except TypeError: try: result = funcdic[operator]() # если функция без аргументов типа pi, e, tau From 3eb28974d2a1890691e514530a140bd192da1575 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Thu, 16 May 2019 11:17:48 +0300 Subject: [PATCH 143/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=BE=20=D0=B2=D0=BE=D0=B7=D0=B2=D0=B5=D0=B4?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B2=20-=D1=81=D1=82=D0=B5=D0=BF?= =?UTF-8?q?=D0=B5=D0=BD=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/.idea/workspace.xml | 25 +++++++++++++++++++++++++ final_task/pycalc.py | 1 + 2 files changed, 26 insertions(+) diff --git a/final_task/.idea/workspace.xml b/final_task/.idea/workspace.xml index 8a4999bd..843e3cbf 100644 --- a/final_task/.idea/workspace.xml +++ b/final_task/.idea/workspace.xml @@ -5,6 +5,10 @@ + + + + + + + diff --git a/final_task/pycalc.py b/final_task/pycalc.py index eb567ad0..b9b2261b 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,3 +1,4 @@ +# 16 may stable e^-e import argparse import math import operator From ac3187ce38bd7bc48b605fad91fd73b93c77955b Mon Sep 17 00:00:00 2001 From: Konstantin Date: Thu, 16 May 2019 11:20:00 +0300 Subject: [PATCH 144/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=BE=20=D0=B2=D0=BE=D0=B7=D0=B2=D0=B5=D0=B4?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B2=20-=D1=81=D1=82=D0=B5=D0=BF?= =?UTF-8?q?=D0=B5=D0=BD=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/pycalc 16may stable exept e-e.py | 317 -------------------- final_task/pycalc.py | 2 +- 2 files changed, 1 insertion(+), 318 deletions(-) delete mode 100644 final_task/pycalc 16may stable exept e-e.py diff --git a/final_task/pycalc 16may stable exept e-e.py b/final_task/pycalc 16may stable exept e-e.py deleted file mode 100644 index eb567ad0..00000000 --- a/final_task/pycalc 16may stable exept e-e.py +++ /dev/null @@ -1,317 +0,0 @@ -import argparse -import math -import operator -from operator import * -import string -import importlib -import importlib.util -from math import * - -split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') -splitset = set(split) -funclist = dir(math)+['abs', 'round', 'sum'] # list of math functions names -funcdic = math.__dict__ # dict of math functions -funcset = set(funclist) -operdic = { - '+': add, - '-': sub, - '*': mul, - '/': truediv, - '//': floordiv, - '%': mod, - '^': pow, - '==': eq, - '<=': le, - '>=': ge, - '<': lt, - '>': gt, - '!=': ne, - 'abs': abs, - 'round': round, - 'sum': sum - } -funcdic.update(operdic) -oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!='] -operset = set(oper) -xpr = '' - - -def parsecmd(): - """ парсинг командной строки """ - global xpr, module - ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') - ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') - ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') - args = ap.parse_args() - xpr = args.EXPRESSION - module = args.MODULE - return - - -def addfunc(module): - """ добавление новой функцию из модуля (module)""" - try: - newfunc = importlib.import_module(module) # импортирование нового модуля - funcdic[module] = newfunc.main - funclist.append(module) - funcset.add(module) - except AttributeError: # module is None - pass - except ModuleNotFoundError: - raise ModuleNotFoundError('ERROR: module not found') - return - - -def parse(xprstr): - """ парсинг строки математического выражения. на выходе список в инфиксной нотации""" - word = '' - xprlst = [] - xprset = set(xprstr) - operset.add(' ') - if xprset.issubset(operset): # проверка если выражение сосотоит только из операторов или пробелов - raise ValueError('ERROR: no digits or functions in expression') - if xprstr.count('(') != xprstr.count(')') or len(xprstr) == 0: # проверка скобок в строке - raise ValueError('ERROR: brackets are not balanced') - # устранение пробелов с операторами и повторов операторов - while xprstr.count(' ') > 0 or \ - xprstr.count('++') > 0 or \ - xprstr.count('--') > 0 or \ - xprstr.count('-+') > 0 or \ - xprstr.count('+-') > 0 or \ - xprstr.count(' *') > 0 or \ - xprstr.count('* ') > 0 or \ - xprstr.count(' +') > 0 or \ - xprstr.count('+ ') > 0 or \ - xprstr.count(' -') > 0 or \ - xprstr.count('- ') > 0 or \ - xprstr.count(', ') > 0: - xprstr = xprstr.replace(' ', ' ') - xprstr = xprstr.replace('--', '+') - xprstr = xprstr.replace('++', '+') - xprstr = xprstr.replace('+-', '-') - xprstr = xprstr.replace('-+', '-') - xprstr = xprstr.replace(' *', '*') - xprstr = xprstr.replace('* ', '*') - xprstr = xprstr.replace(' +', '+') - xprstr = xprstr.replace('+ ', '+') - xprstr = xprstr.replace(' -', '-') - xprstr = xprstr.replace('- ', '-') - xprstr = xprstr.replace(', ', ',') - if xprstr[0] == '+': - xprstr = xprstr[1:] - if xprstr.count(' ') > 0: # проверка лишних пробелов - raise ValueError('ERROR: useles spaces') - - right = len(xprstr) # добавление скобок для возведения в степень в степени типа 2^3^4 - for i in range(xprstr.count('^')): - right = xprstr.rindex('^', 0, right) - # print('right', right) - if xprstr[right] == '^' and xprstr[right+1] == '-': # если возведение в степень типа ^-pi добавить скобки - xprstr = xprstr[:right+1]+'('+xprstr[right+1:] - # print('IF ^- (', 'right=',right,'len=',len(xprstr), xprstr) - j = right+3 - while j < len(xprstr): - # print('j=',j,xprstr[j]) - if xprstr[j] in oper+[')']: - # print('break',j) - break - # print('j+1',j) - j = j + 1 - # print(j) - xprstr = xprstr[:j]+')'+xprstr[j:] - # print('IF ^- )', xprstr) - - if xprstr[:right].count('^') == 0: # добавление скобок для возведения в степень в степени типа 2^3^4 - break - left = xprstr.rindex('^', 0, right)+1 - tmp = xprstr[left:right] - tmpset = set(tmp) - if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): # надо скобки - xprstr = xprstr[:left]+'('+xprstr[left:] - left = right+2 - right = len(xprstr) - for j, data in enumerate(xprstr[left:]): - if data in split and data != '(': - right = left+j - break - tmp = xprstr[left:right] - xprstr = xprstr[:right]+')'+xprstr[right:] - else: # НЕ надо скобки - right = left - - # разбор строки - for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел - if sym in split or i == len(xprstr): - if word in funclist: # если функция - xprlst.append(word) - elif word.replace('.', '').isdigit() and word.count('.') < 2: # если цифра - xprlst.append(float(word)) - elif word != '': # если не пусто и непонятно что, возможно это внешняя функция - addfunc(word) # попытка импортировать неизвестную функцию - xprlst.append(word) - xprlst.append(sym) - word = '' - else: - word = word + sym - xprlst.pop() # удаляется добавленный пробел - - for i, data in enumerate(xprlst): # поииск операторов составных типа <= >= == != содержащихся в списке oper - if i < len(xprlst)-1: - if type(xprlst[i]) == float and xprlst[i+1] == '(': # елсли перед скобкой цифра без оператора - raise ValueError('ERROR: digit & ( wihout operator') - if xprlst[i] == ')' and type(xprlst[i+1]) == float: # елсли после скобки цифра без оператора - raise ValueError('ERROR: ) & digit wihout operator') - if i == len(xprlst) - 1: - break - if str(xprlst[i]) + str(xprlst[i+1]) in oper: # '>' + '=' - xprlst[i+1] = str(xprlst[i]) + str(xprlst[i+1]) # '>=' - xprlst.pop(i) - if xprlst[i] == '-' and xprlst[i-1] in oper+['('] and type(xprlst[i+1]) == float: # (-digit - xprlst[i+1] = xprlst[i+1] * -1 # (digit*(-1) - xprlst.pop(i) - if xprlst[i] == '-' and xprlst[i-1] in oper+['('] and xprlst[i+1] in funclist: # (-func - xprlst[i] = -1 - xprlst.insert(i+1, '*') # (-1*func - if xprlst[0] == '-': - xprlst[0] = -1 - xprlst.insert(1, '*') - return xprlst - - -def prior(op1, op2): - """ сравнивает приоритеты математических опрераторов и функций op1 <= op2, возвращает bool """ - operhi = ['^'] + funclist # 3 - opermid = ['*', '/', '%', '//'] # 2 - operlow = ['+', '-'] # 1 - operlowest = ['(', ')', '==', '<=', '>=', '<', '>', '!=', ','] # 0 - priorset = [operlowest, operlow, opermid, operhi] - for i, data in enumerate(priorset): - if op1 in data: - pr1 = i - if op2 in data: - pr2 = i - return pr1 <= pr2 - - -def postfix(xprlst): - """ преобразование инфиксной нотации в постфиксную - на входе список элементов выражения инфиксной нотации, на выходе список элементов постфиксной нотации """ - output = [] - stack = [] - for i in xprlst: - if type(i) == float or type(i) == int: # если цифра то положить на выход - output.append(i) - elif i == ',': # если , то положить на выход - if stack != []: - while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): - # пока наверху стека оператор с большим или равным приоритетом - output.append(stack.pop()) # переложить оператор из стека на выход - output.append(i) - elif i in oper: # если оператор то положить в стек - if stack == []: # если стек пуст, оператор добавить в стек - stack.append(i) - elif stack[-1] == '(': # если стек содержит ( положить в стек ( - stack.append(i) - else: - while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): - # пока наверху стека оператор с большим или равным приоритетом - output.append(stack.pop()) # переложить оператор из стека на выход - stack.append(i) # иначе положить оператор в стек - elif i in funclist or i == '(': # если функция или ( то помещаем в стек - stack.append(i) - elif i == ')': - while stack[-1] != '(': # пока верх стека не равен ( - output.append(stack.pop()) # выталкиваем элемент из стека на выход. удаляя последний элемент в стеке - stack.pop() # удаление из стека ( - stack.reverse() - return output + stack - - -def operate(operator, args): - """ выполняет математическое действие или функцию (operator) со списком аргументов (args) """ - global stack - # # print('OPERATE', operator, 'ARGS', args, 'STACK', stack) - try: - result = funcdic[operator](*args) # если функция с одним или двумя аргументами типа sin(x), pow(x,y) - stack.pop() - except TypeError: - try: - result = funcdic[operator](args) # если функция с аргументом типа список sum(x,y,z,...) - stack.pop() - except TypeError: - try: - result = funcdic[operator]() # если функция без аргументов типа pi, e, tau - except TypeError: - try: - result = funcdic[operator] # если внешняя функция без аргументов типа pi, e, tau - if type(result) != float: - raise ValueError('ERROR: not float argument for ', operator) - except TypeError: - raise ValueError('ERROR: invalid argument for ', operator) - except ValueError: - raise ValueError('ERROR: invalid argument for ', operator) - # print('RESULT', result) - return result - - -def evalpostfix(xprpstfx): - """ вычисление выражения в постфиксной нотации """ - global stack - stack = [] - args = [] - for i in xprpstfx: - if i in funclist: # если функция типа sin, pow, sum, tau - if len(stack) == 0: - args = 0 # функция без аргументов типа pi, e, tau - if len(stack) == 1: - args = stack[0] # один аргумент функции типа sin(x) - if len(stack) > 1: - j = len(stack)-2 - args.append(stack[-1]) # один аргумент функции типа sin(x) - while stack[j] == ',': # если в стэке список аргументов разделенных запятой , - args.append(stack[j-1]) # добавить в список агрументов функции типа pow(x,y), sum(x,y,z,...) - stack.pop() # удалить из стэка , - stack.pop() # удалить из стэка аргумент - j = j - 2 - args.reverse() - # print('OPERATE', i, 'ARGS', args, 'STACK', stack) - stack.append(operate(i, args)) # удаление аргумента из стэка произойдет в функции operate - args = [] - - elif i in oper: # если оператор типа a + b - # print('OPERATE', i, 'ARGS', *stack[-2:], 'STACK', stack) - tmp = funcdic[i](*stack[-2:]) - stack.pop() # удалить из стэка аргумент a - stack.pop() # удалить из стэка аргумент b - stack.append(tmp) - # print('RESULT', tmp) - else: - stack.append(i) # если число то добавить его в стэк - - # print('STACK',stack) - return stack[0] - - -def calc(xpr): - xprlst = parse(xpr) # разбор строки вырыжения в список - # print(*xprlst, sep=' ') - xprlst = postfix(xprlst) # преобразование инфиксного списка в постфиксных список - # print(*xprlst, sep=' ') - result = evalpostfix(xprlst) # вычисление постфиксного списка - print(result) - return result - - -def main(): - global xpr, module - try: - parsecmd() # парсинг аргументов командной строки xpr выражение и module модуль функции - addfunc(module) # попытка добавления внешней функции если указана -m module - calc(xpr) # калькулятор. вычисление выражения в строке xpr - except Exception as error: - print('ERROR:', error) - return - - -if __name__ == '__main__': - main() diff --git a/final_task/pycalc.py b/final_task/pycalc.py index d68df798..b9b2261b 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,4 +1,4 @@ -# 16 may stable. exep, e^-e +# 16 may stable e^-e import argparse import math import operator From 7f12b8cc9352c424c289fe5f878530476706bad6 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Thu, 16 May 2019 23:31:08 +0300 Subject: [PATCH 145/159] test --- final_task/.idea/workspace.xml | 87 +++++++++++++++++++++++++++++----- final_task/pycalc.py | 83 ++++++++++++++++++-------------- final_task/tmp.py | 17 +++++++ 3 files changed, 138 insertions(+), 49 deletions(-) create mode 100644 final_task/tmp.py diff --git a/final_task/.idea/workspace.xml b/final_task/.idea/workspace.xml index 47ac949c..e3c3e6a7 100644 --- a/final_task/.idea/workspace.xml +++ b/final_task/.idea/workspace.xml @@ -5,6 +5,7 @@ + - + + + + + + + + + + + + + + + + + + + + + + + @@ -63,11 +92,13 @@ - + - + + + + + @@ -147,7 +200,8 @@ - + + @@ -194,20 +248,27 @@ - + - - - - - + + - + - - + + + + + + + + + + + + diff --git a/final_task/pycalc.py b/final_task/pycalc.py index b9b2261b..25d94451 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,4 +1,4 @@ -# 16 may stable e^-e +# 16 may stable e^-e 2^-2^-2 import argparse import math import operator @@ -51,15 +51,18 @@ def parsecmd(): def addfunc(module): """ добавление новой функцию из модуля (module)""" - try: - newfunc = importlib.import_module(module) # импортирование нового модуля - funcdic[module] = newfunc.main - funclist.append(module) - funcset.add(module) - except AttributeError: # module is None - pass - except ModuleNotFoundError: - raise ModuleNotFoundError('ERROR: module not found') + if module is not None: # если введено имя модуля + try: + spec = importlib.util.find_spec(module) + except ImportError: + raise ValueError('ERROR: module ', module, 'not found, or unknown symbol') + if spec is None: # проверка возможности импорта модуля + raise ValueError('ERROR: unknown function or module ', module, 'not found') + else: + newfunc = importlib.import_module(module) # импортирование нового модуля + funcdic[module] = newfunc.main + funclist.append(module) + funcset.add(module) return @@ -103,40 +106,45 @@ def parse(xprstr): if xprstr.count(' ') > 0: # проверка лишних пробелов raise ValueError('ERROR: useles spaces') - right = len(xprstr) # добавление скобок для возведения в степень в степени типа 2^3^4 - for i in range(xprstr.count('^')): - right = xprstr.rindex('^', 0, right) - # print('right', right) + # добавление скобок для pi^-pi --> pi^(-pi) + right = len(xprstr) + for i in range(xprstr.count('^')): # столько раз в выражении содержится ^ + right = xprstr.rindex('^', 0, right) # поиск справа первого ^ if xprstr[right] == '^' and xprstr[right+1] == '-': # если возведение в степень типа ^-pi добавить скобки - xprstr = xprstr[:right+1]+'('+xprstr[right+1:] - # print('IF ^- (', 'right=',right,'len=',len(xprstr), xprstr) + xprstr = xprstr[:right+1]+'('+xprstr[right+1:] # добавляем левую ( j = right+3 - while j < len(xprstr): - # print('j=',j,xprstr[j]) + while j < len(xprstr): # ищем ^(выражение) if xprstr[j] in oper+[')']: - # print('break',j) break - # print('j+1',j) j = j + 1 - # print(j) - xprstr = xprstr[:j]+')'+xprstr[j:] - # print('IF ^- )', xprstr) - - if xprstr[:right].count('^') == 0: # добавление скобок для возведения в степень в степени типа 2^3^4 + xprstr = xprstr[:j]+')'+xprstr[j:] # добавляем правую ) + + # добавление скобок для возведение в степень типа 2^3^4 + right = len(xprstr) + for i in range(xprstr.count('^')): + right = xprstr.rindex('^', 0, right) + if xprstr[:right].count('^') == 0: break left = xprstr.rindex('^', 0, right)+1 tmp = xprstr[left:right] + # print('tmp=', tmp) tmpset = set(tmp) if (tmp[0] == '(' and tmp[-1] == ')') or (tmpset.isdisjoint(splitset)): # надо скобки xprstr = xprstr[:left]+'('+xprstr[left:] - left = right+2 - right = len(xprstr) - for j, data in enumerate(xprstr[left:]): - if data in split and data != '(': - right = left+j + lt = right+2 + # поиск от ^ вправо если () или до знака + brkt = 0 + # print('поиск ^ вправо', xprstr[ss:]) + for j, data in enumerate(xprstr[ss:]): + if data == '(': + brkt = brkt + 1 + if data == ')': + brkt = brkt - 1 + if data in split and data != '(' and brkt == 0: break - tmp = xprstr[left:right] - xprstr = xprstr[:right]+')'+xprstr[right:] + # print(j, data, brkt) + xprstr = xprstr[:lt + 1 + j]+')'+xprstr[lt + 1 + j:] + # print(xprstr, '!!!!!!!',ss, right) else: # НЕ надо скобки right = left @@ -231,7 +239,7 @@ def postfix(xprlst): def operate(operator, args): """ выполняет математическое действие или функцию (operator) со списком аргументов (args) """ global stack - # # print('OPERATE', operator, 'ARGS', args, 'STACK', stack) + # # # print('OPERATE', operator, 'ARGS', args, 'STACK', stack) try: result = funcdic[operator](*args) # если функция с одним или двумя аргументами типа sin(x), pow(x,y) stack.pop() @@ -251,7 +259,7 @@ def operate(operator, args): raise ValueError('ERROR: invalid argument for ', operator) except ValueError: raise ValueError('ERROR: invalid argument for ', operator) - # print('RESULT', result) + # # print('RESULT', result) return result @@ -275,12 +283,14 @@ def evalpostfix(xprpstfx): stack.pop() # удалить из стэка аргумент j = j - 2 args.reverse() - # print('OPERATE', i, 'ARGS', args, 'STACK', stack) + # print('OPERATEf', i, 'ARGS', args, 'STACK', stack) stack.append(operate(i, args)) # удаление аргумента из стэка произойдет в функции operate args = [] elif i in oper: # если оператор типа a + b - # print('OPERATE', i, 'ARGS', *stack[-2:], 'STACK', stack) + # print('OPERATEo', i, 'ARGS', *stack[-2:], 'STACK', stack) + # print(*stack[-2:]) + # print(funcdic[i]) tmp = funcdic[i](*stack[-2:]) stack.pop() # удалить из стэка аргумент a stack.pop() # удалить из стэка аргумент b @@ -309,6 +319,7 @@ def main(): parsecmd() # парсинг аргументов командной строки xpr выражение и module модуль функции addfunc(module) # попытка добавления внешней функции если указана -m module calc(xpr) # калькулятор. вычисление выражения в строке xpr + #except OEError: except Exception as error: print('ERROR:', error) return diff --git a/final_task/tmp.py b/final_task/tmp.py new file mode 100644 index 00000000..9a93b3d9 --- /dev/null +++ b/final_task/tmp.py @@ -0,0 +1,17 @@ +# сделать поиск от ^ вправо если () или до знака +split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') +xprstr = 'e^(-e)^(-e+(2-3))' +print(xprstr) +left = xprstr.rindex('^') +skob = 0 +print(xprstr[left:]) +for j, data in enumerate(xprstr[left+1:]): + if data == '(': + skob = skob + 1 + if data == ')': + skob = skob - 1 + if data in split and data != '(' and skob == 0: + break + print(j, data, skob) + +print('===', xprstr[left+1:left+2+j]) From 51e5f140e38cd877cdab09e1ab7e8972b903253a Mon Sep 17 00:00:00 2001 From: Konstantin Date: Thu, 16 May 2019 23:41:12 +0300 Subject: [PATCH 146/159] test --- final_task/.idea/workspace.xml | 15 +++++++-------- final_task/pycalc.py | 12 ++++++------ final_task/tmp.py | 17 ----------------- 3 files changed, 13 insertions(+), 31 deletions(-) delete mode 100644 final_task/tmp.py diff --git a/final_task/.idea/workspace.xml b/final_task/.idea/workspace.xml index e3c3e6a7..e35f5ee3 100644 --- a/final_task/.idea/workspace.xml +++ b/final_task/.idea/workspace.xml @@ -5,7 +5,6 @@ - - + - + @@ -264,8 +263,8 @@ - - + + diff --git a/final_task/pycalc.py b/final_task/pycalc.py index 25d94451..3eded5a2 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -118,7 +118,7 @@ def parse(xprstr): break j = j + 1 xprstr = xprstr[:j]+')'+xprstr[j:] # добавляем правую ) - + # добавление скобок для возведение в степень типа 2^3^4 right = len(xprstr) for i in range(xprstr.count('^')): @@ -134,9 +134,9 @@ def parse(xprstr): lt = right+2 # поиск от ^ вправо если () или до знака brkt = 0 - # print('поиск ^ вправо', xprstr[ss:]) - for j, data in enumerate(xprstr[ss:]): - if data == '(': + # print('поиск ^ вправо', xprstr[lt:]) + for j, data in enumerate(xprstr[lt:]): + if data == '(': brkt = brkt + 1 if data == ')': brkt = brkt - 1 @@ -144,7 +144,7 @@ def parse(xprstr): break # print(j, data, brkt) xprstr = xprstr[:lt + 1 + j]+')'+xprstr[lt + 1 + j:] - # print(xprstr, '!!!!!!!',ss, right) + # print(xprstr, '!!!!!!!',lt, right) else: # НЕ надо скобки right = left @@ -319,7 +319,7 @@ def main(): parsecmd() # парсинг аргументов командной строки xpr выражение и module модуль функции addfunc(module) # попытка добавления внешней функции если указана -m module calc(xpr) # калькулятор. вычисление выражения в строке xpr - #except OEError: + # except OEError: except Exception as error: print('ERROR:', error) return diff --git a/final_task/tmp.py b/final_task/tmp.py deleted file mode 100644 index 9a93b3d9..00000000 --- a/final_task/tmp.py +++ /dev/null @@ -1,17 +0,0 @@ -# сделать поиск от ^ вправо если () или до знака -split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') -xprstr = 'e^(-e)^(-e+(2-3))' -print(xprstr) -left = xprstr.rindex('^') -skob = 0 -print(xprstr[left:]) -for j, data in enumerate(xprstr[left+1:]): - if data == '(': - skob = skob + 1 - if data == ')': - skob = skob - 1 - if data in split and data != '(' and skob == 0: - break - print(j, data, skob) - -print('===', xprstr[left+1:left+2+j]) From dab525fb89671f8e2fe3336bcc0d26a03160e6fa Mon Sep 17 00:00:00 2001 From: Konstantin Date: Sat, 18 May 2019 01:41:53 +0300 Subject: [PATCH 147/159] add unittest --- final_task/tests.py | 179 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 179 insertions(+) create mode 100644 final_task/tests.py diff --git a/final_task/tests.py b/final_task/tests.py new file mode 100644 index 00000000..5ff554d4 --- /dev/null +++ b/final_task/tests.py @@ -0,0 +1,179 @@ +import unittest +import math +import pycalc + + +class TestMyCaseCalculator(unittest.TestCase): + + def test_default_arithmetic(self): + self.assertEqual(pycalc.calc('10+10'), 10+10) + self.assertEqual(pycalc.calc('2*4'), 2*4) + self.assertEqual(pycalc.calc('5-6'), 5-6) + self.assertEqual(pycalc.calc('10/10'), 10/10) + self.assertEqual(pycalc.calc('10^10'), 10**10) + self.assertEqual(pycalc.calc('21//2'), 21//2) + self.assertEqual(pycalc.calc('2%2'), 2 % 2) + + def test_with_floating_numbers(self): + self.assertEqual(pycalc.calc('0.4 + 1.5'), 0.4 + 1.5) + self.assertEqual(pycalc.calc('.4 + 1.5'), .4 + 1.5) + self.assertEqual(pycalc.calc('.4^-(1.5+0.5)'), eval('.4**-(1.5+0.5)')) + + def test_number_theoretic_and_representation_functions(self): + self.assertEqual(pycalc.calc('ceil(2.5)'), math.ceil(2.5)) + self.assertEqual(pycalc.calc('copysign(1.0, -1.0)'), math.copysign(1.0, -1.0)) + self.assertEqual(pycalc.calc('fabs(-5)'), math.fabs(-5)) + self.assertEqual(pycalc.calc('factorial(2)'), math.factorial(2)) + self.assertEqual(pycalc.calc('floor(5.5)'), math.floor(5.5)) + self.assertEqual(pycalc.calc('fmod(5,5)'), math.fmod(5, 5)) + self.assertEqual(pycalc.calc('frexp(5)'), math.frexp(5)) + self.assertEqual(pycalc.calc('ldexp(3,10)'), math.ldexp(3, 10)) + self.assertEqual(pycalc.calc('fsum([.1, .1, .1])'), math.fsum([.1, .1, .1])) + self.assertEqual(pycalc.calc('fsum({1:2, 5:8, 6:120})'), math.fsum({1: 2, 5: 8, 6: 120})) + self.assertEqual(pycalc.calc('gcd(5, 10)'), math.gcd(5, 10)) + self.assertEqual(pycalc.calc('isclose(1, 2, rel_tol=0.05, abs_tol=0.0)'), + math.isclose(1, 2, rel_tol=0.05, abs_tol=0.0)) + self.assertEqual(pycalc.calc('isclose(1, 2)'), + math.isclose(1, 2)) + self.assertEqual(pycalc.calc('isclose(1, 2, rel_tol=0.05)'), + math.isclose(1, 2, rel_tol=0.05)) + self.assertEqual(pycalc.calc('isfinite(3)'), math.isfinite(3)) + self.assertEqual(pycalc.calc('isinf(3)'), math.isinf(3)) + self.assertEqual(pycalc.calc('isnan(3)'), math.isnan(3)) + self.assertEqual(pycalc.calc('modf(-3)'), math.modf(-3)) + self.assertEqual(pycalc.calc('trunc(3.4)'), math.trunc(3.4)) + self.assertEqual(pycalc.calc('exp(3)'), math.exp(3)) + self.assertEqual(pycalc.calc('expm1(3)'), math.expm1(3)) + self.assertEqual(pycalc.calc('log(10,2)'), math.log(10, 2)) + self.assertEqual(pycalc.calc('log1p(10)'), math.log1p(10)) + self.assertEqual(pycalc.calc('log10(10)'), math.log10(10)) + self.assertEqual(pycalc.calc('log2(10)'), math.log2(10)) + self.assertEqual(pycalc.calc('pow(2,3)'), math.pow(2, 3)) + self.assertEqual(pycalc.calc('sqrt(25)'), math.sqrt(25)) + self.assertEqual(pycalc.calc('erf(3)'), math.erf(3)) + self.assertEqual(pycalc.calc('erfc(3)'), math.erfc(3)) + self.assertEqual(pycalc.calc('gamma(3)'), math.gamma(3)) + self.assertEqual(pycalc.calc('lgamma(3)'), math.lgamma(3)) + + def test_module_math_trigonometry(self): + self.assertEqual(pycalc.calc('sin(90)'), math.sin(90)) + self.assertEqual(pycalc.calc('cos(90)'), math.cos(90)) + self.assertEqual(pycalc.calc('tan(90)'), math.tan(90)) + self.assertEqual(pycalc.calc('asin(1)'), math.asin(1)) + self.assertEqual(pycalc.calc('acos(0)'), math.acos(0)) + self.assertEqual(pycalc.calc('atan(1)'), math.atan(1)) + self.assertEqual(pycalc.calc('hypot(3,4)'), math.hypot(3, 4)) + self.assertEqual(pycalc.calc('degrees(3.14)'), math.degrees(3.14)) + self.assertEqual(pycalc.calc('radians(90)'), math.radians(90)) + self.assertEqual(pycalc.calc('sinh(1)'), math.sinh(1)) + self.assertEqual(pycalc.calc('cosh(1)'), math.cosh(1)) + self.assertEqual(pycalc.calc('tanh(1)'), math.tanh(1)) + self.assertEqual(pycalc.calc('asinh(1)'), math.asinh(1)) + self.assertEqual(pycalc.calc('acosh(1)'), math.acosh(1)) + self.assertEqual(pycalc.calc('atanh(0)'), math.atanh(0)) + self.assertEqual(pycalc.calc('pi'), math.pi) + self.assertEqual(pycalc.calc('e'), math.e) + self.assertEqual(pycalc.calc('tau'), math.tau) + + def test_round_brackets(self): + self.assertEqual(pycalc.calc('(2+2)*2'), (2+2)*2) + self.assertEqual(pycalc.calc('(2+2)*2+(2+2)'), (2+2)*2+(2+2)) + self.assertEqual(pycalc.calc('2+(2+(2+3)+3)+2'), 2+(2+(2+3)+3)+2) + self.assertEqual(pycalc.calc('2+(2+3)*3+2'), 2+(2+3)*3+2) + self.assertEqual(pycalc.calc('((2+2)*3)+2'), ((2+2)*3)+2) + + +class TestEpamCaseCalculator(unittest.TestCase): + + def test_unary_operators(self): + self.assertEqual(pycalc.calc("-13"), -13) + self.assertEqual(pycalc.calc("6-(-13)"), 6-(-13)) + self.assertEqual(pycalc.calc("1---1"), 1---1) + self.assertEqual(pycalc.calc("-+---+-1"), -+---+-1) + + def test_operation_priority(self): + self.assertEqual(pycalc.calc("1+2*2"), 1+2*2) + self.assertEqual(pycalc.calc("1+(2+3*2)*3"), 1+(2+3*2)*3) + self.assertEqual(pycalc.calc("10*(2+1)"), 10*(2+1)) + self.assertEqual(pycalc.calc("10^(2+1)"), 10**(2+1)) + self.assertEqual(pycalc.calc("100/3^2"), 100/3**2) + self.assertEqual(pycalc.calc("100/3%2^2"), 100/3 % 2**2) + + def test_functions_and_constants(self): + self.assertEqual(pycalc.calc("pi+e"), math.pi+math.e) + self.assertEqual(pycalc.calc("log(e)"), math.log(math.e)) + self.assertEqual(pycalc.calc("sin(pi/2)"), math.sin(math.pi/2)) + self.assertEqual(pycalc.calc("log10(100)"), math.log10(100)) + self.assertEqual(pycalc.calc("sin(pi/2)*111*6"), math.sin(math.pi/2)*111*6) + self.assertEqual(pycalc.calc("2*sin(pi/2)"), 2*math.sin(math.pi/2)) + self.assertEqual(pycalc.calc("pow(2, 3)"), math.pow(2, 3)) + self.assertEqual(pycalc.calc("abs(-5)"), abs(-5)) + self.assertEqual(pycalc.calc("round(123.4567890)"), round(123.4567890)) + self.assertEqual(pycalc.calc("round(123.4567890,2)"), round(123.4567890, 2)) + + def test_associative(self): + self.assertEqual(pycalc.calc("102%12%7"), 102 % 12 % 7) + self.assertEqual(pycalc.calc("100/4/3"), 100/4/3) + self.assertEqual(pycalc.calc("2^3^4"), 2**3**4) + + def test_comparison_operators(self): + self.assertEqual(pycalc.calc("1+2*3==1+2*3"), 1+2*3 == 1+2*3) + self.assertAlmostEqual(pycalc.calc("e^5>=e^5+1"), math.e**5 >= math.e**5+1) + self.assertAlmostEqual(pycalc.calc("1+2*4/3+1!=1+2*4/3+2"), 1+2*4/3+1 != 1+2*4/3+2) + self.assertAlmostEqual(pycalc.calc("True+1"), True + 1) + + def test_common_tests(self): + self.assertEqual(pycalc.calc("(100)"), eval("(100)")) + self.assertEqual(pycalc.calc("666"), 666) + self.assertEqual(pycalc.calc("-.1"), -.1) + self.assertEqual(pycalc.calc("1/3"), 1/3) + self.assertEqual(pycalc.calc("1.0/3.0"), 1.0/3.0) + self.assertEqual(pycalc.calc(".1 * 2.0^56.0"), .1 * 2.0**56.0) + self.assertEqual(pycalc.calc("e^34"), math.e**34) + self.assertEqual(pycalc.calc("(2.0^(pi/pi+e/e+2.0^0.0))"), + (2.0**(math.pi/math.pi+math.e/math.e+2.0**0.0))) + self.assertEqual(pycalc.calc("(2.0^(pi/pi+e/e+2.0^0.0))^(1.0/3.0)"), + (2.0**(math.pi/math.pi+math.e/math.e+2.0**0.0))**(1.0/3.0)) + self.assertEqual(pycalc.calc("sin(pi/2^1) + log(1*4+2^2+1, 3^2)"), + math.sin(math.pi/2**1) + math.log(1*4+2**2+1, 3**2)) + self.assertEqual(pycalc.calc("10*e^0*log10(.4 -5/ -0.1-10) - -abs(-53/10) + -5"), + 10*math.e**0*math.log10(.4 - 5 / -0.1-10) - -abs(-53/10) + -5) + expression = "sin(-cos(-sin(3.0)-cos(-sin(-3.0*5.0)-sin(cos(log10(43.0))))+" \ + "cos(sin(sin(34.0-2.0^2.0))))--cos(1.0)--cos(0.0)^3.0)" + self.assertEqual(pycalc.calc(expression), + math.sin(-math.cos(-math.sin(3.0)-math.cos(-math.sin(-3.0*5.0) - + math.sin(math.cos(math.log10(43.0)))) + + math.cos(math.sin(math.sin(34.0-2.0**2.0))))--math.cos(1.0) - + -math.cos(0.0)**3.0)) + self.assertEqual(pycalc.calc("2.0^(2.0^2.0*2.0^2.0)"), 2.0**(2.0**2.0*2.0**2.0)) + self.assertEqual(pycalc.calc("sin(e^log(e^e^sin(23.0),45.0) + cos(3.0+log10(e^-e)))"), + math.sin(math.e**math.log(math.e**math.e**math.sin(23.0), 45.0) + + math.cos(3.0+math.log10(math.e**-math.e)))) + + def test_Error_cases(self): + self.assertRaises(ValueError, pycalc.calc, "") + self.assertRaises(ValueError, pycalc.calc, "+") + self.assertRaises(ValueError, pycalc.calc, "1-") + self.assertRaises(ValueError, pycalc.calc, "1 2") + self.assertRaises(ValueError, pycalc.calc, "==7") + self.assertRaises(ValueError, pycalc.calc, "1 + 2(3 * 4))") + self.assertRaises(ValueError, pycalc.calc, "((1+2)") + self.assertRaises(ValueError, pycalc.calc, "1 + 1 2 3 4 5 6 ") + self.assertRaises(ValueError, pycalc.calc, "log100(100)") + self.assertRaises(ValueError, pycalc.calc, "------") + self.assertRaises(ValueError, pycalc.calc, "5 > = 6") + self.assertRaises(ValueError, pycalc.calc, "5 / / 6") + self.assertRaises(ValueError, pycalc.calc, "6 < = 6") + self.assertRaises(ValueError, pycalc.calc, "6 * * 6") + self.assertRaises(ValueError, pycalc.calc, "(((((") + self.assertRaises(ValueError, pycalc.calc, "abs") + self.assertRaises(ValueError, pycalc.calc, "abs+1") + self.assertRaises(ValueError, pycalc.calc, "isclose(1)") + self.assertRaises(ValueError, pycalc.calc, "cos(2,1)") + self.assertRaises(ValueError, pycalc.calc, "2**2") + self.assertRaises(ValueError, pycalc.calc, "pow(2, 3, 4)") + self.assertRaises(ValueError, pycalc.calc, "fsum[1,,2,3]") + + +if __name__ == '__main__': + unittest.main() From 9effdbf70f74e2ec0115cb741ce8601757eb7a2e Mon Sep 17 00:00:00 2001 From: Konstantin Date: Sat, 18 May 2019 01:46:24 +0300 Subject: [PATCH 148/159] add unittest --- final_task/test.py | 11 +++ final_task/tests.py | 179 -------------------------------------------- 2 files changed, 11 insertions(+), 179 deletions(-) create mode 100644 final_task/test.py delete mode 100644 final_task/tests.py diff --git a/final_task/test.py b/final_task/test.py new file mode 100644 index 00000000..fdbcebbe --- /dev/null +++ b/final_task/test.py @@ -0,0 +1,11 @@ +import unittest +import math +from math import * +import pycalc + + +class TestPycalc(unittest.TestCase): + + def test(self): + self.assertEqual(pycalc.calc('2^3^4'), 2**3**4) + self.assertEqual(pycalc.calc('sin(90)'), sin(90)) diff --git a/final_task/tests.py b/final_task/tests.py deleted file mode 100644 index 5ff554d4..00000000 --- a/final_task/tests.py +++ /dev/null @@ -1,179 +0,0 @@ -import unittest -import math -import pycalc - - -class TestMyCaseCalculator(unittest.TestCase): - - def test_default_arithmetic(self): - self.assertEqual(pycalc.calc('10+10'), 10+10) - self.assertEqual(pycalc.calc('2*4'), 2*4) - self.assertEqual(pycalc.calc('5-6'), 5-6) - self.assertEqual(pycalc.calc('10/10'), 10/10) - self.assertEqual(pycalc.calc('10^10'), 10**10) - self.assertEqual(pycalc.calc('21//2'), 21//2) - self.assertEqual(pycalc.calc('2%2'), 2 % 2) - - def test_with_floating_numbers(self): - self.assertEqual(pycalc.calc('0.4 + 1.5'), 0.4 + 1.5) - self.assertEqual(pycalc.calc('.4 + 1.5'), .4 + 1.5) - self.assertEqual(pycalc.calc('.4^-(1.5+0.5)'), eval('.4**-(1.5+0.5)')) - - def test_number_theoretic_and_representation_functions(self): - self.assertEqual(pycalc.calc('ceil(2.5)'), math.ceil(2.5)) - self.assertEqual(pycalc.calc('copysign(1.0, -1.0)'), math.copysign(1.0, -1.0)) - self.assertEqual(pycalc.calc('fabs(-5)'), math.fabs(-5)) - self.assertEqual(pycalc.calc('factorial(2)'), math.factorial(2)) - self.assertEqual(pycalc.calc('floor(5.5)'), math.floor(5.5)) - self.assertEqual(pycalc.calc('fmod(5,5)'), math.fmod(5, 5)) - self.assertEqual(pycalc.calc('frexp(5)'), math.frexp(5)) - self.assertEqual(pycalc.calc('ldexp(3,10)'), math.ldexp(3, 10)) - self.assertEqual(pycalc.calc('fsum([.1, .1, .1])'), math.fsum([.1, .1, .1])) - self.assertEqual(pycalc.calc('fsum({1:2, 5:8, 6:120})'), math.fsum({1: 2, 5: 8, 6: 120})) - self.assertEqual(pycalc.calc('gcd(5, 10)'), math.gcd(5, 10)) - self.assertEqual(pycalc.calc('isclose(1, 2, rel_tol=0.05, abs_tol=0.0)'), - math.isclose(1, 2, rel_tol=0.05, abs_tol=0.0)) - self.assertEqual(pycalc.calc('isclose(1, 2)'), - math.isclose(1, 2)) - self.assertEqual(pycalc.calc('isclose(1, 2, rel_tol=0.05)'), - math.isclose(1, 2, rel_tol=0.05)) - self.assertEqual(pycalc.calc('isfinite(3)'), math.isfinite(3)) - self.assertEqual(pycalc.calc('isinf(3)'), math.isinf(3)) - self.assertEqual(pycalc.calc('isnan(3)'), math.isnan(3)) - self.assertEqual(pycalc.calc('modf(-3)'), math.modf(-3)) - self.assertEqual(pycalc.calc('trunc(3.4)'), math.trunc(3.4)) - self.assertEqual(pycalc.calc('exp(3)'), math.exp(3)) - self.assertEqual(pycalc.calc('expm1(3)'), math.expm1(3)) - self.assertEqual(pycalc.calc('log(10,2)'), math.log(10, 2)) - self.assertEqual(pycalc.calc('log1p(10)'), math.log1p(10)) - self.assertEqual(pycalc.calc('log10(10)'), math.log10(10)) - self.assertEqual(pycalc.calc('log2(10)'), math.log2(10)) - self.assertEqual(pycalc.calc('pow(2,3)'), math.pow(2, 3)) - self.assertEqual(pycalc.calc('sqrt(25)'), math.sqrt(25)) - self.assertEqual(pycalc.calc('erf(3)'), math.erf(3)) - self.assertEqual(pycalc.calc('erfc(3)'), math.erfc(3)) - self.assertEqual(pycalc.calc('gamma(3)'), math.gamma(3)) - self.assertEqual(pycalc.calc('lgamma(3)'), math.lgamma(3)) - - def test_module_math_trigonometry(self): - self.assertEqual(pycalc.calc('sin(90)'), math.sin(90)) - self.assertEqual(pycalc.calc('cos(90)'), math.cos(90)) - self.assertEqual(pycalc.calc('tan(90)'), math.tan(90)) - self.assertEqual(pycalc.calc('asin(1)'), math.asin(1)) - self.assertEqual(pycalc.calc('acos(0)'), math.acos(0)) - self.assertEqual(pycalc.calc('atan(1)'), math.atan(1)) - self.assertEqual(pycalc.calc('hypot(3,4)'), math.hypot(3, 4)) - self.assertEqual(pycalc.calc('degrees(3.14)'), math.degrees(3.14)) - self.assertEqual(pycalc.calc('radians(90)'), math.radians(90)) - self.assertEqual(pycalc.calc('sinh(1)'), math.sinh(1)) - self.assertEqual(pycalc.calc('cosh(1)'), math.cosh(1)) - self.assertEqual(pycalc.calc('tanh(1)'), math.tanh(1)) - self.assertEqual(pycalc.calc('asinh(1)'), math.asinh(1)) - self.assertEqual(pycalc.calc('acosh(1)'), math.acosh(1)) - self.assertEqual(pycalc.calc('atanh(0)'), math.atanh(0)) - self.assertEqual(pycalc.calc('pi'), math.pi) - self.assertEqual(pycalc.calc('e'), math.e) - self.assertEqual(pycalc.calc('tau'), math.tau) - - def test_round_brackets(self): - self.assertEqual(pycalc.calc('(2+2)*2'), (2+2)*2) - self.assertEqual(pycalc.calc('(2+2)*2+(2+2)'), (2+2)*2+(2+2)) - self.assertEqual(pycalc.calc('2+(2+(2+3)+3)+2'), 2+(2+(2+3)+3)+2) - self.assertEqual(pycalc.calc('2+(2+3)*3+2'), 2+(2+3)*3+2) - self.assertEqual(pycalc.calc('((2+2)*3)+2'), ((2+2)*3)+2) - - -class TestEpamCaseCalculator(unittest.TestCase): - - def test_unary_operators(self): - self.assertEqual(pycalc.calc("-13"), -13) - self.assertEqual(pycalc.calc("6-(-13)"), 6-(-13)) - self.assertEqual(pycalc.calc("1---1"), 1---1) - self.assertEqual(pycalc.calc("-+---+-1"), -+---+-1) - - def test_operation_priority(self): - self.assertEqual(pycalc.calc("1+2*2"), 1+2*2) - self.assertEqual(pycalc.calc("1+(2+3*2)*3"), 1+(2+3*2)*3) - self.assertEqual(pycalc.calc("10*(2+1)"), 10*(2+1)) - self.assertEqual(pycalc.calc("10^(2+1)"), 10**(2+1)) - self.assertEqual(pycalc.calc("100/3^2"), 100/3**2) - self.assertEqual(pycalc.calc("100/3%2^2"), 100/3 % 2**2) - - def test_functions_and_constants(self): - self.assertEqual(pycalc.calc("pi+e"), math.pi+math.e) - self.assertEqual(pycalc.calc("log(e)"), math.log(math.e)) - self.assertEqual(pycalc.calc("sin(pi/2)"), math.sin(math.pi/2)) - self.assertEqual(pycalc.calc("log10(100)"), math.log10(100)) - self.assertEqual(pycalc.calc("sin(pi/2)*111*6"), math.sin(math.pi/2)*111*6) - self.assertEqual(pycalc.calc("2*sin(pi/2)"), 2*math.sin(math.pi/2)) - self.assertEqual(pycalc.calc("pow(2, 3)"), math.pow(2, 3)) - self.assertEqual(pycalc.calc("abs(-5)"), abs(-5)) - self.assertEqual(pycalc.calc("round(123.4567890)"), round(123.4567890)) - self.assertEqual(pycalc.calc("round(123.4567890,2)"), round(123.4567890, 2)) - - def test_associative(self): - self.assertEqual(pycalc.calc("102%12%7"), 102 % 12 % 7) - self.assertEqual(pycalc.calc("100/4/3"), 100/4/3) - self.assertEqual(pycalc.calc("2^3^4"), 2**3**4) - - def test_comparison_operators(self): - self.assertEqual(pycalc.calc("1+2*3==1+2*3"), 1+2*3 == 1+2*3) - self.assertAlmostEqual(pycalc.calc("e^5>=e^5+1"), math.e**5 >= math.e**5+1) - self.assertAlmostEqual(pycalc.calc("1+2*4/3+1!=1+2*4/3+2"), 1+2*4/3+1 != 1+2*4/3+2) - self.assertAlmostEqual(pycalc.calc("True+1"), True + 1) - - def test_common_tests(self): - self.assertEqual(pycalc.calc("(100)"), eval("(100)")) - self.assertEqual(pycalc.calc("666"), 666) - self.assertEqual(pycalc.calc("-.1"), -.1) - self.assertEqual(pycalc.calc("1/3"), 1/3) - self.assertEqual(pycalc.calc("1.0/3.0"), 1.0/3.0) - self.assertEqual(pycalc.calc(".1 * 2.0^56.0"), .1 * 2.0**56.0) - self.assertEqual(pycalc.calc("e^34"), math.e**34) - self.assertEqual(pycalc.calc("(2.0^(pi/pi+e/e+2.0^0.0))"), - (2.0**(math.pi/math.pi+math.e/math.e+2.0**0.0))) - self.assertEqual(pycalc.calc("(2.0^(pi/pi+e/e+2.0^0.0))^(1.0/3.0)"), - (2.0**(math.pi/math.pi+math.e/math.e+2.0**0.0))**(1.0/3.0)) - self.assertEqual(pycalc.calc("sin(pi/2^1) + log(1*4+2^2+1, 3^2)"), - math.sin(math.pi/2**1) + math.log(1*4+2**2+1, 3**2)) - self.assertEqual(pycalc.calc("10*e^0*log10(.4 -5/ -0.1-10) - -abs(-53/10) + -5"), - 10*math.e**0*math.log10(.4 - 5 / -0.1-10) - -abs(-53/10) + -5) - expression = "sin(-cos(-sin(3.0)-cos(-sin(-3.0*5.0)-sin(cos(log10(43.0))))+" \ - "cos(sin(sin(34.0-2.0^2.0))))--cos(1.0)--cos(0.0)^3.0)" - self.assertEqual(pycalc.calc(expression), - math.sin(-math.cos(-math.sin(3.0)-math.cos(-math.sin(-3.0*5.0) - - math.sin(math.cos(math.log10(43.0)))) - + math.cos(math.sin(math.sin(34.0-2.0**2.0))))--math.cos(1.0) - - -math.cos(0.0)**3.0)) - self.assertEqual(pycalc.calc("2.0^(2.0^2.0*2.0^2.0)"), 2.0**(2.0**2.0*2.0**2.0)) - self.assertEqual(pycalc.calc("sin(e^log(e^e^sin(23.0),45.0) + cos(3.0+log10(e^-e)))"), - math.sin(math.e**math.log(math.e**math.e**math.sin(23.0), 45.0) + - math.cos(3.0+math.log10(math.e**-math.e)))) - - def test_Error_cases(self): - self.assertRaises(ValueError, pycalc.calc, "") - self.assertRaises(ValueError, pycalc.calc, "+") - self.assertRaises(ValueError, pycalc.calc, "1-") - self.assertRaises(ValueError, pycalc.calc, "1 2") - self.assertRaises(ValueError, pycalc.calc, "==7") - self.assertRaises(ValueError, pycalc.calc, "1 + 2(3 * 4))") - self.assertRaises(ValueError, pycalc.calc, "((1+2)") - self.assertRaises(ValueError, pycalc.calc, "1 + 1 2 3 4 5 6 ") - self.assertRaises(ValueError, pycalc.calc, "log100(100)") - self.assertRaises(ValueError, pycalc.calc, "------") - self.assertRaises(ValueError, pycalc.calc, "5 > = 6") - self.assertRaises(ValueError, pycalc.calc, "5 / / 6") - self.assertRaises(ValueError, pycalc.calc, "6 < = 6") - self.assertRaises(ValueError, pycalc.calc, "6 * * 6") - self.assertRaises(ValueError, pycalc.calc, "(((((") - self.assertRaises(ValueError, pycalc.calc, "abs") - self.assertRaises(ValueError, pycalc.calc, "abs+1") - self.assertRaises(ValueError, pycalc.calc, "isclose(1)") - self.assertRaises(ValueError, pycalc.calc, "cos(2,1)") - self.assertRaises(ValueError, pycalc.calc, "2**2") - self.assertRaises(ValueError, pycalc.calc, "pow(2, 3, 4)") - self.assertRaises(ValueError, pycalc.calc, "fsum[1,,2,3]") - - -if __name__ == '__main__': - unittest.main() From 45da54d7ae99e9dc0523a0a2300ca84931c001a1 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Mon, 20 May 2019 12:27:00 +0300 Subject: [PATCH 149/159] unittest epam testcases --- .../inspectionProfiles/Project_Default.xml | 2 + final_task/.idea/workspace.xml | 66 +++++++++---------- final_task/pycalc.py | 10 +-- final_task/test.py | 66 ++++++++++++++++++- 4 files changed, 100 insertions(+), 44 deletions(-) diff --git a/final_task/.idea/inspectionProfiles/Project_Default.xml b/final_task/.idea/inspectionProfiles/Project_Default.xml index d1c81f2c..01c4f104 100644 --- a/final_task/.idea/inspectionProfiles/Project_Default.xml +++ b/final_task/.idea/inspectionProfiles/Project_Default.xml @@ -73,6 +73,8 @@ diff --git a/final_task/.idea/workspace.xml b/final_task/.idea/workspace.xml index 1275cac2..16b07d91 100644 --- a/final_task/.idea/workspace.xml +++ b/final_task/.idea/workspace.xml @@ -5,11 +5,9 @@ - - - + - + - + - + - - + + - - + + + + + @@ -66,11 +67,10 @@ print except TypeError try - enu ss skob - ss + operator pycalc.main @@ -98,12 +98,14 @@ + @@ -112,6 +114,7 @@ + @@ -123,7 +126,6 @@ + @@ -206,7 +193,6 @@ - @@ -236,13 +222,6 @@ - - - - - - - @@ -255,22 +234,29 @@ - + - - + + - + - + - - + + + + + + + + + - + diff --git a/final_task/pycalc.py b/final_task/pycalc.py index e2dfbd5c..a6741975 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -1,4 +1,3 @@ -# 21 may stable import argparse import math from math import * @@ -8,7 +7,11 @@ import importlib.util split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') -funclist = dir(math)+['abs', 'round', 'sum'] +# Good style +#funclst = [attr in dir(math) if callable(getattr(math, attr))] +# fundic = dict([(attr, getattr(math, attr)) for attr in dir(math) if callable(getattr(math, attr))]) +# callable false pi, e, tau +funclst = dir(math) + ['abs', 'round', 'sum'] funcdic = math.__dict__ operdic = { '+': add, @@ -30,23 +33,21 @@ } funcdic.update(operdic) oper = ['^', '//', '/', '*', '%', '-', '+', '==', '<=', '>=', '<', '>', '!='] -xpr = '' def parsecmd(): - """ парсинг командной строки """ - global xpr, module + """парсинг командной строки""" ap = argparse.ArgumentParser(description='Pure-python command-line calculator.') ap.add_argument('EXPRESSION', type=str, help='expression string to evalute') ap.add_argument('-m', '--MODULE', type=str, help='use modules MODULE [MODULE...] additional modules to use') args = ap.parse_args() - xpr = args.EXPRESSION + xprstr = args.EXPRESSION module = args.MODULE - return + return xprstr, module def addfunc(module): - """ добавление новой функцию из модуля (module)""" + """добавление новой функцию из модуля (module)""" if module is not None: # если введено имя модуля try: spec = importlib.util.find_spec(module) @@ -57,12 +58,12 @@ def addfunc(module): else: newfunc = importlib.import_module(module) # импортирование нового модуля funcdic[module] = newfunc.main - funclist.append(module) + funclst.append(module) return def unaryexp(xprstr): - """ добавление в строку выражения скобок для возведение в степень типа pi^-pi >>> pi^(-pi) """ + """добавление в строку выражения скобок для возведение в степень типа pi^-pi >>> pi^(-pi)""" right = len(xprstr) for i in range(xprstr.count('^')): right = xprstr.rindex('^', 0, right) # поиск справа первого ^ @@ -71,23 +72,22 @@ def unaryexp(xprstr): right = right + 3 # поиск строки справа от ^ brkt = 0 - for j, data in enumerate(xprstr[right:]): - if data == '(': + j = 0 + while j < len(xprstr[right:]) or (brkt == 0 and xprstr[j] == ')'): + if xprstr[j] == '(': brkt = brkt + 1 - if data == ')': + if xprstr[j] == ')': brkt = brkt - 1 - if brkt == 0 and data in oper: + if brkt == 0 and xprstr[j] in oper: j = j - 1 break - if brkt == 0 and data == ')': - break + j = j + 1 xprstr = xprstr[:right + 1 + j] + ')' + xprstr[right + 1 + j:] - # print('EXP ^- ', xprstr) return(xprstr) def brackets4exp(xprstr): - """ добавление в строку выражения скобок для возведение в степень типа 2^3^4 >>> 2^(3^4) """ + """добавление в строку выражения скобок для возведение в степень типа 2^3^4 >>> 2^(3^4)""" right = len(xprstr) for i in range(xprstr.count('^')): right = xprstr.rindex('^', 0, right) # находим позицию самого правого знака ^ @@ -118,6 +118,7 @@ def brackets4exp(xprstr): def preparse(xprstr): + """очистка строки выражения от мусора, повторных знаков и пробелов""" xprset = set(xprstr) operset = set(oper) operset.add(' ') @@ -155,7 +156,7 @@ def preparse(xprstr): def afterparse(xprlst): - # for i, data in enumerate(xprlst): # поииск операторов составных типа <= >= == != содержащихся в списке oper + """поиск операторов типа <= >= == !=, замена унарнонго - на -1*""" i = 0 while i < len(xprlst): if i < len(xprlst)-1: @@ -168,11 +169,10 @@ def afterparse(xprlst): if str(xprlst[i]) + str(xprlst[i+1]) in oper: # '>' + '=' xprlst[i+1] = str(xprlst[i]) + str(xprlst[i+1]) # '>=' xprlst.pop(i) - # унарный минус (-( +-( +-5 +-sin # print('i=', i, '[i]=', xprlst[i]) if xprlst[i] == '-' and xprlst[i-1] in oper+['('] and (type(xprlst[i + 1]) == float - or xprlst[i + 1] in funclist + or xprlst[i + 1] in funclst or xprlst[i + 1] == '-' or xprlst[i + 1] == '('): xprlst[i] = -1 @@ -186,7 +186,7 @@ def afterparse(xprlst): def parse(xprstr): - """ парсинг строки математического выражения. на выходе список в инфиксной нотации""" + """парсинг строки математического выражения. на выходе список в инфиксной нотации""" word = '' xprlst = [] xprstr = preparse(xprstr) # подготовка к парсингу @@ -196,7 +196,7 @@ def parse(xprstr): # разбор строки for i, sym in enumerate(xprstr + ' '): # добавлен дополнительный пробел if sym in split or i == len(xprstr): - if word in funclist: # если функция + if word in funclst: # если функция xprlst.append(word) elif word.replace('.', '').isdigit() and word.count('.') < 2: # если цифра xprlst.append(float(word)) @@ -208,14 +208,13 @@ def parse(xprstr): else: word = word + sym xprlst.pop() # удаляется добавленный пробел - # print('PARSE', *xprlst, sep=' ') return xprlst def prior(op1, op2): - """ сравнивает приоритеты математических опрераторов и функций op1 <= op2, возвращает bool """ - operhiest = ['^'] + funclist # 4 + """сравнивает приоритеты математических опрераторов и функций op1 <= op2, возвращает bool""" + operhiest = ['^'] + funclst # 4 operhi = ['*'] # 3 opermid = ['/', '%', '//'] # 2 operlow = ['+', '-'] # 1 @@ -230,8 +229,8 @@ def prior(op1, op2): def postfix(xprlst): - """ преобразование инфиксной нотации в постфиксную - на входе список элементов выражения инфиксной нотации, на выходе список элементов постфиксной нотации """ + """преобразование инфиксной нотации в постфиксную + на входе список элементов выражения инфиксной нотации, на выходе список элементов постфиксной нотации""" output = [] stack = [] for i in xprlst: @@ -239,7 +238,7 @@ def postfix(xprlst): output.append(i) elif i == ',': # если , то положить на выход if stack != []: - while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): + while stack != [] and stack[-1] in oper+funclst and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом output.append(stack.pop()) # переложить оператор из стека на выход output.append(i) @@ -249,11 +248,11 @@ def postfix(xprlst): elif stack[-1] == '(': # если стек содержит ( положить в стек ( stack.append(i) else: - while stack != [] and stack[-1] in oper+funclist and prior(i, stack[-1]): + while stack != [] and stack[-1] in oper+funclst and prior(i, stack[-1]): # пока наверху стека оператор с большим или равным приоритетом output.append(stack.pop()) # переложить оператор из стека на выход stack.append(i) # иначе положить оператор в стек - elif i in funclist or i == '(': # если функция или ( то помещаем в стек + elif i in funclst or i == '(': # если функция или ( то помещаем в стек stack.append(i) elif i == ')': while stack[-1] != '(': # пока верх стека не равен ( @@ -265,7 +264,7 @@ def postfix(xprlst): def operate(operator, args): - """ выполняет математическое действие или функцию (operator) со списком аргументов (args) """ + """выполняет математическое действие или функцию (operator) со списком аргументов (args)""" global stack # используется в функции evalpostfix # print('OPERATE', operator, 'ARGS', args, 'STACK', stack) try: @@ -292,12 +291,12 @@ def operate(operator, args): def evalpostfix(xprpstfx): - """ вычисление выражения в постфиксной нотации (список)""" + """вычисление выражения в постфиксной нотации (список)""" global stack # используется в функции operate для удаления аргументов из стека stack = [] args = [] for i in xprpstfx: - if i in funclist: # если функция типа sin, pow, sum, tau + if i in funclst: # если функция типа sin, pow, sum, tau if len(stack) == 0: args = 0 # функция без аргументов типа pi, e, tau if len(stack) == 1: @@ -330,9 +329,9 @@ def evalpostfix(xprpstfx): return stack[0] -def calc(xpr): - """ вычисление строки (xpr) математического выражения""" - xprlst = parse(xpr) # разбор строки вырыжения в список +def calc(xprstr): + """вычисление строки (xprstr) математического выражения""" + xprlst = parse(xprstr) # разбор строки вырыжения в список xprlst = afterparse(xprlst) xprlst = postfix(xprlst) # преобразование инфиксного списка в постфиксных список result = evalpostfix(xprlst) # вычисление постфиксного списка @@ -341,12 +340,10 @@ def calc(xpr): def main(): - global xpr, module try: - parsecmd() # парсинг аргументов командной строки xpr выражение и module модуль функции + xprstr, module = parsecmd() # парсинг аргументов командной строки xprstr выражение и module модуль функции addfunc(module) # попытка добавления внешней функции если указана -m module - calc(xpr) # калькулятор. вычисление выражения в строке xpr - # except OSError: + calc(xprstr) # калькулятор. вычисление выражения в строке xprstr except Exception as error: print('ERROR:', error) return From ba5346a3b8f87fad2dda53da969c1c557c23b885 Mon Sep 17 00:00:00 2001 From: Konstantin Date: Thu, 23 May 2019 00:34:09 +0300 Subject: [PATCH 159/159] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D1=81=D0=B8=D0=BD=D1=82=D0=B0=D0=BA=D1=81?= =?UTF-8?q?=D0=B8=D1=81,=20=D0=BA=D0=BE=D0=BC=D0=BC=D0=B5=D0=BD=D1=82?= =?UTF-8?q?=D0=B0=D1=80=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- final_task/.idea/workspace.xml | 9 +++------ final_task/pycalc.py | 2 +- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/final_task/.idea/workspace.xml b/final_task/.idea/workspace.xml index 6bd5f7a4..3f362a23 100644 --- a/final_task/.idea/workspace.xml +++ b/final_task/.idea/workspace.xml @@ -194,7 +194,7 @@ - + @@ -253,11 +253,8 @@ - - - - - + + diff --git a/final_task/pycalc.py b/final_task/pycalc.py index a6741975..b3df6ebb 100644 --- a/final_task/pycalc.py +++ b/final_task/pycalc.py @@ -8,7 +8,7 @@ split = ('^', '/', '*', '%', '-', '+', '=', '<', '>', '!', '(', ')', ',') # Good style -#funclst = [attr in dir(math) if callable(getattr(math, attr))] +# funclst = [attr in dir(math) if callable(getattr(math, attr))] # fundic = dict([(attr, getattr(math, attr)) for attr in dir(math) if callable(getattr(math, attr))]) # callable false pi, e, tau funclst = dir(math) + ['abs', 'round', 'sum']