lolamontes69

Python/ Random equation evolution on a friday night.

Jun 29th, 2013
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.25 KB | None | 0 0
  1. from random import randint
  2.  
  3. def produce_equation(magicnum):
  4.     total = 0
  5.     numlist = [(1.0),(2.0),(3.0),(4.0),(5.0),(6.0),(7.0),(8.0),(9.0)]
  6.     oplist = ['+','-','/','*']
  7.     count = 0
  8.     winner = 'a'*4000 # A high value so the first successful equation produced will get added.
  9.     corrects = 60
  10.     high = 16
  11.     for variablename in range(corrects):
  12.         while total != magicnum:
  13.             equa = ''
  14.             for a in range(randint(2,high)):
  15.                 equa += str(numlist[randint(0,8)])+' '+str(oplist[randint(0,3)])
  16.             while equa[-1] in oplist:
  17.                 if equa[-1] in oplist: equa = equa[:-1].strip() # Tidy operators from end of equation
  18.                 total = eval(equa)
  19.                 count += 1
  20.         print "\n********Generation",count,"********\n",equa,"produces",total
  21.         total = 0
  22.         if len(equa) < len(winner): winner = equa               # Selection of the 'fittest'.
  23.         high = len(winner)/4                                    # (Optimization)
  24.  
  25.     print "\n\n######################################################\n"
  26.     print "Shortest equation to get the value of",magicnum
  27.     print "From",corrects,"randomly generated correct equations is\n\n",winner,"\n"
  28.     print "######################################################"
  29.  
  30. magicnum = float(raw_input('Enter the magic number >'))
  31. if magicnum < 10: print "Are you just retarded?"
  32. else: produce_equation(magicnum)
  33.  
  34.  
  35. """ What is this?
  36.    *************
  37.    Enter a number at the prompt and the program will start generating random equations using the numbers 1-9 and the basic operators that will produce it. During the iterations any equation that produces the chosen number will be added to 'winner' if it is shorter than the last successful equation. The maximum length of the equation is modified to be the same length as the current shortest equation to optimise production.
  38.    The first shortest equation to produce the target sum, within successful attempts value 'corrects', is the winner.
  39.    
  40.    Notes: Operator execution order is Pythonesque.
  41.           This is not the best way of finding the shortest equation, hoping that random solutions will produce themselves from nowhere; a brute method would solve it much more accurately.
  42. """
Advertisement
Add Comment
Please, Sign In to add comment