Advertisement
russ123

Find Sequence Function - Refactored

Nov 19th, 2012
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.08 KB | None | 0 0
  1. """
  2. Not finished!
  3. """
  4.  
  5. from random import choice, random
  6.  
  7.  
  8. class ExpressionFormConstructor(object):
  9.     """
  10.    BNF specificaton:
  11.        <expr_form>     ::=     (<operator>, <operand>, <operand>)
  12.        <operator>      ::=     "+" | "-" | "*" | "/" | "^"
  13.        <operand>       ::=     "e" | "c" | "x"
  14.        "e"             ::=     <expr_form>
  15.        "c"             ::=     int
  16.        "x"             ::=     x
  17.    """
  18.     non_terminating_expr_forms = (
  19.         ('+', 'x', 'e'),
  20.         ('-', 'x', 'e'),
  21.         ('*', 'x', 'e'),
  22.         ('/', 'x', 'e'))
  23.  
  24.     terminating_expr_forms = (
  25.         ('+', 'x', 'c'),
  26.         ('-', 'x', 'c'),
  27.         ('*', 'x', 'c'),
  28.         ('/', 'x', 'c'),
  29.         ('^', 'x', 'c'))
  30.        
  31.     all_expr_forms = non_terminating_expr_forms + terminating_expr_forms
  32.  
  33.     def rand_form(self, depth=0):
  34.         """
  35.        rand_form() -> tuple(expr_form), list(constants)
  36.        depth refers to maximum nested depth of expr_form
  37.        """
  38.         constants = []
  39.         if depth is 0:
  40.             expr_form = list(choice(self.terminating_expr_forms))
  41.         else:
  42.             expr_form = list(choice(self.all_expr_forms))
  43.  
  44.         if expr_form[1] is 'c':
  45.             constants.append(0)
  46.         elif expr_form[1] is 'e':
  47.             expr_form[1], con = self.rand_form(depth - 1)
  48.             constants.extend(con)
  49.         else:
  50.             pass
  51.  
  52.         if expr_form[2] is 'c':
  53.             constants.append(0)
  54.         elif expr_form[2] is 'e':
  55.             expr_form[2], con = self.rand_form(depth - 1)
  56.             constants.extend(con)
  57.         else:
  58.             pass
  59.         return tuple(expr_form), constants
  60.  
  61.  
  62. class ExpressionForm(object):
  63.  
  64.     symb_to_op = {'+':lambda a, b: a + b,
  65.                   '-':lambda a, b: a - b,
  66.                   '*':lambda a, b: a * b,
  67.                   '/':lambda a, b: float(a) / b,
  68.                   '^':pow}
  69.  
  70.     def __init__(self, expr_form, constants):
  71.         self.expr_form = expr_form
  72.         self.constants = constants # number of constants.
  73.         self.population = [] # each individual is a unique tuple of constants.
  74.         self.graveyard = set() # contains hash values for failed individuals.
  75.  
  76.     def __str__(self, expr_form=None, root=True):
  77.         expr_form = self.expr_form if expr_form is None else expr_form
  78.         symb, A, B = expr_form
  79.         A = A if A in 'cx' else self.__str__(A, False)
  80.         B = B if B in 'cx' else self.__str__(B, False)
  81.         return ('%s %s %s' if root else '(%s %s %s)') % (A, symb, B)
  82.  
  83.     def evaluate(self, x, ind, expr=None, c=0):
  84.         """
  85.        x -> int, ind -> from self.population
  86.        """
  87.         symb, A, B = expr if expr else self.expr_form
  88.         op = self.symb_to_op[symb]
  89.         root = True if expr is None else False
  90.  
  91.         if A is 'c':
  92.             A = ind[c]
  93.             c += 1
  94.         elif A is 'x':
  95.             A = x
  96.         else: # A is an expr_form
  97.             A, c = self.evaluate(x=x, ind=ind, expr=A, c=c)
  98.  
  99.         if B is 'c':
  100.             B = ind[c]
  101.             c += 1
  102.         elif B is 'x':
  103.             B = x
  104.         else: # B is an expr_form
  105.             B, c = self.evaluate(x=x, ind=ind, expr=B, c=c)
  106.  
  107.         return op(A, B) if root else (op(A, B), c)
  108.  
  109.  
  110. # ---------- testing ---------->
  111.  
  112.  
  113.  
  114. ##from random import randint
  115. ##
  116. ##Constructor = ExpressionFormConstructor()
  117. ##
  118. ##def test():
  119. ##    Expr = ExpressionForm(*Constructor.rand_form(3))
  120. ##
  121. ##    # populate
  122. ##    for ind in range(100):
  123. ##        Expr.population.append(tuple([randint(1, 10) for constant in Expr.constants]))
  124. ##
  125. ##    # test and remove error prone individuals
  126. ##    for ind in range(len(Expr.population)):
  127. ##        try:
  128. ##            print [Expr.evaluate(x, Expr.population[ind]) for x in range(10)]
  129. ##        except (OverflowError, ZeroDivisionError, ValueError) as err:
  130. ##            print err
  131. ##            Expr.population[ind] = False
  132. ##    Expr.population = [ind for ind in Expr.population if ind]
  133. ##    print "lost:", 100 - len(Expr.population), "individuals"
  134. ##
  135. ##while True:
  136. ##    raw_input()
  137. ##    test()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement