Ejemplo n.º 1
0
def test_add_two_numbers():
    '''
    Test method for the add_numbers function.
    '''
    calc_obj1 = calculator.Calculator(2, 2)
    assert calc_obj1.add_numbers() == 4
    calc_obj2 = calculator.Calculator(1, -1)
    assert calc_obj2.add_numbers() == 0
Ejemplo n.º 2
0
 def testFour(self):
     calc = calculator.Calculator()
     #Text parser test
     #If everything doesn't work as expected, this will enter an infinite loop, or throw an exception.
     tests = list("11+12+1*20 / 20=Q")
     with patch.object(calculator, "getwch", create=True,
                       side_effect=tests):
         c = calculator.Calculator()
         c.inputParser()
Ejemplo n.º 3
0
def main():
    help_msg = \
"This is calculator for basic math expressions.\n\
Input correct expression and press <ENTER>.\n\
Press 'q <Enter>' to exit."

    readline_configure()

    c = calc.Calculator()

    while True:
        user_input = raw_input('> ')
        if user_input == 'h':
            print(help_msg)
        elif user_input == 'q':
            break
        else:
            try:
                result = c.calculate("".join(user_input))
            except (calc.parser.ParseError, calc.converter.ConvertError,
                    calc.converter.ConvertError, calc.evaluator.EvaluateError,
                    ArithmeticError, ValueError) as e:
                print("Error: " + str(e))
            else:
                print("= " + str(result))
Ejemplo n.º 4
0
 def help_run_test(self, tests):
     calc = calculator.Calculator()
     for test in tests:
         arg_list = calc.parse_string_to_list(test[0])
         calc.generate_output_queue(arg_list)
         res = calc.calculate()
         self.assertAlmostEqual(test[1], res)
Ejemplo n.º 5
0
    def testThree(self):
        calc = calculator.Calculator()
        #Individual function test cases
        #preProcessing
        self.assertEqual(calc.preProcessExpression("1 + 1 = "), "1+1")
        self.assertEqual(calc.preProcessExpression("1 -- 1 = "), "1n-1")
        self.assertEqual(calc.preProcessExpression("1 + 1 -1 = "), "1+1n1")

        #Getting numbers
        tests = ['5n15/3', '11+12+120', '15n-20']
        leftExpectedNumbers = ['3', '120', '-20']
        leftExpectedOriginals = ['5n15/', '11+12+', '15n']
        rightExpectedNumbers = ['5', '11', '15']
        rightExpectedOriginals = ['n15/3', '+12+120', 'n-20']

        for i in range(len(tests)):
            self.assertEqual(
                calc.getNumber(tests[i], "left"),
                (leftExpectedNumbers[i], leftExpectedOriginals[i]))
            self.assertEqual(
                calc.getNumber(tests[i], "right"),
                (rightExpectedNumbers[i], rightExpectedOriginals[i]))

        with self.assertRaises(ValueError) as ex:
            calc.getNumber("11+12+13", "center")
        exception = ex.exception
        self.assertEqual(exception.args[0], 'Unrecognized direction')
Ejemplo n.º 6
0
 def testOne(self):
     calc = calculator.Calculator()
     #Equations called out in the application
     self.assertEqual(calc.evaluate("2+2="), 4)
     self.assertEqual(calc.evaluate("-5* 5/3 ="), -8.3333333333333333)
     self.assertEqual(calc.evaluate("7+-6 ="), 1)
     self.assertEqual(calc.evaluate("-5* 5-15 /3 ="), -30)
Ejemplo n.º 7
0
    def __init__(self):
        Tk.__init__(self)
        self.title("Calculadora")
        self.geometry('270x300+600+150')
        self.resizable(0, 0)

        self.calculator = calculator.Calculator(self)
        self.calculator.pack()
Ejemplo n.º 8
0
 def test_generate_queue_2(self):
     calc = calculator.Calculator()
     _input = [
         calc.functions['EXP'], '(', '(',
         1, calc.operators['+'], 2, calc.operators['*'], 3, ')', ')'
     ]
     calc.generate_output_queue(_input)
     self.assertAlmostEqual(1096.633158428, calc.calculate())
 def testingSquareRoot(self):
     with open('./Unit Test Addition.csv', 'r') as addition:
         data = csv.reader(addition)
         converting_into_list = list(data)
         for x in range(1, len(converting_into_list)):
             arg1 = int(converting_into_list[x][x - x])
             result = int(converting_into_list[x][x - x + 1])
             main_func = calculator.Calculator().square_root(arg1)
             self.assertEqual(main_func, result)
