# 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. # 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: self.conn.reply(str(e)) return try: self.server.doMessage(channel, user+": "+str(self.stack[0])) except Exception as e: return