Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

added Homeworks #1-#7 from Unit 5

  • Loading branch information...
commit d10655b44271dd181deea0199a5a24c28255639f 1 parent 7e2d0c0
authored April 12, 2012
BIN  Unit5/.DS_Store
Binary file not shown
17  Unit5/5_6_short.py
... ...
@@ -0,0 +1,17 @@
  1
+def new_procedure(htable, key, update):
  2
+    bucket = hashtable_get_bucket(htable, key)
  3
+    for entry in bucket:
  4
+        if entry[0] == key and update == None:
  5
+            return entry[1]
  6
+        elif entry[0] == key and update != None:
  7
+             entry[1] = update 
  8
+             return
  9
+    if update != None:
  10
+        bucket.append([key, update])
  11
+    return None
  12
+
  13
+def hashtable_update(htable, key, value):
  14
+    new_procedure(htable, key, value)
  15
+
  16
+def hashtable_lookup(htable, key):
  17
+    return new_procedure(htable, key, None)
76  Unit5/hw5_3.py
... ...
@@ -0,0 +1,76 @@
  1
+#Dictionaries of Dictionaries (of Dictionaries)
  2
+
  3
+#The next several questions concern the data structure below for keeping 
  4
+#track of Udacity's courses (where all of the values are strings):
  5
+  
  6
+#    { <hexamester>, { <class>: { <property>: <value>, ... },
  7
+#                                     ... },
  8
+#      ... }
  9
+
  10
+#For example,
  11
+
  12
+courses = {
  13
+    'feb2012': { 'cs101': {'name': 'Building a Search Engine',
  14
+                           'teacher': 'Dave',
  15
+                           'assistant': 'Peter C.'},
  16
+                 'cs373': {'name': 'Programming a Robotic Car',
  17
+                           'teacher': 'Sebastian',
  18
+                           'assistant': 'Andy'}},
  19
+    'apr2012': { 'cs101': {'name': 'Building a Search Engine',
  20
+                           'teacher': 'Dave',
  21
+                           'assistant': 'Sarah'},
  22
+                 'cs212': {'name': 'The Design of Computer Programs',
  23
+                           'teacher': 'Peter N.',
  24
+                           'assistant': 'Andy',
  25
+                           'prereq': 'cs101'},
  26
+                 'cs253': {'name': 'Web Application Engineering - Building a Blog',
  27
+                           'teacher': 'Steve',
  28
+                           'prereq': 'cs101'},
  29
+                 'cs262': {'name': 'Programming Languages - Building a Web Browser',
  30
+                           'teacher': 'Wes',
  31
+                           'assistant': 'Peter C.',
  32
+                           'prereq': 'cs101'},
  33
+                 'cs373': {'name': 'Programming a Robotic Car',
  34
+                           'teacher': 'Sebastian'},
  35
+                 'cs387': {'name': 'Applied Cryptography',
  36
+                           'teacher': 'Dave'}},
  37
+    'jan2044': { 'cs001': {'name': 'Building a Quantum Holodeck',
  38
+                           'teacher': 'Dorina'},
  39
+                        'cs003': {'name': 'Programming a Robotic Robotics Teacher',
  40
+                           'teacher': 'Jasper'},
  41
+                     }
  42
+    }
  43
+
  44
+
  45
+#For the following questions, you will find the
  46
+#        for <key> in <dictionary>:
  47
+#                   <block>
  48
+#construct useful.  This loops through the key values in the Dictionary.  For
  49
+#example, this procedure returns a list of all the courses offered in the given
  50
+#hexamester:
  51
+
  52
+def courses_offered(courses, hexamester):
  53
+    res = []
  54
+    for c in courses[hexamester]:
  55
+        res.append(c)
  56
+    return res
  57
+
  58
+#Define a procedure, is_offered(courses, course, hexamester), that returns True
  59
+#if the input course is offered in the input hexamester, and returns False
  60
+#otherwise.  For example,
  61
+
  62
+#print is_offered(courses, 'cs101', 'apr2012') => True
  63
+#print is_offered(courses, 'cs003', 'apr2012') => False
  64
+
  65
+#(Note: it is okay if your procedure produces an error if the input hexamester is not included in courses.  
  66
+#For example, is_offered(courses, 'cs101', 'dec2011') can produce an error.)
  67
+
  68
+def is_offered(courses, course, hexamester):
  69
+    try:
  70
+        if courses[hexamester][course]:
  71