Ejemplo n.º 10
0
 def test_complete_system(self):
     calc = calculator.Calculator()
     ex1 = "(3 MINUS 5) GANGE 5"
     ex2 = "EXP(12.2 PLUSS 3 GANGE 1)"
     ex3 = "SQRT(6 GANGE 6)"
     self.assertEqual(-10, calc.calculate_expression(ex1))
     self.assertAlmostEqual(3992786.8352109445,
                            calc.calculate_expression(ex2))
     self.assertEqual(6, calc.calculate_expression(ex3))
 def testingDivision(self):
     with open('./Unit Test Division.csv', 'r') as addition:
         data = csv.reader(addition)
         converting_into_list = list(data)
         for x in range(1, len(converting_into_list)):
             arg1 = int(converting_into_list[x][x - x])
             arg2 = int(converting_into_list[x][x - x + 1])
             result = int(converting_into_list[x][x - x + 2])
             main_func = calculator.Calculator().division(arg1, arg2)
             self.assertEqual(main_func, result)
 def test_add_record(self, init_limit, data_records, msg_err):
     result = calculator.Calculator(init_limit)
     assert hasattr(result,
                    'add_record'), msg_err('add_method', 'add_record',
                                           'Calculator')
     records, today, week = data_records
     for record in records:
         result.add_record(record)
     assert result.records == records, msg_err('wrong_attr', 'records',
                                               'Calculator')
 def test_get_week_stats(self, init_limit, data_records, msg_err):
     result = calculator.Calculator(init_limit)
     records, today, week = data_records
     for record in records:
         result.add_record(record)
     assert hasattr(result,
                    'get_week_stats'), msg_err('add_method',
                                               'get_week_stats',
                                               'Calculator')
     assert result.get_week_stats() == week, msg_err(
         'wrong_method', 'get_week_stats', 'Calculator')
Ejemplo n.º 14
0
    def new_session(self, *args):
        ''' a session represents the screen you see when you open
        a calculator program on linux or windows. (or a physical one!)

        this week, we will only be dealing with calculating fractions.
        you should tell the user to encase the fractions in brackets,
        then extract the fractions for calculation purposes.

        once inside a session,

        prompt the console to print the current value, initialized as 0.
        just like a regular calculator, usage will be as follows.

        user types (15/4)+(12/13)
        user types enter
        program calculates, saves into a last_result variable.
        program prints the last_result variable.
        program prompts to continue or exit
        if continued, program displays and types ANS
        (representing the last_result variable.)
        program proceeds.

        the calculation will require you to recognize a fraction from
        user input, then call the add()/subtract()/multiply()/divide()
        functions from the Calculator class.

        '''
        userInput = input('Enter your mathematical expression: ' + args[0])
        if args[0] == "ANS" and not args[1] == "":
            userInput = "(%s/%s)" % (args[1].numerator,
                                     args[1].denominator) + userInput
        # userInput = '(15/4)+(12/13)'
        fractions = self.fractionRegex.findall(userInput)
        # print(fractions)
        fraction1 = Fraction(fractions[0][0], fractions[0][1])
        fraction2 = Fraction(fractions[1][0], fractions[1][1])
        self.calculator = calculator.Calculator(fraction1, fraction2)
        sign = self.signRegex.findall(userInput)
        print(sign)
        if sign[3] == "/":
            result = self.calculator.divide()
            print("(%s/%s)" % (result.numerator, result.denominator))
        elif sign[3] == "+":
            result = self.calculator.add()
            print("(%s/%s)" % (result.numerator, result.denominator))
        elif sign[3] == "-":
            result = self.calculator.subtract()
            print("(%s/%s)" % (result.numerator, result.denominator))
        elif sign[3] == "*":
            result = self.calculator.multiply()
            print("(%s/%s)" % (result.numerator, result.denominator))
        else:
            print("Incorrect input.")
        return result
Ejemplo n.º 15
0
def calc():
    '''
    Controller code for the main webesite application
    '''
    if request.method == 'POST':
        calc_obj = calculator.Calculator(request.form['first_number'],
                                         request.form['second_number'])
        calc_json = calc_obj.return_json()

        return render_template('calculator.html', results=calc_json)
    return render_template('calculator.html')
