Exemple #1
0
 def test_exception_rpn(self):
     data = [
         ["1 1 - 0 /", ZeroDivisionError, "ゼロで割ることはできません"],
         ["a 12 -", ValueError, "値が正しくありません"],
         ["1 12 1", Exception, "式が正しくありません"],
         ["1 -", IndexError, "式が正しくありません"],
     ]
     for target in data:
         with self.assertRaises(target[1], msg=target[2]):
             rpn(target[0])
Exemple #2
0
def expectEqual( command1, command2 ):
    print( 'rpn', command1 )
    print( 'rpn', command2 )

    result1 = rpn( shlex.split( command1 ) )[ 0 ]
    result2 = rpn( shlex.split( command2 ) )[ 0 ]

    compareResults( result1, result2 )

    print( '    both are equal!' )
    print( '' )
Exemple #3
0
    def __init__(self):
        Gtk.Window.__init__(self, title="RPN Calculator")
        self.set_border_width(10)
        self.set_size_request(600, 500)
        self.set_position(Gtk.WindowPosition.CENTER)

        # Layout
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        self.add(vbox)

        # Scroll Window (Packed in right side of hbox)
        self.scrolledwindow = Gtk.ScrolledWindow()
        self.scrolledwindow.set_hexpand(True)
        self.scrolledwindow.set_vexpand(True)
        vbox.pack_start(self.scrolledwindow, True, True, 0)

        # TextView added to Scroll Window
        self.textview = Gtk.TextView()
        font = Pango.FontDescription('monospace 14')
        self.textview.modify_font(font)
        self.textbuffer = self.textview.get_buffer()
        self.textbuffer.set_text("RPN Calculator by Darrell Harriman\
        \n\n\tEnter ? for help\n\n")
        self.textview.set_wrap_mode(Gtk.WrapMode.WORD)
        self.scrolledwindow.add(self.textview)

        # Text Entry 1
        self.text1 = Gtk.Entry()
        self.text1.set_text("")
        self.text1.connect("activate", self.submit_entry1)
        vbox.pack_start(self.text1, False, False, 0)

        self.R = rpn("")
        self.text1.grab_focus()
Exemple #4
0
	def calculate(self, calcinput):

		tokens = []

		# Turn string input into a list of tokens
		for char in calcinput:
			tk = self.tokenizer(char)

			if not tk:
				continue

			if len(tokens) > 0:
				ltk = tokens[-1]
				if ltk.kind == tk.kind and tk.kind in (Kind.alpha, Kind.numeric):
					ltk.update(tk.value)
					continue
			
			tokens.append(tk)

		# Convert infix notation into postfix notation
		s = ShuntingYard()
		s.feed(tokens)
		args = []
		for x in s.output_queue:
			args.append(x.value)

		# Run output through the reverse polish notation calculator
		return rpn(*args)
Exemple #5
0
 def test_rpn(self):
     data = [
         ["1 2 + 4 -", -1],
     ]
     for target in data:
         result = rpn(target[0])
         if result != target[1]:
             print(target[0])
         self.assertEqual(result, target[1])
Exemple #6
0
def dorpn(args):
	try: 
		result = rpn(*args)

	except IndexError:
		result = INDEX_ERROR

	except ValueError:
		result = VALUE_ERROR

	return result
Exemple #7
0
def expectException( command ):
    print( 'rpn', command )

    result = rpn( shlex.split( command ) )

    if result == [ nan ]:
        print( 'exception test passed!' )
        print( '' )
        return True

    raise ValueError( 'exception was expected but didn\'t happen' )
    return False
Exemple #8
0
def expectEquivalent( command1, command2 ):
    print( 'rpn', command1 )
    print( 'rpn', command2 )

    result1 = rpn( shlex.split( command1 ) )[ 0 ]
    result2 = rpn( shlex.split( command2 ) )[ 0 ]

    if isinstance( result1, list ) != isinstance( result2, list ):
        print( '**** error in results comparison' )
        print( '    result 1: ', result1 )
        print( '    result 2: ', result2 )
        raise ValueError( 'one result is a list, the other isn\'t' )

    if not areListsEquivalent( result1, result2 ):
        print( '**** error in results comparison' )
        print( '    result 1: ', result1 )
        print( '    result 2: ', result2 )
        raise ValueError( 'unit test failed' )

    print( '    both are equal!' )
    print( '' )
Exemple #9
0
def testOperator( command ):
    print( 'rpn', command )
    result = rpn( shlex.split( command ) )

    if result is not None and isinstance( result[ 0 ], mpf ) and result == [ nan ]:
        raise ValueError( 'unit test failed' )

    if result is not None:
        handleOutput( result )

    print( '    operator works!' )
    print( '' )