+            return True
  72
+    except KeyError: 
  73
+        return False
  74
+
  75
+print is_offered(courses, 'cs003', 'apr2012') 
  76
+ 
72  Unit5/hw5_4.py
... ...
@@ -0,0 +1,72 @@
  1
+#Dictionaries of Dictionaries (of Dictionaries)
  2
+
  3
+#The next several questions concern the data structure below for keeping 
  4
+#track of Udacity's courses (where all of the values are strings):
  5
+  
  6
+#    { <hexamester>, { <class>: { <property>: <value>, ... },
  7
+#                                     ... },
  8
+#      ... }
  9
+
  10
+#For example,
  11
+
  12
+courses = {
  13
+    'feb2012': { 'cs101': {'name': 'Building a Search Engine',
  14
+                           'teacher': 'Dave',
  15
+                           'assistant': 'Peter C.'},
  16
+                 'cs373': {'name': 'Programming a Robotic Car',
  17
+                           'teacher': 'Sebastian',
  18
+                           'assistant': 'Andy'}},
  19
+    'apr2012': { 'cs101': {'name': 'Building a Search Engine',
  20
+                           'teacher': 'Dave',
  21
+                           'assistant': 'Sarah'},
  22
+                 'cs212': {'name': 'The Design of Computer Programs',
  23
+                           'teacher': 'Peter N.',
  24
+                           'assistant': 'Andy',
  25
+                           'prereq': 'cs101'},
  26
+                 'cs253': {'name': 'Web Application Engineering - Building a Blog',
  27
+                           'teacher': 'Steve',
  28
+                           'prereq': 'cs101'},
  29
+                 'cs262': {'name': 'Programming Languages - Building a Web Browser',
  30
+                           'teacher': 'Wes',
  31
+                           'assistant': 'Peter C.',
  32
+                           'prereq': 'cs101'},
  33
+                 'cs373': {'name': 'Programming a Robotic Car',
  34
+                           'teacher': 'Sebastian'},
  35
+                 'cs387': {'name': 'Applied Cryptography',
  36
+                           'teacher': 'Dave'}},
  37
+    'jan2044': { 'cs001': {'name': 'Building a Quantum Holodeck',
  38
+                           'teacher': 'Dorina'},
  39
+                        'cs003': {'name': 'Programming a Robotic Robotics Teacher',
  40
+                           'teacher': 'Jasper'},
  41
+                     }
  42
+    }
  43
+
  44
+
  45
+#For the following questions, you will find the
  46
+#        for <key> in <dictionary>:
  47
+#                   <block>
  48
+#construct useful.  This loops through the key values in the Dictionary.  For
  49
+#example, this procedure returns a list of all the courses offered in the given
  50
+#hexamester:
  51
+
  52
+def courses_offered(courses, hexamester):
  53
+    res = []
  54
+    for c in courses[hexamester]:
  55
+        res.append(c)
  56
+    return res
  57
+
  58
+#Define a procedure, when_offered(courses, course), that takes as a courses data
  59
+#structure and a string representing a class, and returns a list of strings
  60
+#representing the hexamesters when the input course is offered.  For example,
  61
+
  62
+#print when_offered (courses, 'cs101') => ['apr2012', 'feb2012']
  63
+#print when_offered(courses, 'bio893') => []
  64
+
  65
+def when_offered(courses,course):
  66
+    l = [key for key in courses if course in courses[key]]
  67
+    return l
  68
+
  69
+print when_offered (courses, 'cs101')
  70
+
  71
+
  72
+
85  Unit5/hw5_5.py
... ...
@@ -0,0 +1,85 @@
  1
+#Dictionaries of Dictionaries (of Dictionaries)
  2
+
  3
+#The next several questions concern the data structure below for keeping 
  4
+#track of Udacity's courses (where all of the values are strings):
  5
+  
  6
+#    { <hexamester>, { <class>: { <property>: <value>, ... },
  7
+#                                     ... },
  8
+#      ... }
  9
+
  10
+#For example,
  11
+
  12