Ejemplo n.º 16
0
 def test_text_parser(self):
     calc = calculator.Calculator()
     ex1 = [2.0, calc.operators['GANGE'], 3.0, calc.operators['PLUSS'], 1.0]
     txt1 = "2.0 GANGE 3.0 PLUSS 1.0"
     self.assertEqual(ex1, calc.parse_text(txt1))
     ex2 = [
         calc.functions['EXP'], '(', 1.0, calc.operators['PLUSS'], 2.0,
         calc.operators['GANGE'], 3.0, ')'
     ]
     txt2 = "EXP(1.0PLUSS2.0GANGE3.0)"
     self.assertEqual(ex2, calc.parse_text(txt2))
Ejemplo n.º 17
0
    def test_generate_queue_1(self):
        calc = calculator.Calculator()
        _input = [
            1, 2, 3, calc.operators['*'],
            calc.operators['+'], calc.functions['EXP']
        ]

        for elem in _input:
            calc.output_queue.push(elem)

        self.assertAlmostEqual(1096.633158428, calc.calculate())
Ejemplo n.º 18
0
    def __cal_taptime(self):
        '''Figure out how much time to tap for on cellphone's screen'''

        #Calculate distance between pawn and target by calculater.py
        helper=calculator.Calculator(self.screenshot_name)
        self.dist=helper.cal_dist()

        #Determine the jump factor by invoking self.__cal_factor
        self.__cal_factor()

        #Figure out tap_time
        self.tap_time=int(self.dist*self.factor)
Ejemplo n.º 19
0
 def testTwo(self):
     calc = calculator.Calculator()
     #Other useful test cases
     self.assertEqual(calc.evaluate("11+12+1*20 / 20"), 24)
     self.assertEqual(calc.evaluate("22+22="), 44)
     self.assertEqual(calc.evaluate("-22/-22="), 1)
     self.assertEqual(calc.evaluate("-100--50="), -50)
     #Edge cases
     with self.assertRaises(ZeroDivisionError) as ex:
         calc.evaluate("100/0=")
     exception = ex.exception
     self.assertEqual(exception.args[0], 'float division by zero')
Ejemplo n.º 20
0
    def test_functions_single(self):
        calc = calculator.Calculator()
        self.assertAlmostEqual(
            0.0, calc.functions['COS'].execute(math.pi/2))

        self.assertAlmostEqual(
            1.0, calc.functions['SIN'].execute(math.pi/2))

        self.assertAlmostEqual(
            1.0, calc.functions['EXP'].execute(0))

        self.assertAlmostEqual(
            2.0, calc.functions['SQRT'].execute(4))
Ejemplo n.º 21
0
 def test_between(self):
     calc = calculator.Calculator()
     self.assertEqual(
         calc.distance(9718, 99999), None,
         "Distance between an existing and a non-existing postcode should be None"
     )
     self.assertEqual(
         calc.distance(99999, 1000), None,
         "Distance between a non-existing and an existing postcode should be None"
     )
     self.assertEqual(
         int(calc.distance(9718, 1000)), 146,
         "Distance between postcodes 9718 and 1000 should be 146 km")
Ejemplo n.º 22
0
 def test_shunting_yard(self):
     calc = calculator.Calculator()
     list1_of_ops = [
         2, calc.operators['GANGE'], 3, calc.operators['PLUSS'], 1
     ]
     calc.convert_to_RPN(list1_of_ops)
     self.assertEqual(7, calc.eval_RPN())
     list2_of_ops = [
         calc.functions['EXP'], '(', 1, calc.operators['PLUSS'], 2,
         calc.operators['GANGE'], 3, ')'
     ]
     calc.convert_to_RPN(list2_of_ops)
     self.assertAlmostEqual(1096.63315843, calc.eval_RPN())
Ejemplo n.º 23
0
 def test_calculator(self):
     calc = calculator.Calculator()
     self.assertAlmostEqual(
         1096.6331584284585,
         calc.functions['EXP'].execute(calc.operators['PLUSS'].execute(
             1, calc.operators['GANGE'].execute(2, 3))))
     calc.output_queue.push(1)
     calc.output_queue.push(2)
     calc.output_queue.push(3)
     calc.output_queue.push(calculator_utils.Operator(numpy.multiply, 1))
     calc.output_queue.push(calculator_utils.Operator(numpy.add, 0))
     calc.output_queue.push(calculator_utils.Function(numpy.exp))
     self.assertAlmostEqual(1096.6331584284585, calc.eval_RPN())