Exemple #10
0
def expectResult( command, expected ):
    print( 'rpn', command )
    result = rpn( shlex.split( command ) )[ 0 ]

    compare = None

    if isinstance( expected, list ):
        compare = [ ]

        for i in expected:
            if isinstance( i, ( int, float, complex ) ):
                compare.append( mpmathify( i ) )
            else:
                compare.append( i )
    else:
        if isinstance( expected, ( int, float, complex ) ):
            compare = mpmathify( expected )
        else:
            compare = expected

    compareResults( result, compare )

    print( '    test passed!' )
    print( '' )
Exemple #11
0
            if stack0.isEmpty() or stack0.top() == '+' or stack0.top(
            ) == '-' or stack0 == '(':
                stack0.push(token)
            else:
                while not stack0.isEmpty() and (stack0.top() == '*'
                                                or stack0.top() == '/'):
                    output.append(stack0.pop())
                stack0.push(token)
        elif token == '(':
            stack0.push(token)
        elif token == ')':
            while stack0.top() != '(':
                output.append(stack0.pop())
            stack0.pop()
            # pop out '(' and discard
        else:
            output.append(token)
    while (not stack0.isEmpty()):
        # pop out the reset operators
        output.append(stack0.pop())
    return output


# test run
# a + b * c + ( d * e + f ) * g
if __name__ == '__main__':
    print(inToPostfix('a + b * c + ( d * e + f ) * g'))

import rpn
print(rpn.rpn(' '.join(inToPostfix('1 + 2 - 3 * 6 + ( 5 - 2 ) * 7 / 2 - 1'))))
Exemple #12
0
def test_example_1():
	assert rpn(5, 8, '+') == 13
Exemple #13
0
def test_division():
	assert rpn('8', '2', '/') == 4
Exemple #14
0
def test_multiply():
	assert rpn('2', 2, '*') == 4
Exemple #15
0
def test_zero():
	with pytest.raises(ZeroDivisionError):
		rpn('2', '0', '/')
Exemple #16
0
def test_bad_str():
 	with pytest.raises(ValueError):
 		rpn('this', 'bad', '+')
Exemple #17
0
def test_addition():
	assert rpn('2', 2, '+') == 4
Exemple #18
0
def test_subtraction():
	assert rpn('7', '3', '-') == 4
Exemple #19
0
def test_wikipedia_example():
	assert rpn(5, 1, 2, '+', 4, '*', '+', 3, '-') == 14
Exemple #20
0
def test_weird_chars():
	with pytest.raises(ValueError):
		# below looks normal but the minus symbol is 
		# some different unicode symbol so it won't
		# recognize it as an operator and blow up 
		assert rpn(5, 3, '−') == 2
Exemple #21
0
def test_weird_input_array():
	with pytest.raises(ValueError):
		assert rpn([5, 3, '-']) == 2
Exemple #22
0
 def eval(self):
     return rpn(self.value)
Exemple #23
0
def test_bad_input_string():
	with pytest.raises(ValueError):
		assert rpn('5 3 -') == 2
Exemple #24
0
top = (variable_file.readline()).strip()
structure = read_structure(top)
variables = {}
samples = True

for equation in equations:
    top += "," + equation[0] + ",Error"
top += "\n"
output_csv.write(top)
string = ""
line = variable_file.readline()
while line:
    line = line.strip()
    string += line
    read_vars(line, structure, variables)
    for equation in equations:
        answer = rpn(equation[1], variables, output_file, samples)
        answer.string = equation[0]
        answer.string_nums = ""
        variables[equation[0]] = answer
        string += "," + str(answer.value) + "," + str(answer.error)
    samples = False
    string += "\n"
    line = variable_file.readline()
output_csv.write(string[:-1])
output_file.write("\\end{document}")
output_file.close()
formula_file.close()
variable_file.close()
output_csv.close()
os.system("pdflatex output.tex")
Exemple #25
0
def test_example_2():
	assert rpn(-3, -2, '*', 5, '+') == 11
Exemple #26
0
def rapport(token):
    r = rpn.rpn(rpn.token(token))
    return render_template('rapport.html',
                           observateurs=r.observateurs(),
                           especes=r.especes())
Exemple #27
0
def test_example_3():
	assert rpn(2, 9, 3, '+', '*') == 24
Exemple #28
0
class MyApp(QtWidgets.QMainWindow, Ui_MainWindow):
# class MyApp(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.calcEntry.returnPressed.connect(self.updateScreen)

        self.cmds = {
        "?": self.showHelp,
        "sh": self.showStack,
        "w": self.welcome,
        "exit": self.appExit
        }

self.R = rpn("")
        self.welcome()

    def updateScreen(self):
        entryStr = self.calcEntry.text()
        if entryStr in self.cmds:
            self.cmds[entryStr]()
        else:
            self.R.update(entryStr)
            rpnOut = self.R.getStack()
            self.calcScreen.setText(rpnOut)
#            self.calcScreen.append(entryStr)
            self.calcEntry.setText("")

    def showHelp(self):
        self.calcScreen.setFontPointSize(10)
Exemple #29
0
def test_example_4():
	assert rpn(20, 13, '-', 2, '/') == 3.5