+courses = {
  13
+    'feb2012': { 'cs101': {'name': 'Building a Search Engine',
  14
+                           'teacher': 'Dave',
  15
+                           'assistant': 'Peter C.'},
  16
+                 'cs373': {'name': 'Programming a Robotic Car',
  17
+                           'teacher': 'Sebastian',
  18
+                           'assistant': 'Andy'}},
  19
+    'apr2012': { 'cs101': {'name': 'Building a Search Engine',
  20
+                           'teacher': 'Dave',
  21
+                           'assistant': 'Sarah'},
  22
+                 'cs212': {'name': 'The Design of Computer Programs',
  23
+                           'teacher': 'Peter N.',
  24
+                           'assistant': 'Andy',
  25
+                           'prereq': 'cs101'},
  26
+                 'cs253': {'name': 'Web Application Engineering - Building a Blog',
  27
+                           'teacher': 'Steve',
  28
+                           'prereq': 'cs101'},
  29
+                 'cs262': {'name': 'Programming Languages - Building a Web Browser',
  30
+                           'teacher': 'Wes',
  31
+                           'assistant': 'Peter C.',
  32
+                           'prereq': 'cs101'},
  33
+                 'cs373': {'name': 'Programming a Robotic Car',
  34
+                           'teacher': 'Sebastian'},
  35
+                 'cs387': {'name': 'Applied Cryptography',
  36
+                           'teacher': 'Dave'}},
  37
+    'jan2044': { 'cs001': {'name': 'Building a Quantum Holodeck',
  38
+                           'teacher': 'Dorina'},
  39
+                        'cs003': {'name': 'Programming a Robotic Robotics Teacher',
  40
+                           'teacher': 'Jasper'},
  41
+                     }
  42
+    }
  43
+
  44
+
  45
+#For the following questions, you will find the
  46
+#        for <key> in <dictionary>:
  47
+#                   <block>
  48
+#construct useful.  This loops through the key values in the Dictionary.  For
  49
+#example, this procedure returns a list of all the courses offered in the given
  50
+#hexamester:
  51
+
  52
+def courses_offered(courses, hexamester):
  53
+    res = []
  54
+    for c in courses[hexamester]:
  55
+        res.append(c)
  56
+    return res
  57
+
  58
+#[Double Gold Star] Define a procedure, involved(courses, person), that takes as
  59
+#input a courses structure and a person and returns a Dictionary that describes
  60
+#all the courses the person is involved in.  A person is involved in a course if
  61
+#they are a value for any property for the course.  The output Dictionary should
  62
+#have hexamesters as its keys, and each value should be a list of courses that
  63
+#are offered that hexamester (the courses in the list can be in any order).
  64
+
  65
+#For example,
  66
+
  67
+# print involved(courses, 'Dave') => {'apr2012': ['cs101', 'cs387'], 'feb2012': ['cs101']}
  68
+# print involved(courses, 'Peter C.') => {'apr2012': ['cs262'], 'feb2012': ['cs101']}
  69
+# print involved(courses, 'Dorina') => {'jan2044': ['cs001']}
  70
+
  71
+def involved(courses, person):
  72
+    inv = {}
  73
+    for hexamester in courses:
  74
+        for course in courses[hexamester]:
  75
+            for elem in courses[hexamester][course]:
  76
+                if courses[hexamester][course][elem] == person:
  77
+                        if hexamester in inv:
  78
+                            inv[hexamester]+=[course]
  79
+                        else:
  80
+                            inv[hexamester]=[course]
  81
+    return inv
  82
+    
  83
+
  84
+
  85
+
66  Unit5/hw5_6.py
... ...
@@ -0,0 +1,66 @@
  1
+#6. In video 28. Update, it was suggested that some of the duplicate code in
  2
+#lookup and update could be avoided by a better design.  We can do this by
  3
+#defining a procedure that finds the entry corresponding to a given key, and
  4
+#using that in both lookup and update.
  5
+
  6
+#Here are the original procedures:
  7
+
  8
+def refactoring(htable, key):
  9
+    bucket = hashtable_get_bucket(htable, key)
  10
+    for entry in bucket:
  11
+        if entry[0] == key:
  12
+            return entry[1]
  13
+                 
  14
+def hashtable_update(htable, key, value):
  15
+    entry1 = refactoring(htable, key)
  16
+    bucket = hashtable_get_bucket(htable, key)
  17
+    if entry1:
  18
+        bucket.remove([key, entry1])
  19
+    bucket.append([key, value])
  20
+    
  21
+def hashtable_lookup(htable, key):
  22
+    bucket = hashtable_get_bucket(htable, key)
  23
+    entry1 = refactoring(htable, key)
  24
+    if not entry1:
  25
+            return None
  26
+    return entry1
  27
+
  28
