Learn faster and stay on-track by joining this free class with other self-learners.
Register for MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming now.
|
MIT OpenCourseWare 6.00 Introduction to Computer Science and ProgrammingClass length: 24 weeks. Start anytime. Creator: duallain Status: Established |
Join this class! |
|
Lesson 17: Assignment 1: Quiz 2Homework Submissions5 totalQuiz 2
#1) Is each of the following True or False
1.1. A greedy algorithm can be used to solve the 0-1 knapsack optimization problem.
FALSE
1.2. Dynamic programming can be used to solve optimization problems where the size of the space of possible solutions is exponentially large.
TRUE
1.3. Dynamic programming can be used to find an approximate solution to an optimization problem, but cannot be used to find a solution that is guaranteed to be optimal.
FALSE
1.4. In Python, an instance of a class is an object, but a class itself is not.
FALSE
1.5. In Python, a subclass can override a function definition contained in a super class.
TRUE
1.6. Decision trees are always binary.
FALSE
#2) Provide code implementing a Python function that meets the specification below.
def findMedian(L):
"""
Finds median of L.
L: a non-empty list of floats
Returns: If L has an odd number of elements, returns the median element of L. For example, if L is the list [15.0, 5.3, 18.2], returns 15.0.
If L has an even number of elements, returns the average of the two median elements. For example, if L is the list [1.0, 2.0, 3.0, 4.0], returns 2.5.
If the list is empty, raises a ValueError exception.
Side effects: none.
"""
try:
if len(L) < 1:
raise exception
L_middle = len(L) / 2
L_sorted = sorted(L)
if len(L) % 2 == 0: # even case
median = (L_sorted[L_middle] + L_sorted[L_middle+1]) / 2
else:
median = L_sorted[L_middle]
return median
except ValueError:
print "L ValueError"
#3) What does the following code print?
class Shape(object):
def __cmp__(s1, s2):
return cmp(s1.area(), s2.area())
class Square(Shape):
def __init__(self, h):
self.side = float(h)
def area(self):
return self.side**2
def __str__(self):
return 'Square with side ' + str(self.side)
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159*(self.radius**2)
def __str__(self):
return 'Circle with radius ' + str(self.radius)
def f(L):
if len(L) == 0: return None
x = L[0]
for s in L:
if s >= x:
x = s
return x
s = Square(4) # Create a square, s, with height 4
print s.area() # Print area of s = 16
L = [] # Create list L
shapes = {0:Circle, 1: Square} # Create dictionary with two keys.
for i in range(10): # loop ten times
L.append(shapes[i%2](i)) # add objects from shapes dictionary L list
print L[4] # "Circle with radius 4"
print f(L) # "Circle with radius 8"
16.0
Circle with radius 4
Circle with radius 8
4) The following two formulas can be used to formalize a 0-1 knapsack problem.
1) See handout. 2) See handout.
4.1) What do each of n, pi, xi, wi, and C represent?
Beats me.
4.2) Use the formulas (refer to them as “formula 1” and “formula 2”) to
describe the optimization problem to be solved.
No idea.
#5. Write pseudo code describing merge sort.
def msort(L):
sorted = []
La = L[,l/2]
Lb = L[l/2,]
La = msort(La)
Lb = msort(Lb
for each in range La:
if La > Lb:
sorted.append(La)
else:
sorted.append(Lb)
return sorted
#6) Consider the two functions specified below that are used to play a “guess a number game.”
def cmpGuess(guess):
"""
Assumes that guess is an integer in range(maxVal).
returns -1 if guess is < than the magic number, 0 if it is equal to the magic number and 1 if it is greater than the magic number.
"""
def findNumber(maxVal):
"""
Assumes that maxVal is a positive integer. Returns a number, num, such that
cmpGuess(num) == 0.
"""
num = maxVal / 2
if cmpGuess(num) == 0:
return num
elif cmpGuess(num) == -1:
return num / 2
else:
Write a Python implementation of findNumber that guesses the magic number defined by
cmpGuess. Your program should have the lowest time complexity possible. (20 points)
For 1.1: When we made the greedy algorithm based on the ratio between value and work, my implementation for a majority of the cases produced the optimal solution. In the few cases where it was sub-optimal it was only off by 1-2 value units. And since it's complexity was O(n) it was more efficient than the Dynamic programming algorithm when the work constraint was high, because Dynamic programming complexity increases as the number of solutions increase. For Problem 6: Is it me, or is the solution they posted to problem 6 incorrect? I tried implementing it with my own version of cmpGuess() that followed the specification and I had to change if cmpGuess(s[mid]) == -1: from -1 to 1 to get it to work properly. And as far as I can tell using the while loop is the same complexity as the recursive implementation if I am not mistaken — O(log(n)). Is one version superior to the other? # Problem 1:
# 1.1: True --> Inorrect
# 1.2: True --> Correct
# 1.3: False --> Correct
# 1.4: False --> Correct
# 1.5: True --> Correct
# 1.6: False --> Correct
# Problem 2: --> Correct
def findMedian(L):
"""Finds median of L.
L: a non-empty list of floats
Returns:
If L has an odd number of elements, returns the median
element of L. For example, if L is the list
[15.0, 5.3, 18.2], returns 15.0.
If L has an even number of elements, returns the average
of the two median elements. For example, if L is the
list [1.0, 2.0, 3.0, 4.0], returns 2.5.
If the list is empty, raises a ValueError exception.
Side effects: none.
"""
if L == []: raise ValueError, 'List is empty'
sortL = sorted(L[:])
length = len(sortL)
median = length/2
if length%2 == 1:
return sortL[median]
else:
return (sortL[median-1]+sortL[median])/2.0
# Problem 3: --> Correct
# The code prints:
# 16.0
# Circle with radius 4
# Circle with radius 8
# Problem 4:
# 4.1: --> Correct
# n = total items
# pi = value of item i
# xi = whether item is selected or not 1/0
# wi = weight of item i
# C = the constraint, in this case the total weight
# 4.2: --> Correctish
# Formula 1: the highest sum of the total value of selected items from i = 1 to n
# Formula 2: within the constraint of the sum of weights of the selected items from
# i = 1 to n being less than or equal to the constraint C.
# Problem 5: --> Incorrect, I hate writing pseudocode!
# Take a list, L split it in half until you can compare each list entry individually.
# then merge the lists back together in order.
# Problem 6: --> I think it is correct, but implemented with a while loop instead of recursively
def findNumber(maxVal):
"""
Assumes that maxVal is a positive integer.
Returns a number, num, such that cmpGuess(num) == 0.
"""
lowGuess = 0
highGuess = maxVal
guess = (highGuess+lowGuess)/2
correct = cmpGuess(guess)
while correct != 0:
if correct == 1:
highGuess = guess
guess = (highGuess+lowGuess)/2
correct = cmpGuess(guess)
else:
lowGuess = guess
guess = (highGuess+lowGuess)/2
correct = cmpGuess(guess)
return guess
No comments. Sign up or log in to comment # 1.1 True? - May not be best algo?
# 1.2 True - If problem has optimal substructure and overlapping subproblems
# 1.3 False - Dynamic programming can find optimal solution
# 1.4 False - The class and instances of the class are both objects
# 1.5 True - Each class can redefine parent class methods with their own.
# 1.6 False - Multi-branch trees?
# 2.0) ----------------
def findMedian(L):
if len(L) == 0: raise ValueError("Must have at least 1 item in the list")
length = len(L)
copy = sorted(L)
mid = copy[length / 2]
if length % 2 == 1:
return mid
else:
return (mid + copy[length / 2-1]) / 2
# 3.0) -----------------------
# 16.0
# Circle with radius 4
# Circle with radius 8
# 4.1) -------------------------
# n - number of items
# pi = price of item i
# xi = 1 if taken; 0 if not taken
# wi = weight of item i
# C = maximum weight constraint
# 4.2) --------------------------
# 1) Formula one finds optimal solution given price
# 2_ Formula two add a weight constraint on formula one
# 5.0)
# If length of list is <= 1: return list
# Else divide list in half and recursively return the sorted sublists
# Merge the sorted sublists
#6.0)
def cmpGuess(guess):
answer = 701
if guess == answer:
return 0
if guess < answer:
return -1
if guess > answer:
return 1
def findNumber(maxVal=1000):
low = 0
high = maxVal
guess = (low + high) / 2
while cmpGuess(guess) != 0:
if cmpGuess(guess) == -1:
low = guess
else:
high = guess
guess = (low + high) / 2
return guess
No comments. Sign up or log in to comment 1.1) False.
1.2) True, so long as they contain optimal substructure and overlapping sub problems
1.3) False, dynamic programming *can* find an optimal solution
1.4) False, classes themselves are objects in addition to class instances
1.5) True
1.6) False, can have more than one branch.
2)
def findMedian(L):
""" Finds median of L.
L: a non-empty list of floats
Returns:
If L has an odd number of elements, returns the median
element of L. For example, if L is the list
[15.0, 5.3, 18.2], returns 15.0.
If L has an even number of elements, returns the average
of the two median elements. For example, if L is the
list [1.0, 2.0, 3.0, 4.0], returns 2.5.
If the list is empty, raises a ValueError exception.
Side effects: none.
"""
if type(L) != list:
message = '%s is not a list' %L
raise TypeError(message)
else:
if len(L) > 0:
##print len(L)%2
if len(L)%2 != 0: #i.e if the list has an odd number of elements
middle = len(L)/2
L.sort()
print 'The median of %s is' %L, L[middle]
return L[middle]
else:
total = 0
for item in L:
total += item
mean = float(total)/len(L)
print 'The median of %s is' %L, mean
return mean
raise ValueError('Received an empty list to analyse. No can do.')
3)
16
Circle with radius 4
Circle with radius 8
4)
4.1)
n: number of items to choose from
p_i: Value of ith item
x_i: 0 for taken, 1 for discarded
C: knapsack weight capacity
4.2)
Formula 2 is a weight constraint on the maximization of formula 1.
5)
Return the list if it has only one item. Otherwise, divide it in two equal lenght halves
and order each of these recursively rerunning the method just described. Finally, merge the
returned sublists.
6)
def cmpGuess(guess):
"""Assumes that guess is an integer in range(maxVal). returns -1 if guess is < than the magic
number, 0 if it is equal to the magic number and 1 if it is greater than the magic number."""
magicnum = 891
if guess == magicnum:
return 0
if guess > magicnum:
return 1
if guess <magicnum:
return -1
def findNumber(maxVal):
"""Assumes that maxVal is a positive integer. Returns a number, num, such that
cmpGuess(num) == 0."""
ordered_integers = range(maxVal)
low = 0
high = maxVal
guess = (low + high)/2
while cmpGuess(guess) != 0:
#print 'low:', low, 'high:', high ,'guess:', guess
if cmpGuess(guess) == -1:
low = guess
else:
high = guess
guess = (low + high)/2
return guess
No comments. Sign up or log in to comment A little confused as to why 1.1 is False...I thought a greedy algorithm could come up with a solution, but not necessarily an optimal one 1.1) True, though the solution might not be optimal
1.2) True, so long as they contain optimal substructure and overlapping sub problems
1.3) False, dynamic programming *can* find an optimal solution
1.4) False, Classes themselves are objects in addition to class instances
1.5) True
1.6) False, can have more than one branch
2)
def findMedian(L):
"""Finds median of L.
L: a non-empty list of floats
Returns:
If L has an odd number of elements, returns the median element of
L. For example, if L is the list [15.0, 5.3, 18.2], returns 15.0.
If L has an even number of elements, returns the average of the
two median elements. For example, if L is the list
[1.0, 2.0, 3.0, 4.0], returns 2.5.
If the list is empty, raises a ValueError exception.
Side effects: none
"""
if len(L) == 0:
raise ValueError('List cannot be empty')
sortedList = sorted(L)
if len(sortedList) % 2 != 0:
return sortedList[len(sortedList) // 2]
return (sortedList[len(sortedList) // 2 - 1] + sortedList[len(sortedList) // 2]) / 2.0
3)
16
L = [
Circle(0),
Square(1),
Circle(2),
Square(3),
Circle(4),
Square(5),
Circle(6),
Square(7),
Circle(8),
Square(9),
]
Circle with radius 4
Circle with radius 8
4) True
4.1)
n is number of items in the knapsack
p sub i is the price of the element i
x sub i is whether item i is selected for inclusion
w sub i is the weight of item i
C is a constant representing the maximum weight allowed
4.2)
formula 1 calculates all possible possible values
formula 2 calculates all possible combinations with the weight constraint
5)
merge_sort(sequence)
if length of sequence is 1,
return sequence
if length of sequence is 2,
if sequence[0] is less than sequence[1],
return sequence
else
return [sequence[1], sequence[0]]
sorted_first_half = merge_sort(first half of sequence)
sorted_second_half = merge_sort(second half of sequence)
return merge(sorted_first_half, sorted_second_half)
merge(sequence_1, sequence_2)
while sequence_1 and sequence_2 have items left
if sequence_1[0] is greater than sequence_2[0],
remove element 0 from sequence_1 and add it to sorted_sequence
else
remove element 0 form sequence_2 and add it to sorted_sequence
if sequence_1 has elements left,
add the rest of sequence_1 to sorted_sequence
if sequence_2 has elements left,
add the rest of sequence_2 to sorted_sequence
return sorted_sequence
6)
def cmpGuess(guess):
"""Assumes that guess is an integer in range(maxVal). returns -1 if
guess is < than the magic number, 0 if it is equal to the magic
number and 1 if it is greater than the magic number."""
def findNumber(maxVal):
"""Assumes that maxVal is a positive integer. Returns a number, num,
such that cmpGuess(num) == 0."""
low = 0
high = maxVal
while True:
guess = low + (high - low) / 2
result = cmpGuess(guess)
if (result == 0): return guess
if (result == -1):
low = guess
else:
high = guess
Comments:On question 3. L is not printed right? Also, findNumber does not seem to halt here. |
No comments. Sign up or log in to comment