Last active
April 14, 2018 22:34
-
-
Save hamzamuric/4caa78fd43ecd9b5152604c25f969ef9 to your computer and use it in GitHub Desktop.
Convert expression to a postfix notation with GTK+ GUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from gi.repository import Gtk | |
class MainWindow(Gtk.Window): | |
def __init__(self): | |
Gtk.Window.__init__(self, title="Postfix") | |
self.set_border_width(10) | |
self.set_size_request(250, 150) | |
# Layout | |
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8) | |
self.add(vbox) | |
# Label | |
self.label = Gtk.Label() | |
self.label.set_label('Postfiksni izraz') | |
vbox.pack_start(self.label, True, True, 0) | |
# Input | |
self.input = Gtk.Entry() | |
self.input.set_text('a + b * c') | |
vbox.pack_start(self.input, True, True, 0) | |
# Button | |
self.button = Gtk.Button(label='Convert to postfix') | |
self.button.connect('clicked', self.convert) | |
vbox.pack_start(self.button, True, True, 0) | |
def convert(self, widget): | |
operators = {'(': 0, ')': 0, '+': 1, '-': 1, '*': 2, '/': 2, '%': 2} | |
stack = [] | |
postfix = [] | |
expression = self.input.get_text().split() | |
for ch in expression: | |
if ch in operators: | |
if ch is ')': | |
while stack and stack[-1] is not '(': | |
postfix.append(stack.pop()) | |
stack.pop() | |
continue | |
# if stack and operators[ch] <= operators[stack[-1]]: | |
if stack and operators[stack[-1]] is 2 and (operators[ch] is 2 or operators[ch] is 1): | |
postfix.append(stack.pop()) | |
stack.append(ch) | |
else: | |
postfix.append(ch) | |
for _ in range(len(stack)): | |
postfix.append(stack.pop()) | |
output = ' '.join(str(e) for e in postfix) | |
self.label.set_label(output) | |
window = MainWindow() | |
window.connect("delete-event", Gtk.main_quit) | |
window.show_all() | |
Gtk.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should be updated to support powers (x^y).
You can try to add it, as well as other additional features. 😄