+def make_hashtable(size):
  29
+    table = []
  30
+    for unused in range(0, size):
  31
+        table.append([])
  32
+    return table
  33
+
  34
+def hash_string(s, size):
  35
+    h = 0
  36
+    for c in s:
  37
+         h = h + ord(c)
  38
+    return h % size
  39
+
  40
+def hashtable_get_bucket(htable, key):
  41
+    return htable[hash_string(key, len(htable))]
  42
+
  43
+
  44
+#Whenever we have duplicate code like the loop that finds the entry in
  45
+#hashtable_update and hashtable_lookup, we should think if there is a better way
  46
+#to write this that would avoid the duplication.  We should be able to rewrite
  47
+#these procedures to be shorter by defining a new procedure and rewriting both
  48
+#hashtable_update and hashtable_lookup to use that procedure.
  49
+
  50
+#Modify the code for both hashtable_update and hashtable_lookup to have the same
  51
+#behavior they have now, but using fewer lines of code in each procedure.  You
  52
+#should define a new procedure to help with this.  Your new version should have
  53
+#approximately the same running time as the original version, but neither
  54
+#hashtable_update or hashtable_lookup should include any for or while loop, and
  55
+#the block of each procedure should be no more than 6 lines long.
  56
+
  57
+#Your procedures should have the same behavior as the originals.  For example,
  58
+
  59
+table = make_hashtable(10)
  60
+hashtable_update(table, 'Python', 'Monty')
  61
+hashtable_update(table, 'CLU', 'Barbara Liskov')
  62
+hashtable_update(table, 'JavaScript', 'Brendan Eich')
  63
+hashtable_update(table, 'Python', 'Guido van Rossum')
  64
+print hashtable_lookup(table, 'Python') # => Guido van Rossum
  65
+
  66
+
61  Unit5/hw5_7.py
... ...
@@ -0,0 +1,61 @@
  1
+#[Double Gold Star] Memoization is a way to make code run faster by saving
  2
+#previously computed results.  Instead of needing to recompute the value of an
  3
+#expression, a memoized computation first looks for the value in a cache of pre-
  4
+#computed values.
  5
+
  6
+#Define a procedure, cached_execution(cache, code), that takes in two inputs: a
  7
+#cache, which is a Dictionary that maps strings representing Python expressions
  8
+#to their previously computed values, and code, a string that is a Python
  9
+#expression.  Your procedure should return the value of code, but should only
  10
+#evaluate code if it has not been previously evaluated.
  11
+
  12
+def cached_execution(cache,code):
  13
+    if code in cache:
  14
+        return cache[code]
  15
+    else:
  16
+        cache[code] = eval(code)
  17
+        return cache[code]
  18
+    
  19
+#Here is an example showing the desired behavior of cached_execution:
  20
+
  21
+def factorial(n):
  22
+    print "Running factorial"
  23
+    result = 1
  24
+    for i in range(2, n + 1):
  25
+        result = result * i
  26
+    return result
  27
+
  28
+cache = {} # start cache as an empty dictionary
  29
+### first execution (should print out Running factorial and the result)
  30
+#print cached_execution(cache, 'factorial(50)')                           
  31
+
  32
+#print "Second time:"
  33
+### second execution (should only print out the result)
  34
+#print cached_execution(cache, 'factorial(50)')
  35
+
  36
+#Here is a more interesting example using cached_execution 
  37
+#(do not worry if you do not understand this, though, 
  38
+#it will be more clear after Unit 6):
  39
+
  40
+def cached_fibo(cache, n):
  41
+    if n == 1 or n == 0:
  42
+        return n
  43
+    else:
  44
+        return cached_execution(cache, 'cached_fibo(cache, ' + str(n - 1) + ')') \
  45
+               + cached_execution(cache, 'cached_fibo(cache, ' + str(n - 2) + ')')
  46
+
  47
+cache = {}
  48
+# do not try this at home...at least without a cache!
  49
+print cached_execution(cache, 'cached_fibo(cache, 100)')
  50
+
  51
+#Hint: you will need to use the built-in eval function similarly to how we used
  52
+#it in time_execution.  The eval function takes a string as input, and returns
  53
+#the result of evaluating that string as a Python expression.
  54
+
  55
+
  56
+    
  57
+    
  58
+    
  59
+    
  60
+    
  61
+ 

0 notes on commit d10655b

Please sign in to comment.
Something went wrong with that request. Please try again.