Advertisement
Vermiculus

Untitled

Apr 8th, 2012
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 29.03 KB | None | 0 0
  1. def d(m, s):
  2.     raw_input(m.format(s))
  3.  
  4. def statement_contains(s, l):
  5.     """Checks to see if s (a list of words) contains an element in l"""
  6.     ####### {v : v \in s AND v \in l} != {}
  7.     return [v for v in s if v in l] != []
  8.  
  9. class Command:
  10.     ##token class to be executed in the kitchen
  11.     imperative = ""
  12.     imperativequalifier = ""
  13.     ing = ""
  14.     n = -1
  15.     p = -1
  16.  
  17.     def nth(self, a):
  18.         self.n = a
  19.     def pth(self, a):
  20.         self.p = a
  21.     def ingredient(self, a):
  22.         self.ing = a
  23.  
  24.     def __str__(self):
  25.         return self.imperative + " " + self.imperativequalifier + " " + self.ing + " " + str(self.n) + " " + str(self.p)
  26.  
  27. class Cookbook:
  28.     ##Class for parsing statements into command objects
  29.     a = "Take ingredient from refrigerator. \nPut ingredient into nth mixing bowl. \nPut ingredient into mixing bowl. \nAdd ingredient. \nAdd ingredient to mixing bowl. \nAdd ingredient to nth mixing bowl. \nRemove ingredient. \nRemove ingredient from mixing bowl. \nRemove ingredient from nth mixing bowl. \nCombine ingredient. \nCombine ingredient into mixing bowl. \nCombine ingredient into nth mixing bowl. \nDivide ingredient. \nDivide ingredient into mixing bowl. \nDivide ingredient into nth mixing bowl. \nAdd dry ingredients. \nAdd dry ingredients into mixing bowl. \nAdd dry ingredients into nth mixing bowl. \nLiquify ingredient. \nLiquify contents of the mixing bowl. \nLiquify contents of the nth mixing bowl. \nStir mixing bowl for num minutes. \nStir nth mixing bowl for num minutes. \nStir ingredient into the mixing bowl. \nStir ingredient into the nth mixing bowl. \nMix well. \nMix the mixing bowl well. \nMix the nth mixing bowl well. \nClean mixing bowl. \nClean nth mixing bowl. \nPour contents of the mixing bowl into baking dish \nPour contents of the nth mixing bowl the pth baking dish \nVerb the ingredient. \nVerb until verbed. \nVerb the ingredient until verbed. \nSet aside. \nServe with auxiliary-recipe. \nRefrigerate. \nRefrigerate for num hours. \nServes num."
  30.     l = list()
  31.     reserved = ['ingredient', "nth", "pth", "ingredient."]
  32.  
  33.     ##constructor initializes the list l
  34.     def __init__(self):
  35.         la = self.a.split("\n")
  36.        
  37.         for each in la:
  38.             self.l.append(each.split())
  39.  
  40.     ##verifies that a given ingredient has been declared
  41.     def ingredient(self, arg):
  42.         if(arg=="zuchinni"):
  43.             return arg
  44.  
  45.     ##verifies that a given number is a proper ordinal
  46.     ##returns an integer if it is
  47.     def nth(self, arg):
  48.         tailing = arg[len(arg)-2:len(arg)]
  49.         digits = arg[0:len(arg)-2]
  50.  
  51.         if(14 > int(digits[len(digits)-2:len(digits)]) > 10):
  52.             if(tailing=="th"):
  53.                 return digits
  54.         elif(int(digits[-1])==1):
  55.             if(tailing=="st"):
  56.                 return digits
  57.         elif(int(digits[-1])==2):
  58.             if(tailing=="nd"):
  59.                 return digits
  60.         elif(int(digits[-1])==3):
  61.             if(tailing=="rd"):
  62.                 return digits
  63.         elif(tailing=="th"):
  64.                 return digits
  65.         raise exception
  66.  
  67.     def pth(self, arg):
  68.         return nth(arg)
  69.  
  70.     def num(self, arg):
  71.         return int(arg)
  72.  
  73.     ##helper method for test that compares an individual template against the argument
  74.     def testDeep(self, arg, template):
  75.         for y in xrange(0, len(template)):
  76.             if(template[y] in self.reserved):
  77.                 func = getattr(self, template[y])
  78.                 try:    
  79.                     arg[y] = func(arg[y])
  80.                 except:
  81.                     return False
  82.             else:
  83.                 if(template[y] != arg[y]):
  84.                     return False
  85.                
  86.         return True
  87.  
  88.     ##helper method for test which converts the result into a command object
  89.     def makeCommand(self, passOn):
  90.         c = Command()
  91.         c.imperative = str(passOn[0][0])
  92.         c.imperativequalifier = str(passOn[0][1])
  93.        
  94.         for x in xrange(0, len(passOn[1])):
  95.             try:
  96.                 getattr(c, passOn[1][x])(passOn[0][x])
  97.             except:
  98.                 pass
  99.         return c
  100.  
  101.     ##turns a valid chef string into a command object
  102.     ##checks syntax against a list of valid template statements
  103.     def test(self, arg):
  104.        
  105.         testme = arg.split()
  106.         passOn = ()
  107.         for x in xrange(0, len(self.l)):
  108.             template = (self.l[x])
  109.             if(len(testme) == len(template)):
  110.                 if(self.testDeep(testme, template)==True):
  111.                     ##remove the period from the template (will interfere with getattr(command, s) in case "Add ingredient.")
  112.                     template[-1] = template[-1][0:len(template[-1])-1]
  113.                     passOn = (testme, template)
  114.                     break
  115.                 else:
  116.                     pass
  117.         m = self.makeCommand(passOn)
  118.         return m
  119.  
  120. class Kitchen:
  121.     """A facility for interpreting the esoteric language 'Chef'."""
  122.     class Error(Exception):
  123.         def __init__(self, title, message):
  124.             self.title = title
  125.             self.message = message
  126.    
  127.     def __init__(self, recipe="", master=None):
  128.         """Constructor
  129.        
  130.        Initializes lists for mixing bowls and baking dishes and
  131.            begins evaluating the recipe (taken in as a string).
  132.        """
  133.         import Bowl
  134.        
  135.         self.food = list()
  136.         with open('food.txt', 'r') as f:
  137.             for line in f:
  138.                 self.food.append(line[:-1])
  139.        
  140.         if master is None:
  141.             from collections import deque
  142.             self.ingredients = dict()    # contains a dictionary of ingredients
  143.             self.mixing_bowls = list()    # list of mixing bowls, stack-style
  144.             self.baking_dishes = list() # list of baking dishes, stack-style
  145.             self.stdin = deque()        # Our very own stdin! So we *could* take in more than one character at a time from what the user sees
  146.             self.stdout = deque()        # Well, if we have an stdin, might as well have an stdout. May make life easier.
  147.             self.history = list()        # Contains a list (stack) of (func, arg) tuples, most-recent last. Useful for looping.
  148.        
  149.         #handles a copy constructor
  150.         elif hasattr(master, 'ingredients') and hasattr(master, 'mixing_bowls') and hasattr(master, 'baking_dishes') and hasattr(master, 'stdin') and hasattr(master, 'stdout') and hasattr(master, 'history'):
  151.             self.ingredients = master.ingredients
  152.             self.mixing_bowls = master.mixing_bowls
  153.             self.baking_dishes = master.baking_dishes
  154.             self.stdin = master.stdin
  155.             self.stdout = master.stdout
  156.            
  157.             #self.history        = master.history
  158.             # This statement may interfere with correct looping.
  159.             #
  160.             # Note that how we are storing the history right now allows me to say things like this:
  161.             #
  162.             # >>> self.history.append(self.take, ['pizza', 'from', 'refrigerator'])
  163.             # >>> last_cmd = self.history[-1]
  164.             # (self.take, ['pizza', 'from', 'refrigerator'])
  165.             # >>> last_cmd[0](last_cmd[1])
  166.             # (does that last command again)
  167.  
  168.     def do(self, s):
  169.         """Does an arbitrary operation from a valid Chef string
  170.        
  171.        The command must be the first word, case sensitive.
  172.        If the command does not exist, None is returned.
  173.        The rest of the string is passed to the desired function as a list.
  174.        
  175.        Author: Sean
  176.        """
  177.        
  178.         def isVerbStatement(li):
  179.             return len(li) == 3 and li[1] == "the" and li[2] in [v + "." for v in self.ingredients]
  180.        
  181.         t = s.split()
  182.         try:
  183.             if s == "Ingredients.":
  184.                 self._do_ingredients()
  185.             elif len(t) < 2:
  186.                 raise Kitchen.Error("Syntax Error", "Commands must have at least two tokens.")
  187.             elif hasattr(self, t[0]):
  188.                 return getattr(self, t[0])(t[1:])
  189.             elif isVerbStatement(t): # the word may be a verb
  190.                 print "Verbing!"
  191.                 print "Verb:", t[0]
  192.             else:
  193.                 print "No such attribute"
  194.            
  195.         except Kitchen.Error as (title, message):
  196.             import sys
  197.             sys.excepthook(*sys.exc_info())
  198.            
  199.             print ""
  200.             print "{t}: {m}\a".format(t=title, m=message)
  201.             return False
  202.    
  203.     def _do_ingredients(self):
  204.         """Author: Sean"""
  205.         s = raw_input()
  206.         measures = {"ml":"wet", "l":"wet", "dash":"wet", "dashes":"wet", "g":"dry", "kg":"dry", "pinch":"dry", "pinches":"dry", "cup":None, "cups":None, "teaspoon":None, "teaspoons":None, "tablespoon":None, "tablespoons":None, None:None}
  207.         types = {"heaped":"dry", "level":"dry"}
  208.         while s != "":
  209.             s = self._get_ingredient(s, measures, types)
  210.             self.ingredients[s[0]] = (s[1], s[2])
  211.             s = raw_input()
  212.        
  213.     def __repr__(self):
  214.         """Author: Sean"""
  215.         return "  Ingridients: {ing}\n Mixing Bowls: {mb}\nBaking Dishes: {bd}\n Input Buffer: {ip}\nOutput Buffer: {op}".format(ing=str(self.ingredients), mb=str(self.mixing_bowls), bd=str(self.baking_dishes), ip=str(self.stdin), op=str(self.stdout))
  216.    
  217.     # Have this function declare a multidimensional array of strings according to differing degrees of messiness
  218.     # so it can be called
  219.     # ...    return arr[len(mixing_bowls) // 5][len(baking_dishes) // 5]
  220.     # or something like that.
  221.     def __str__(self):
  222.         """Author: Sean"""
  223.         return "You see a mess of utensils; you have a lot of work yet to do."
  224.    
  225.     def _get_bowl(self, s):
  226.         """Returns the mixing bowl specified by this string.
  227.        
  228.        This method searches the string provided for the mixing bowl needed:
  229.        >>> getDish("Pour the 3rd mixing bowl into the 2nd baking dish.")
  230.        3
  231.        
  232.        If no ordinal for a mixing bowl is specified, it defaults to 1:
  233.        >>> getDish("Put zucchinis into the mixing bowl.")
  234.        1
  235.        
  236.        If there is no mention of any mixing bowls, this function returns None:
  237.        >>> getDish("I've got poop for brains.")
  238.        None
  239.        
  240.        Author:
  241.        """
  242.         pass
  243.         return 0
  244.    
  245.     def _get_dish(self, s):
  246.         """Returns the baking dish specified by this string.
  247.        
  248.        This method searches the string provided for the baking dish needed:
  249.        >>> getDish("Pour the 3rd mixing bowl into the 2nd baking dish")
  250.        2
  251.        
  252.        If no ordinal for a baking dish is specified, it defaults to 1:
  253.        >>> getDish("Pour the 3rd mixing bowl into the baking dish")
  254.        1
  255.        
  256.        If there is no mention of any baking dishes, this function returns None:
  257.        >>> getDish("I've got poop for brains.")
  258.        None
  259.        
  260.         Author:
  261.        """
  262.         pass
  263.         return 0
  264.    
  265.     def _get_ingredient(self, item, measures, types):
  266.         """Takes exactly one string, a dictionary of valid measures, and a dictionary of valid measure-types and returns (name, value, type)
  267.        
  268.        Author: Sean
  269.        """
  270.         name = type = value = explicit_type = None
  271.         s = item.split()
  272.         if len(s) < 1:
  273.             raise Kitchen.Error("Ingredient Error", "Blank line encountered.")
  274.         if s[0].isdigit():
  275.             value = int(s[0])
  276.             if statement_contains(s[1:], measures):
  277.                 if s[1] in types:
  278.                     type = types[s[1]]
  279.                     name = s[2:]
  280.                 elif s[1] in measures:
  281.                     type = measures[s[1]]
  282.                     name = s[2:]
  283.                 else:
  284.                     raise Kitchen.Error("Ingredient Error", "Illegal value or ingredient encountered.")
  285.             else:
  286.                 name = s[1:]
  287.         elif s[0] in measures:
  288.             type = measures[s[0]]
  289.             name = s[1:]
  290.             if name == []:
  291.                 raise Kitchen.Error("Ingredient Error", "Must specifiy an ingredient name.")    
  292.             elif s[0] in types:
  293.                 if s[1] in measures:
  294.                     type = types[type]
  295.                     name = s[2:]
  296.                     if name == []:
  297.                         raise Kitchen.Error("Ingredient Error", "Must specifiy an ingredient name.")
  298.             else:
  299.                 raise Kitchen.Error("Ingredient Error", "Must specifiy measure for type.")
  300.         else:
  301.             name = s
  302.         name = ' '.join(name)
  303.         return (name, value, type)
  304.    
  305.     def _get_ingredients(self, l):
  306.         """Takes a list l of ingredient-statements and populates the ingredients.
  307.        
  308.        Author: Sean
  309.        """
  310.        
  311.         if len(l) < 1:
  312.             raise Kitchen.Error("Ingredient Error", "Must have at least one ingredient.")
  313.        
  314.         measures = {"ml":"wet", "l":"wet", "dash":"wet", "dashes":"wet", "g":"dry", "kg":"dry", "pinch":"dry", "pinches":"dry", "cup":None, "cups":None, "teaspoon":None, "teaspoons":None, "tablespoon":None, "tablespoons":None, None:None}
  315.         types = {"heaped":"dry", "level":"dry"}
  316.        
  317.         for item in l:
  318.             ing = self._get_ingredient(item, measures, types)
  319.             self.ingredients[ing[0]] = (ing[1], ing[2])
  320.  
  321.     bowl_index = None
  322.     dish_index = None
  323.     ingr_index = None
  324.     comd_index = None
  325.     auxc_index = None
  326.     def Take(self, s):
  327.         """Take (ingredient) from refrigerator.
  328.        
  329.        This reads a numeric value from STDIN into
  330.            the ingredient named, overwriting any
  331.            previous value.
  332.            
  333.        Author: Sean
  334.        """
  335.        
  336.         def isFood(s):
  337.             return not s.isdigit()
  338.        
  339.         ingredient_name = ' '.join(s[:-2])
  340.        
  341.         if not isFood(ingredient_name):
  342.             raise Kitchen.Error("Name Error", "You can't eat {}".format(ingredient_name))
  343.             return False
  344.         elif s[-1] != "refrigerator." or s[-2] != "from":
  345.             raise Kitchen.Error("Syntax Error", "Take <ingredient> from refrigerator.")
  346.             return False
  347.        
  348.         elif len(self.stdin) is 0:
  349.             _in = raw_input("Press enter after input: ")
  350.             if _in.isdigit(): # if the entire input can be parsed as a single number
  351.                 self.stdin.append(int(_in)) # append that number to the buffer
  352.                 self.ingredients[ingredient_name] = self.stdin.popleft()
  353.             else:
  354.                 for char in _in: # otherwise, append the integer value of each character entered to the buffer.
  355.                     self.stdin.append(ord(char))
  356.                 self.ingredients[ingredient_name] = self.stdin.popleft()
  357.        
  358.         else:
  359.             self.ingredients[ingredient_name] = self.stdin.popleft()
  360.        
  361.         self.history.append((self.take, s))
  362.        
  363.         return True
  364.    
  365.     def Put(self, s):
  366.         """Put (ingredient) into the [nth] mixing bowl.
  367.        
  368.        This puts the ingredient into the nth mixing bowl.
  369.        """
  370.         self.mixing_bowls.append(self.ingredients[s[ingr_index]])
  371.         return True
  372.    
  373.     def Fold(self, s):
  374.         """Fold (ingredient) into [nth] mixing bowl.
  375.        
  376.        This removes the top value from the nth mixing bowl and places it in the ingredient.
  377.        """
  378.         self.ingredients[s[ingr_index]] = self.mixing_bowls.pop()
  379.         return True
  380.    
  381.     def Add(self, s):
  382.         """Two uses.
  383.        
  384.        
  385.        Add (ingredient) [to [nth] mixing bowl].
  386.            This adds the value of ingredient to the
  387.            value of the ingredient on top of the
  388.            nth mixing bowl and stores the result
  389.            in the nth mixing bowl.
  390.        
  391.        Add dry ingredients [to [nth] mixing bowl].
  392.            This adds the values of all the dry ingredients
  393.            together and places the result into the
  394.            nth mixing bowl.
  395.        """
  396.         if s[auxc_index]:
  397.             self.mixing_bowls[s[bowl_index]].append(sum([ingr for ingr in self.ingredients if ingr[0] is 'dry']))
  398.         else:
  399.             self.mixing_bowls[s[bowl_index]][-1] += self.ingredients[s[ingr_index]]
  400.         return False
  401.    
  402.     def Remove(self, s):
  403.         """Remove ingredient [from [nth] mixing bowl].
  404.        
  405.        This subtracts the value of ingredient from
  406.            the value of the ingredient on top of the
  407.            nth mixing bowl and stores the result in
  408.            the nth mixing bowl.
  409.        """
  410.         self.mixing_bowls[s[bowl_index]][-1] -= self.ingredients[s[ingr_index]]
  411.         return True
  412.    
  413.     def Combine(self, s):
  414.         """Combine ingredient [into [nth] mixing bowl].
  415.        
  416.        This multiplies the value of ingredient by
  417.            the value of the ingredient on top of
  418.            the nth mixing bowl and stores the result
  419.            in the nth mixing bowl.
  420.        """
  421.         self.mixing_bowls[s[bowl_index]][-1] *= self.ingredients[s[ingr_index]]
  422.         return True
  423.    
  424.     def Divide(self, s):
  425.         """Divide ingredient [into [nth] mixing bowl].
  426.        
  427.        This divides the value of ingredient into
  428.            the value of the ingredient on top of
  429.            the nth mixing bowl and stores the result
  430.            in the nth mixing bowl.
  431.        """
  432.         self.mixing_bowls[s[bowl_index]][-1] /= self.ingredients[s[ingr_index]]
  433.         return False
  434.    
  435.     def Liquefy(self, s):
  436.         """Two uses.
  437.        
  438.        
  439.        Liquefy | Liquify ingredient.
  440.            This turns the ingredient into a liquid,
  441.            i.e. a Unicode character for output purposes.
  442.            
  443.            (Note: The original specification used
  444.            the word "Liquify", which is a spelling
  445.            error. "Liquify" is deprecated.
  446.            Use "Liquefy" in all new code.)
  447.        
  448.        Liquefy | Liquify contents of the [nth] mixing bowl.
  449.            This turns all the ingredients in the nth mixing bowl
  450.            into a liquid, i.e. a Unicode characters for
  451.            output purposes.
  452.        """
  453.         pass
  454.         return False
  455.    
  456.     def Stir(self, s):
  457.         """Two uses.
  458.        
  459.        
  460.        Stir [the [nth] mixing bowl] for number minutes.
  461.            This "rolls" the top number ingredients
  462.            in the nth mixing bowl, such that the
  463.            top ingredient goes down that number of
  464.            ingredients and all ingredients above it
  465.            rise one place. If there are not that many
  466.            ingredients in the bowl, the top ingredient
  467.            goes to tbe bottom of the bowl and all
  468.            the others rise one place.
  469.        
  470.        Stir ingredient into the [nth] mixing bowl.
  471.            This rolls the number of ingredients
  472.            in the nth mixing bowl equal to
  473.            the value of ingredient, such that
  474.            the top ingredient goes down that number
  475.            of ingredients and all ingredients above
  476.            it rise one place. If there are not that
  477.            many ingredients in the bowl, the top
  478.            ingredient goes to tbe bottom of the bowl
  479.            and all the others rise one place.
  480.        """
  481.         pass
  482.         return False
  483.    
  484.     def Mix(self, s):
  485.         """Mix [the [nth] mixing bowl] well.
  486.        
  487.        This randomises the order of the
  488.            ingredients in the nth mixing bowl.
  489.        """
  490.         import random
  491.         random.shuffle(self.mixing_bowls[s[bowl_index]])
  492.         return True
  493.    
  494.     def Clean(self, s):
  495.         """Clean [nth] mixing bowl.
  496.        
  497.        This removes all the ingredients
  498.            from the nth mixing bowl.
  499.        
  500.        Author: Sean
  501.        """
  502.         if len(s) > 3 or s[1] != 'mixing' or s[2] != 'bowl.':
  503.             return False
  504.        
  505.         num = self._get_dish(' '.join(s))
  506.         if num == None:
  507.             return False
  508.        
  509.         self.mixing_bowls[num] = list()
  510.         return True
  511.    
  512.     def Pour(self, s):
  513.         """Pour contents of the [nth] mixing bowl into the [pth] baking dish.
  514.        
  515.        This copies all the ingredients from
  516.            the nth mixing bowl to the
  517.            pth baking dish, retaining the order
  518.            and putting them on top of anything
  519.            already in the baking dish.
  520.        """
  521.         self.baking_dishes[s[dish_index]].extend(self.mixing_bowls[s[bowl_index]])
  522.         return True
  523.    
  524.     def Set(self, s):
  525.         """Set aside.
  526.        
  527.        This causes execution of the innermost
  528.            loop in which it occurs to end
  529.            immediately and execution
  530.            to continue at the statement after
  531.            the "until".
  532.        """
  533.         pass
  534.         return False
  535.    
  536.     def Serve(self, s):
  537.         """Two uses.
  538.        
  539.        
  540.        Serve with auxiliary-recipe.
  541.            This invokes a sous-chef to immediately
  542.            prepare the named auxiliary-recipe.
  543.            The calling chef waits until the sous-chef
  544.            is finished before continuing.
  545.            
  546.            See the section on auxiliary recipes below.
  547.        
  548.        Serves number-of-diners.
  549.            This statement writes to STDOUT the contents
  550.            of the first number-of-diners baking dishes.
  551.            It begins with the 1st baking dish,
  552.            removing values from the top one by one and
  553.            printing them until the dish is empty,
  554.            then progresses to the next dish, until all
  555.            the dishes have been printed.
  556.            
  557.            The serves statement is optional, but is
  558.            required if the recipe is to output anything!
  559.        """
  560.         for dish in self.baking_dishes:
  561.             while dish:
  562.                 self.stdout.append(dish.pop())
  563.         return False
  564.    
  565.     def Refrigerate(self, s):
  566.         """Refrigerate [for number hours].
  567.        
  568.        This causes execution of the recipe
  569.            in which it appears to end immediately.
  570.            If in an auxiliary recipe, the auxiliary
  571.            recipe ends and the sous-chef's first
  572.            mixing bowl is passed back to the calling
  573.            chef as normal. If a number of hours is
  574.            specified, the recipe will print out its
  575.            first number baking dishes before ending.
  576.        """
  577.         pass
  578.         return False
  579.    
  580.     def _verb_(self, s):
  581.         """Takes care of VERB until VERBED.
  582.        Not a clue on how to do this yet.
  583.        
  584.        IDEA!
  585.         -- Create a new kitchen
  586.         -- keep reading in commands until verbed
  587.         -- pass commands to a new kitchen
  588.         -- once we reach 'until verbed', execute the history again
  589.         -- keep executing until condition is zero
  590.        """
  591.  
  592.         pass
  593.  
  594. def read_recipe(filepath):
  595.     """Loads the given *.chef file and does initial parsing.
  596.    
  597. This method will parse the given filename
  598.  
  599. See http://docs.python.org/library/doctest.html#module-doctest
  600. So much awesome.
  601.  
  602. Example output:
  603. >>> print read_recipe("/hw.chef")
  604. ["Hello World Souffle", "This recipe prints the immortal words "Hello world!", in a basically brute force way. It also makes a lot of food for one person.", "72 g haricot beans
  605. 101 eggs
  606. 108 g lard
  607. 111 cups oil
  608. 32 zucchinis
  609. 119 ml water
  610. 114 g red salmon
  611. 100 g dijon mustard
  612. 33 potatoes", "Put potatoes into the mixing bowl. Put dijon mustard into the mixing bowl. Put lard into the mixing bowl. Put red salmon into the mixing bowl. Put oil into the mixing bowl. Put water into the mixing bowl. Put zucchinis into the mixing bowl. Put oil into the mixing bowl. Put lard into the mixing bowl. Put lard into the mixing bowl. Put eggs into the mixing bowl. Put haricot beans into the mixing bowl. Liquefy contents of the mixing bowl. Pour contents of the mixing bowl into the baking dish.
  613.  
  614. Serves 1."]
  615.    """
  616.     pass
  617.  
  618. # takes the instruction string from earlier and splits it into statements
  619. def preheat(method):
  620.     """Takes all of the statements (as a single string) under Method and begins the parsing process.
  621.    
  622. This method returns a list of simple tuples where the first element is the command
  623. and the second element is the source string. The output of this method is intended
  624. for calling Mom.
  625.    """
  626.     pass
  627.  
  628. def gather(ingredients):
  629.     """Return a dictionary of ingredients from the given string.
  630.    
  631. The dictionary returned will contain the ingredient as a string
  632. mapped to a tuple, where the first element indicates if it is dry or wet
  633. and the second element denotes its numeric value.
  634.  
  635. Example:
  636.    {'apple':('dry', 96), 'oil':('wet', 59), etc.}
  637.    """
  638.     pass
  639.  
  640. # Because we all know her handwriting is horrid.
  641. # we may be able to make this fun by using advanced features of functions in Python
  642. def callMom(method):
  643.     """Takes a list of command-string tuples and returns a list of pure command-tuples.
  644.    
  645. Following is a list of commands and descriptions, following the pattern
  646. (<command>,     <arguments>)    - execute <command> with <arguments>
  647. where the default value of ## is exactly 1 (signifying the mixing bowl index
  648. and where # is a plain number
  649.  
  650. For overloaded commands, use hasattr() for type checking
  651.  
  652. ('take',     'ingredient')                   - get one character from the user and place its numeric value into ingredient
  653. ('put',         'ingredient', ##)               - push the ingredient onto the ##th mixing bowl
  654. ('fold',     'ingredient', ##)               - pop the ##th mixing bowl into the ingredient
  655. ('add',         'ingredient', ##)               - peek at the ##th mixing bowl and add (numerically) ingredient to it
  656. ('remove',     'ingredient', ##)               - peek at the ##th mixing bowl and subtract (numerically) ingredient from it
  657. ('combine',     'ingredient', ##)               - peek at the ##th mixing bowl and multiply (numerically) ingredient with it
  658. ('divide',     'ingredient', ##)               - peek at the ##th mixing bowl and divide (numerically) ingredient from it
  659. ('add', ##)                                   - takes all of the dry ingredients and places the sum into the #th mixing bowl
  660. ('liquefy',     'ingredient')                   - transform the ingredient into its Unicode equivalent
  661. ('liquefy',      ##)                           - transform the contents of the ##th mixing bowl into their Unicode equivalents
  662. ('stir',      ##,            #)               -
  663. ('stir',     'ingredient',    ##)               -
  664. ('mix',           ##)                           - randomize the order of the ##th mixing bowl
  665. ('clean',       ##)                           - pop the ##th mixing bowl until empty
  666. ('loop',      'verb',       'ingredient')   - See after.
  667. ('next',      'verb',       'ingredient')   - See after.
  668. ('exit')                                   - Continues execution after the next 'next'
  669. ('serve',      'recipe')                       - Invokes the execution of another recipe
  670. ('fridge')                                   - Ends execution immediately and returns the first mixing bowl
  671. ('fridge, #)                               - Print out the first # baking dishes before calling ('fridge')
  672.  
  673. ('serves', #)                               - Pops and prints each baking dish in succession. This is the last command.
  674.  
  675. Note that everything that follows the 'serve' command is an auxiliary recipe.
  676.  
  677. Looping:
  678.   With the 'loop' command, if the ingredient is non-zero, continue execution until reaching the 'next' command. If the ingredient is zero, continue execution after a matching 'next'.
  679.   At the 'next' command, if an ingredient is given (defaulting to the ingredient given by 'loop'), continue execution at the previous 'loop' if the given ingredient is non-zero. If the ingredient is zero, simply continue.
  680.  
  681. The output of this method is intended for cooking.
  682.    """
  683.    
  684.     pass
  685.  
  686. def loadVerbs(path):
  687.     """Return a list verbs and their past-tense form read from a file with the given path.
  688.        
  689. The return will be a list of tuples containing two strings:
  690. the first being the infinite stem, the second being the simple past.
  691.  
  692. Example:
  693.    [("sift","sifted"),("boil","boiled"), ...]
  694.    """
  695.     pass
  696.  
  697. def loadFoods(path):
  698.     """ Returns a simple list of foods read from a file with the given path."""
  699.     pass
  700.  
  701. # executes a list of commands
  702. def cook(ingredients, method):
  703.     """Execute the list of commands given using the ingredients provided.
  704.    
  705. Execute the given list of commands in the format given by calling Mom.
  706. It is an error if a given command does not exist.
  707.    """
  708.    
  709.     ###################################################
  710.    
  711.     # iterate through the commands with complete control over position
  712.     #    (python's for-each loop does not give you any control)
  713.     cmd_index = 0
  714.     while cmd_index < len(method):
  715.         cmd_index += 1
  716.         pass
  717.    
  718.     pass
  719.  
  720.  
  721. ########################################
  722.  
  723.  
  724. print statement_contains("hello world".split(), ["hello", "poop"])
  725.  
  726. hat = 'c= '
  727.  
  728. kills = ["quit", "exit", "stop", "kill", "term"]
  729.  
  730. k = Kitchen()
  731.  
  732. cmd = raw_input(hat)
  733. while cmd[:4] not in kills: # checks the first four letters
  734.     k.do(cmd)
  735.     print repr(k)
  736.     cmd = raw_input(hat)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement