hrheingold

Testing Knowledge of Classes

Jun 18th, 2013
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.31 KB | None | 0 0
  1. import random
  2. from urllib import urlopen
  3. import sys
  4.  
  5. WORD_URL = "http://learncodethehardway.org/words.txt"
  6. WORDS = []
  7.  
  8. PHRASES = {
  9.     "class ###(###):":
  10.        "Make a class named ### that is-a ###.",
  11.     "class ###(object):\n\tdef __init__(self, ***)" :
  12.         "class ### has-a __init__ that takes self and *** parameters.",
  13.     "class ###(object):\n\tdef ***(self, @@@)":
  14.         "class ### has-a function named *** that takes self and @@@ parameters.",
  15.     "*** = ###()":
  16.         "Set *** to an instance of class ###.",
  17.     "***.***(@@@))":
  18.         "From *** get the *** function, and call it with paramters self, @@@.",
  19.     "***.*** = '***'":
  20.         "From *** get the *** attribute and set it to '***'."
  21. }
  22.  
  23. #do they want to drill phrases first
  24. PHRASE_FIRST = False
  25. if len(sys.argv) == 2 and sys.argv[1] == "english":
  26.     PHRASE_FIRST = True
  27.  
  28. #load up the words from the website
  29. for word in urlopen(WORD_URL).readlines():
  30.     WORDS.append(word.strip())
  31.  
  32. def convert(snippet, phrase):
  33.     class_names = [w.capitalize() for w in
  34.                    random.sample(WORDS, snippet.count("###"))]
  35.     other_names = random.sample(WORDS, snippet.count("***"))
  36.     results = []
  37.     param_names = []
  38.  
  39.     for i in range(0, snippet.count("@@@")):
  40.         param_count = random.randint(1,3)
  41.         param_names.append(', '.join(random.sample(WORDS, param_count)))
  42.  
  43.     for sentence in snippet, phrase:
  44.         result = sentence[:]
  45.  
  46.         # fake class names
  47.         for word in class_names:
  48.             result = result.replace("###", word, 1)
  49.  
  50.         # fake other names
  51.         for word in other_names:
  52.             result = result.replace("***", word, 1)
  53.  
  54.         # fake parameter lists
  55.         for word in param_names:
  56.             result = result.replace("@@@", word, 1)
  57.  
  58.         results.append(result)
  59.  
  60.     return results
  61.  
  62. # keep going until they hit CTRL-D
  63. try:
  64.     while True:
  65.         snippets = PHRASES.keys()
  66.         random.shuffle(snippets)
  67.  
  68.         for snippet in snippets:
  69.             phrase = PHRASES[snippet]
  70.             question, answer = convert(snippet, phrase)
  71.             if PHRASE_FIRST:
  72.                 question, answer = answer, question
  73.  
  74.             print question
  75.  
  76.             raw_input("> ")
  77.             print "ANSWER: %s\n\n" % answer
  78.  
  79. except EOFError:
  80.     print "\nBye"
Advertisement
Add Comment
Please, Sign In to add comment