Ejemplo n.º 24
0
def execute():
    """
    This method executes the logic of addition or multiplication
    """
    parse_arguments()
    numbers = args.number
    calc = calculator.Calculator(numbers)
    if args.add:
        result = calc.add()
        print("Result of addition is {res}".format(res=result))
    elif args.mul:
        product = calc.mul()
        print("Result of addition is {res}".format(res=product))
Ejemplo n.º 25
0
    def __init__(self):
        self.calc = cl.Calculator()
        self.layout = [
            [sg.InputText(size=(36, 5), key='txt')],
            [sg.Text(key='alert', text='Digite uma equação acima', size=(32, 0))],
            [btn(txt='('), btn(txt=')'), btn(txt='C'), btn(txt='⌫')],
            [btn(txt='x^y'), btn(txt='x^2'), btn(txt='n!'), btn(txt='/')],
            [btn(txt='7'), btn(txt='8'), btn(txt='9'), btn(txt='*')],
            [btn(txt='4'), btn(txt='5'), btn(txt='6'), btn(txt='-')],
            [btn(txt='1'), btn(txt='2'), btn(txt='3'), btn(txt='+')],
            [btn(txt='.'), btn(txt='0'), btn(txt='=', size=14)]
        ]

        self.window = sg.Window("Calculadora").layout(self.layout)
Ejemplo n.º 26
0
 def test_within(self):
     calc = calculator.Calculator()
     within = [
         postcode for (postcode, km) in calc.postcodesaround(9718, 10)
     ]
     self.assertEqual(
         len(within) > 0, True,
         "There should be al least one postcode within 10km of postcode 9718"
     )
     self.assertEqual(
         9811 in within, True,
         "Postcode 9811 should be within 10km of postcode 9718")
     self.assertEqual(
         1200 in within, False,
         "Postcode 1200 shouldn't be within 10km of postcode 9718")
Ejemplo n.º 27
0
    def __init__(self):
        self.id = 0
        self.data = ""
        self.result = ""
        self.log = ""

        self.con = threading.Condition()
        self.workQueue = queue.Queue(10)

        self.CMDS = [
            CMD(0, 1, "转换", str2md5.Str2Md5()),
            CMD(1, 1, "运行", monkeypeach.MonkeyPeach()),
            CMD(2, 1, "运行", fibonacci.Fibonacci()),
            CMD(3, 0, "计算", calculator.Calculator())
        ]
Ejemplo n.º 28
0
def calc_handler(request):
    logger.Logger().log(f'Get calc from {request.hostname}:{request.port}')

    req_handler = request_handler.RequestHandler(
        request, base_request_checker.BaseRequestChecker(request))

    if 'tariff' in req_handler.get_params():
        req_tariff = tariffs.tariff_container.get(
            req_handler.get_param('tariff'))
    else:
        req_tariff = tariffs.tariff_container.get('base')

    calc = calculator.Calculator(req_handler, req_tariff)
    res = calc.calc()
    logger.Logger().log(f'Response {res} to {request.hostname}:{request.port}')
    return req_handler.response(**res)
    def test_init(self, init_limit, msg_err):
        assert hasattr(calculator,
                       'Calculator'), msg_err('add_class', 'Calculator')
        result = calculator.Calculator(init_limit)
        assert hasattr(result, 'limit'), msg_err('add_attr', 'limit',
                                                 'Calculator')
        assert result.limit == init_limit, msg_err('wrong_attr', 'limit',
                                                   'Calculator')
        assert hasattr(result, 'records'), msg_err('add_attr', 'records',
                                                   'Calculator')
        assert result.records == [], msg_err('wrong_attr', 'records',
                                             'Calculator')

        assert not hasattr(result, 'USD_RATE'), msg_err(
            'dont_create_attr', 'USD_RATE', 'Calculator')
        assert not hasattr(result, 'EURO_RATE'), msg_err(
            'dont_create_attr', 'EURO_RATE', 'Calculator')
Ejemplo n.º 30
0
def main():

    calc = calculator.Calculator()
    firstNumber = input("\nFirst number: ")
    operation = input("\nOperation (+, -, *, /): ")
    secondNumber = input("\nSecond number: ")

    if operation == "+":
        print("\nYour answer is: " + calc.add(firstNumber, secondNumber))
    if operation == "-":
        print("\nYour answer is: " + calc.subtract(firstNumber, secondNumber))
    if operation == "*":
        print("\nYour answer is: " + calc.multiply(firstNumber, secondNumber))
    if operation == "/":
        print("\nYour answer is: " + calc.divide(firstNumber, secondNumber))
    else:
        print("\nYour operation is invalid, please try again")