# guppy Copyright (C) 2010-2011 guppy team members. # # This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. # This is free software, and you are welcome to redistribute it # under certain conditions; type `show c' for details. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # rpn module # --gry @plugin class rpn(object): """Math - Reverse Polish Notation""" def __init__(self, server): self.server = server self.commands = ["rpn"] self.server.handle("command", self.handle_command, self.commands) def handle_command(self, channel, user, cmd, args): if cmd == "rpn": if len(args) < 1: self.server.doMessage(channel, user + ": reverse-polish-notation calculator. syntax: rpn 2 4 1 + / gives 2/5.") return self.stack = [] for char in args: try: char = float(char) # if it succeeds, then char is a number self.stack.append(char) except Exception as e: # float(char) failed, it's nonsense or an operator try: a = float(self.stack.pop()) # last b = float(self.stack.pop()) # pre-last if char == "+": self.stack.append(a + b) elif char == "-": self.stack.append(b - a) elif char == "^": self.stack.append(pow(b, a)) elif char == "*": self.stack.append(a * b) elif char == "/": self.stack.append(b / a) except Exception as e: # Hardcoding this bit in many places is stupid. self.server.doMessage(channel, user + ": " + str(e)) return try: self.server.doMessage(channel, user + ": " + str(self.stack[0])) except Exception as e: print(e) return