Guest

python without ifs. challenge one.

By: a guest on Jun 12th, 2011  |  syntax: Python  |  size: 1.55 KB  |  hits: 54  |  expires: Never
download  |  raw  |  embed  |  report abuse
Copied
  1. #coding: utf-8
  2. """
  3. Make calculator that has [2, 3, 5] numbers, plus and minus buttons and equal button.
  4.  
  5. Additional condition: make it without any if statements
  6. """
  7. class CalcModel:
  8.     """
  9.    Calculator Model
  10.  
  11.    >>> c = CalcModel()
  12.    >>> c.add_number(5)
  13.    >>> c.add_number(6)
  14.    >>> c.current_number
  15.    '056'
  16.    >>> c.plus()
  17.    >>> c.number_stack
  18.    [56]
  19.    >>> c.add_number(3)
  20.    >>> c.add_number(4)
  21.    >>> c.equal()
  22.    90
  23.    >>> c.add_number(6)
  24.    >>> c.add_number(7)
  25.    >>> c.minus()
  26.    >>> c.equal()
  27.    23
  28.    """
  29.     actions = {
  30.         '+': lambda x,y: x+y,
  31.         '-': lambda x,y: x-y
  32.     }
  33.     def __init__(self):
  34.         self.current_number = "0"
  35.         self.number_stack = []
  36.         self.action_stack = []
  37.  
  38.     def add_number(self, n):
  39.         self.current_number += str(n)
  40.  
  41.     def add_action(self, action):
  42.         self.number_stack.append(int(self.current_number))
  43.         self.current_number = "0"
  44.         self.action_stack.append(action)
  45.  
  46.     def plus(self):
  47.         self.add_action('+')
  48.  
  49.     def minus(self):
  50.         self.add_action('-')
  51.  
  52.     def equal(self):
  53.         self.number_stack.append(int(self.current_number))
  54.         result = 0
  55.         for ind, action in enumerate(self.action_stack):
  56.             result += self.actions[action](self.number_stack[ind], self.number_stack[ind+1])
  57.         self.current_number = "0"
  58.         self.number_stack = [result]
  59.         self.action_stack = []
  60.         return result
  61.  
  62. if __name__ == "__main__":
  63.     import doctest
  64.     doctest.testmod()