def test_calc(self): ''' Check if calculator can performe 4 basic operations properly ''' self.assertEqual(calc.calc('+','1','1'), 2) self.assertEqual(calc.calc('-','11','111'), -100) self.assertEqual(calc.calc('*','11','11'), 121) self.assertEqual(calc.calc('/','33','3'), 11) self.assertRaises(ZeroDivisionError, calc.calc, '/','33','0')
def post(self): expr = str(self.request.get('expr')) session = str(self.request.get('session')) tokens = expr.split() if expr == 'h': self.response.write(helpcontent) elif len(tokens) == 2 and tokens[0] == 'save': saved_sessions = db.GqlQuery('SELECT * FROM Session WHERE ' + 'name = :1', tokens[1]) if saved_sessions.count() == 1: for s in saved_sessions: s.content = session s.put() else: s = Session(name=tokens[1], content=session) s.put() self.response.write('session saved') elif len(tokens) == 2 and tokens[0] == 'load': saved_sessions = db.GqlQuery('SELECT * FROM Session WHERE ' + 'name = :1', tokens[1]) if saved_sessions.count() == 0: self.response.write('session not found') else: self.response.write(saved_sessions[0].content) else: try: result = calc.calc(expr) self.response.write(result) except Exception, e: self.response.write(e)
def solve(equation, sym='x'): """ solving a*x + b = 0 for any form of a*x + b let x = 1, => a + b -> v1 let x = 0, => b -> v2 => b = v2, a = v1 - b = v1 - v2 x = -b/a = -v2/(v1-v2) """ expr = equation.replace('=', '-(') + ')' expr = expr.replace(' ', '') val1 = calc(expr.replace(sym, '1')) val2 = calc(expr.replace(sym, '0')) return 1.*(-val2)/(val1-val2)
def handleButton(self): number = self.input.text() try: number = int(number) x,y = calc.calc(number) self.sc.update_compute(number) except Exception: print(Exception) QtWidgets.QMessageBox.about(self, 'Error', 'Input can only be a number') pass
def parse(string): # should be large enough min_dis = 100000000 min_lst = None for e_list in para: for elm in para[e_list]: #get the minimal element or a threshold uses to fast the programs if elm[2] == None: print ("lacking a pinyin") return None temp = calc.calc(string, elm[2]) if temp < min_dis: min_dis = temp min_lst = [e_list ,elm] return min_lst
def get(self): page = Page.CALC parameters = getPageDict(page) parameters['User'] = "******" % (getCurrentUser(), getGroup()) try: c = calc() logging.debug(80*"*") logging.debug("loans =") logging.debug(c['loans']) logging.debug(80*"*") logging.debug("bids =") logging.debug(c['bids']) if 'loans' in c and 'bids' in c: parameters['loans'] = c['loans'] parameters['bids'] = c['bids'] for i in range(1, len(c['bids'])): b = Bid.get_by_key_name(key_names = c['bids'][i][0]['bid']) for j in range(len(c['bids'][i])): if 'key' in c['bids'][i][j]: l = loan.getLoan(c['bids'][i][j]['key']) if (l.curr_upb >= long(float(c['bids'][i][j]['val']))): l.curr_upb -= long(float(c['bids'][i][j]['val'])) l.put() else: raise CalcError("ERROR: At discount Bit %s to Loan %s curr_upb %s" % (str(c['bids'][i][0]['bid']), str(l.collateral_key), str(l.curr_upb))) b.status = 'Accepted' b.put() self.response.out.write(template.render("templates/results.html", parameters)) except: g = getGroup() if g == 'Demo': c = Demo_Param_Calc() parameters['loans'] = c['loans'] parameters['bids'] = c['bids'] self.response.out.write(template.render( "templates/results.html", parameters)) else: self.response.out.write(template.render("templates/oops.html", []))
def test_calc_028(self): self.assertEqual(calc('-69 * 42 * -25 - -71 + -43 + -73 * 48 - 74'), 68900)
def testSyntax(self): with self.assertRaises(SyntaxError): calc.calc('+1+1')
def testMultiplication(self): self.assertEqual(calc.calc('6*3'), 18)
def testSubtraction(self): self.assertEqual(calc.calc('10-2'), 8)
def testDivision(self): self.assertEqual(calc.calc('5/5'),1)
def test_calc_224(self): self.assertEqual(calc('4- 8- 53- -36'), -21)
def test_calc_220(self): self.assertEqual(calc('-59- -28- 6- 8'), -45)
def main(argv): """ Main """ #"hlmNzc:d:e:f:L:n:s:U:v:" features = {} featuresArffTrue = {} featuresArffFalse = {} options = {} currentFeature="" deleteDate = 0 # countMTrue = 0 # countMFalse = 0 makeArff = False authFile = False if len(sys.argv) ==1: usage() else: for i, arg in enumerate(argv): #print arg if arg=='-a': # initialize variables, dictionaries, lists for each feature showNums = False # authFile = False viz = False try: currentFeature = argv[i+1] except KeyError: usage() if currentFeature not in features: features[currentFeature] = [] options[currentFeature] = {} options[currentFeature]['column'] = -1 options[currentFeature]['equilibrium'] = 0 options[currentFeature]['noZero'] = False options[currentFeature]['numberOnly'] = False options[currentFeature]['lowerLimit'] = False options[currentFeature]['upperLimit'] = False options[currentFeature]['lastBeforeEq'] = False options[currentFeature]['startDate'] = False options[currentFeature]['makeArff'] = False options[currentFeature]['viz'] = False options[currentFeature]['neg'] = False options[currentFeature]['pos'] = False options[currentFeature]['step'] = False options[currentFeature]['cum'] = False options[currentFeature]['lastIncreasing'] = False options[currentFeature]['count'] = 0 options[currentFeature]['prev'] = 0 options[currentFeature]['next'] = 0 options[currentFeature]['deleteDate'] = 0 try: if arg == '-c': options[currentFeature]['column'] = float(argv[i+1]) if arg == '-e': options[currentFeature]['equilibrium'] = float(argv[i+1]) if arg == '-L': options[currentFeature]['lowerLimit'] = str(argv[i+1]).split(",") if arg == '-U': options[currentFeature]['upperLimit'] = str(argv[i+1]).split(",") if arg == '-n': options[currentFeature]['numberOnly'] = float(argv[i+1]) if arg == '-d': options[currentFeature]['startDate'] = str(argv[i+1]) if arg == '-dd': options[currentFeature]['deleteDate'] = int (argv[i+1]) deleteDate = int(argv[i+1]) if arg == '-l': options[currentFeature]['lastBeforeEq'] =True if arg == '-li': options[currentFeature]['lastIncreasing'] = True if arg == '-C': options[currentFeature]['count'] = str(argv[i+1]) if arg == '-N': options[currentFeature]['next'] = int(argv[i+1]) if arg == '-P': options[currentFeature]['prev'] = int(argv[i+1]) if arg == '-z': options[currentFeature]['noZero'] =True if arg == '-M': #options[currentFeature]['makeArff'] =True #countMTrue = countMTrue + 1 makeArff = True if arg == '-m': showNums = True if arg == '-f': authFile = str(argv[i+1]) if arg == '-v': options[currentFeature]['viz'] = (str(argv[i+1])).split(',') viz = (str(argv[i+1])).split(',') try: neg = False pos = False if viz[0] == 'neg': options[currentFeature]['neg'] = True elif viz[0] == 'pos': options[currentFeature]['pos'] = True elif viz[0] != 'neg' and viz[0] != 'pos': usage() options[currentFeature]['step'] = int(viz[1]) except IndexError: usage() try: options[currentFeature]['cum'] = bool(viz[2]) except IndexError: options[currentFeature]['cum'] = False except IndexError: usage() """ # carry over all options specified for "result" for other features if "result" in options: # print "result in options!" for resultOption in options["result"]: for feature in options: if not feature == "result": options[feature][resultOption] = options["result"][resultOption] """ if deleteDate: for feature in options: options[feature]['deleteDate'] = deleteDate if authFile: #if countMTrue: features = newparser.ingestAuth(authFile, features) data = newparser.postProc(features, options) buckets = data["buckets"] filteredFeatures = data["lists"] optionsUpdated = data["options"] #print "buckets", buckets calcVals = calc.calc(buckets) output.printit(calcVals, showNums) output.vizBatch(buckets, optionsUpdated) if makeArff: output.genArff('result.arff', filteredFeatures, optionsUpdated) print "result.arff file generated!\n" #if countMFalse: # else: #featuresArffFalse = newparser.ingestAuth(authFile, featuresArffFalse) #valuesArffFalse = newparser.post_proc(featuresArffFalse, options) #output.vizBatch(values, options) else: usage()
def test_calc(): assert calc('1+2*3') == 7 assert calc('1*2+3') == 5 assert calc('(1+2)*3') == 9 assert calc('1/(3-2)*4') == 4 assert calc('3*2+4*1+(4+9)*6') == 88
def update_compute(self, n=400): x, y = calc.calc(n) self.axes.plot(x, y, 'ro') self.draw()
def compute_initial_figure(self): x, y = calc.calc(400) self.axes.plot(x, y, 'ro')
def testAddition(self): self.assertEqual(calc.calc(re.search("\d+\d",s),2))
def testType(self): with self.assertRaises(TypeError): calc.calc('string')
def test_calc_216(self): self.assertEqual( calc( '-(-85) * (31 - -16 * (69)) * (75 * -((((36 - -33)))) / -32)'), 15601816.40625)
def test_calc_218(self): self.assertEqual(calc('-33- 31- 18- 54'), -136)
def testFloats(self): self.assertEqual(calc.calc('2.5+1.4'), 3.9)
def test_calc_222(self): self.assertEqual(calc('-15- 94- 60- 4'), -173)
def testMultiDigit(self): self.assertEqual(calc.calc('15+512'), 527)
def do(): def testing(act, exp): Test.expect( abs(act - exp) < 1e-6, "{} should equal {}".format(act, exp)) Test.it("Fixed tests") tests = [["2 + 3 * 4 / 3 - 6 / 3 * 3 + 8", 8], ["1 + 2 * 3 * 3 - 8", 11], ["1 + 2 * 3 * (5 - 2) - 8", 11], ["1 + 2 * 3 * (5 - (3 - 1)) - 8", 11], ["4 + -(1)", 3], ["4 - -(1)", 5], ["4 * -(1)", -4], ["4 / -(1)", -4], ["-1", -1], ["-(-1)", 1], ["-(-(-1))", -1], ["-(-(-(-1)))", 1], ["(((((-1)))))", -1], ["5 - 1", 4], ["5- 1", 4], ["5 -1", 4]] try: if calc("'x'") == "x": Test.expect(False, "Trying to use eval?") except: pass for test in tests: testing(calc(test[0]), test[1]) Test.it("Random tests") for i in range(100): try: expression = "{}{} {} {}{} {} {}{} {} {}{} {} {}{} {} {}{} {} {}{} {} {}{}".format( random.choice(["-", ""]), random.randint(1, 100), random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]), random.randint(1, 100), random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]), random.randint(1, 100), random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]), random.randint(1, 100), random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]), random.randint(1, 100), random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]), random.randint(1, 100), random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]), random.randint(1, 100), random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]), random.randint(1, 100)) testing(calc(expression), eval(expression)) except ZeroDivisionError: pass for i in range(100): try: expression = "{}({}{}) {} ({}{} {} {}{} {} {}({})) {} ({}{} {} {}((({}({}{} {} {}{})))) {} {}{})".format( random.choice(["-", ""]), random.choice(["-", ""]), random.randint(1, 100), random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]), random.randint(1, 100), random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]), random.randint(1, 100), random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]), random.randint(1, 100), random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]), random.randint(1, 100), random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]), random.choice(["-", ""]), random.choice(["-", ""]), random.randint(1, 100), random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]), random.randint(1, 100), random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]), random.randint(1, 100)) testing(calc(expression), eval(expression)) except ZeroDivisionError: pass for i in range(100): expression = "{}{}- {}{}- {}{}- {}{}".format(random.choice(["-", ""]), random.randint(1, 100), random.choice(["-", ""]), random.randint(1, 100), random.choice(["-", ""]), random.randint(1, 100), random.choice(["-", ""]), random.randint(1, 100)) testing(calc(expression), eval(expression))
def testNegativeSum(self): self.assertEqual(calc.calc('3-4', -1))
def test_minus(): tree = ("-", (2, 4)) assert calc(tree) == -6 tree = (("-", (2, 4)), 3) assert calc(tree) == -3
def testMultiplciation(self): self.assertEqual(calc.calc('2*4'), 8)
def testAddition(self): self.assertEqual(calc.calc('1+1'), 2)
def testMultiplciation(self): self.assertEqual(calc.calc('10*12'), 120)
def test_calc(self): for expr, val in self.exprtoval: result = calc.calc(expr) self.assertEqual(val, result)
def test_calc_026(self): self.assertEqual(calc('46 + 92 + -34 + 35 / -72 + -2 * 41 + 26'), 47.513888888888886)
def test_calc_214(self): self.assertEqual( calc( '-(-86) - (64 + 14 / (22)) + (-73 * -(((-(-44 / -80)))) * -20)' ), 824.3636363636365)
def test_calc_202(self): self.assertEqual( calc( '(54) + (13 / -50 * (29)) - (-64 - -(((-(-34 * 52)))) / -50)'), 145.82)
def test_calc_215(self): self.assertEqual( calc('(-82) / (-3 / 40 * (95)) / (-53 - -(((-(-29 * -20)))) * -12)' ), 0.001666247564763944)
def test_calc_203(self): self.assertEqual( calc( '(-53) + (100 * -46 - -(28)) * (91 * (((-(-17 - 47)))) / 96)'), -277421.0)
def test_calc_217(self): self.assertEqual(calc('40- 10- 8- -72'), 94)
def test_calc_002(self): self.assertEqual(calc('1 + 2 * 3 * 3 - 8'), 11)
def test_calc_219(self): self.assertEqual(calc('-75- -37- 62- 50'), -150)
def test_calc_204(self): self.assertEqual( calc('(30) - (67 * 13 * -(97)) + (-24 - ((((-88 / 99)))) * -31)'), 84465.44444444444)
def test_calc_221(self): self.assertEqual(calc('62- -57- -78- -95'), 292)
def test_calc_205(self): self.assertEqual( calc('-(95) - (-40 + -44 * (77)) / (32 - -((((77 - 82)))) * -8)'), -47.388888888888886)
def test_calc_223(self): self.assertEqual(calc('92- -19- 22- 36'), 53)
def test_calc_206(self): self.assertEqual( calc( '-(-97) * (-97 - -86 * -(23)) * (-46 + ((((-69 - 44)))) / -37)' ), 8643945.27027027)
def test_calc_225(self): self.assertEqual(calc('21- -71- 51- 80'), -39)
def test_calc_207(self): self.assertEqual( calc('(-13) + (9 / 14 / (54)) - (-29 - -((((-48 / 38)))) + 10)'), 7.275062656641605)
def test_int_int(self): calc.calc(7, 8)
def test_calc_208(self): self.assertEqual( calc('(-40) - (-85 * 22 - (78)) - (2 - (((-(-19 * 62)))) + 60)'), 3024)
def test_calc_209(self): self.assertEqual( calc( '-(-38) * (8 - 21 * (98)) + (75 - -(((-(-25 + -38)))) * -97)'), -83936)
def test_calc_027(self): self.assertEqual(calc('-4 + 89 - -84 + 75 + 50 + -11 - 64 + 22'), 241)
menu(' <- Select player A\'s number of last Cards', '') cards_A = int(input('')) system('cls') menu('', ' <- Select player B\'s number of last Cards') cards_B = int(input('')) system('cls') if cards_A <= 0: menu(' <- Select player A\'s fatigue level', '') fatigue_A = int(input('')) system('cls') else: fatigue_A = 0 if cards_B <= 0: menu('', ' <- Select player B\'s fatigue level') fatigue_B = int(input('')) system('cls') else: fatigue_B = 0 menu(' <- Player A', ' <- Player B') turn = input('Which player\'s turn is it ? (A or B)\n').lower() system('cls') winner, life = calc(life_A, life_B, cards_A, cards_B, fatigue_A, fatigue_B, turn) if winner: #True = Player B will win #False = Player A will win menu('',' <- Player B wins with ' + str(life) + ' life') else: menu(' <- Player A wins with ' + str(life) + ' life', '')
def test_calc_210(self): self.assertEqual( calc('(-3) * (-58 * 17 / (40)) * (-84 / -(((-(-42 + -70)))) * -69)' ), -3826.9124999999995)
def testMultiplciation(self): self.assertEqual(calc.calc('3*2'), 6)
def testMultiplication(self): self.assertEqual(calc.calc('5*5'),25)
def testSubtraction(self): self.assertEqual(calc.calc('1-1'), 0)
def test_calc_212(self): self.assertEqual( calc( '-(20) * (-38 - -76 + (96)) + (-18 + (((-(69 + -73)))) / 60)'), -2697.9333333333334)
def testDivision(self): self.assertEqual(calc.calc('6/2'), 3)
def test_calc_213(self): self.assertEqual( calc('-(69) * (28 + -76 * (56)) + (90 + -(((-(100 - 2)))) / 61)'), 291823.60655737703)
def test_calc_211(self): self.assertEqual( calc('-(1) / (-20 / -53 * -(49)) + (-79 + ((((-57 - 9)))) - -5)'), -139.94591836734693)
def testMultiplciation(self): self.assertEqual(calc.calc('1*5'), 5)