SlideShare a Scribd company logo
1 of 9
Download to read offline
For any help regarding Python Homework Help
visit : - https://www.programminghomeworkhelp.com,
Email :- support@programminghomeworkhelp.com or
call us at :- +1 (315) 557-6473
For any help regarding Python Homework Help
visit : - https://www.programminghomeworkhelp.com,
Email :- support@programminghomeworkhelp.com or
call us at :- +1 (315) 557-6473
Problem
Problem
1)Is each of the following True or False
1.A greedy algorithm can be used to solve the 0-1 knapsack optimization
problem.
2.Dynamic programming can be used to solve optimization problems where the
size of the space of possible solutions is exponentially large.
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
https://www.programminghomeworkhelp.com
https://www.programminghomeworkhelp.com
optimization problem, but cannot be used to find a solution that is guaranteed to
be optimal.
4.In Python, an instance of a class is an object, but a class itself is not.
5.In Python, a subclass can override a function definition contained in a super
class.
6.Decision trees are always binary.
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
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. """
https://www.programminghomeworkhelp.com
https://www.programminghomeworkhelp.com
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 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)
https://www.programminghomeworkhelp.com
https://www.programminghomeworkhelp.com
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) print s.area() L =
shapes = {0:Circle, 1: Square} for i in range(10):
L.append(shapes[i%2](i)) print L[4]
L.append(shapes[i%2](i)) print L[4]
print f(L)
4) The following two formulas can be used to formalize a 0-1 knapsack problem.
1) 2)
4.1) What do each of n, pi, xi, wi, and C represent?
https://www.programminghomeworkhelp.com
https://www.programminghomeworkhelp.com
4.2) Use the formulas (refer to them as “formula 1” and “formula 2”) to describe the
optimization problem to be solved.
5. Write pseudo code describing merge sort.
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
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."""
Write a Python implementation of findNumber that guesses the magic number
defined by cmpGuess. Your program should have the lowest time complexity
possible.
https://www.programminghomeworkhelp.com
https://www.programminghomeworkhelp.com
Problem 1
1. False. 2. True. 3. False. 4. False. 5. True. 6. False.
Problem 2
def findMedian(L):
if len(L) == 0: raise ValueError("Empty list") copy = L[:]
copy.sort()
if len(copy) % 2 == 1: return copy[len(copy) / 2]
else:
return (copy[len(copy) / 2] + copy[len(copy) / 2 - 1]) / 2
Solution
Solution
return (copy[len(copy) / 2] + copy[len(copy) / 2 - 1]) / 2
Problem 3
Problem 4
1. n — total number of items
•pi — value of item i
•xi — value is 1 if item i is taken; 0 otherwise
16.0
Circle with radius 4
Circle with radius 8
https://www.programminghomeworkhelp.com
https://www.programminghomeworkhelp.com
•wi — weight of item i
•C — maximum weight allotted
2. Maximize formula 1 while obeying the constraint of formula 2.
Probem 5
If the list is of length 0 or 1, then return the list Otherwise,
Divide list into left and right subsets of about the same size Sort each
sublist recursively by re-applying merge sort Merge the returned (sorted)
sublists
sublists
Problem 6
def findNumber(maxVal): """
Assumes that maxVal is a positive integer. Returns a number, num, such that
cmpGuess(num) == 0 """
s = range(0, maxVal)
return bsearch(s, 0, len(s) – 1)
https://www.programminghomeworkhelp.com
https://www.programminghomeworkhelp.com
def bsearch(s, first, last): if (last - first) < 2:
if cmpGuess(s[first]) == 0: return first
else:
return last
mid = first + (last - first)/2 if cmpGuess(s[mid]) == 0:
return s[mid]
if cmpGuess(s[mid]) == -1:
return bsearch(s, first, mid - 1) return bsearch(s, mid + 1, last)
def cmpGuess(guess):
def cmpGuess(guess):
"""
Assumes that guess is an integer in range(maxVal). Returns
-1 if guess is < magic number, 0 if ==, 1 if > "“”
https://www.programminghomeworkhelp.com
https://www.programminghomeworkhelp.com

More Related Content

Similar to Python Homework Sample

The Ring programming language version 1.3 book - Part 82 of 88
The Ring programming language version 1.3 book - Part 82 of 88The Ring programming language version 1.3 book - Part 82 of 88
The Ring programming language version 1.3 book - Part 82 of 88Mahmoud Samir Fayed
 
Next.ml Boston: Data Science Dev Ops
Next.ml Boston: Data Science Dev OpsNext.ml Boston: Data Science Dev Ops
Next.ml Boston: Data Science Dev OpsEric Chiang
 
The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180 The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180 Mahmoud Samir Fayed
 
Gráficas en python
Gráficas en python Gráficas en python
Gráficas en python Jhon Valle
 
Kamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil Witecki
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lessonteach4uin
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnArnaud Joly
 
The Ring programming language version 1.7 book - Part 90 of 196
The Ring programming language version 1.7 book - Part 90 of 196The Ring programming language version 1.7 book - Part 90 of 196
The Ring programming language version 1.7 book - Part 90 of 196Mahmoud Samir Fayed
 
Python for Scientific Computing
Python for Scientific ComputingPython for Scientific Computing
Python for Scientific ComputingAlbert DeFusco
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.pptssuser419267
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.pptUmooraMinhaji
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonPython Ireland
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionNandan Sawant
 
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxJLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxvrickens
 

Similar to Python Homework Sample (20)

The Ring programming language version 1.3 book - Part 82 of 88
The Ring programming language version 1.3 book - Part 82 of 88The Ring programming language version 1.3 book - Part 82 of 88
The Ring programming language version 1.3 book - Part 82 of 88
 
Next.ml Boston: Data Science Dev Ops
Next.ml Boston: Data Science Dev OpsNext.ml Boston: Data Science Dev Ops
Next.ml Boston: Data Science Dev Ops
 
The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180 The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180
 
Gráficas en python
Gráficas en python Gráficas en python
Gráficas en python
 
Kamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, code
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lesson
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
 
The Ring programming language version 1.7 book - Part 90 of 196
The Ring programming language version 1.7 book - Part 90 of 196The Ring programming language version 1.7 book - Part 90 of 196
The Ring programming language version 1.7 book - Part 90 of 196
 
Python for Scientific Computing
Python for Scientific ComputingPython for Scientific Computing
Python for Scientific Computing
 
Writing Faster Python 3
Writing Faster Python 3Writing Faster Python 3
Writing Faster Python 3
 
OOC in python.ppt
OOC in python.pptOOC in python.ppt
OOC in python.ppt
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.ppt
 
08-classes-objects.ppt
08-classes-objects.ppt08-classes-objects.ppt
08-classes-objects.ppt
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
C Programming Homework Help
C Programming Homework HelpC Programming Homework Help
C Programming Homework Help
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
 
Django Good Practices
Django Good PracticesDjango Good Practices
Django Good Practices
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 Edition
 
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxJLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
 

Recently uploaded

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 

Recently uploaded (20)

Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 

Python Homework Sample

  • 1. For any help regarding Python Homework Help visit : - https://www.programminghomeworkhelp.com, Email :- support@programminghomeworkhelp.com or call us at :- +1 (315) 557-6473 For any help regarding Python Homework Help visit : - https://www.programminghomeworkhelp.com, Email :- support@programminghomeworkhelp.com or call us at :- +1 (315) 557-6473
  • 2. Problem Problem 1)Is each of the following True or False 1.A greedy algorithm can be used to solve the 0-1 knapsack optimization problem. 2.Dynamic programming can be used to solve optimization problems where the size of the space of possible solutions is exponentially large. 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 https://www.programminghomeworkhelp.com https://www.programminghomeworkhelp.com optimization problem, but cannot be used to find a solution that is guaranteed to be optimal. 4.In Python, an instance of a class is an object, but a class itself is not. 5.In Python, a subclass can override a function definition contained in a super class. 6.Decision trees are always binary.
  • 3. 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 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. """ https://www.programminghomeworkhelp.com https://www.programminghomeworkhelp.com
  • 4. 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 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) https://www.programminghomeworkhelp.com https://www.programminghomeworkhelp.com
  • 5. 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) print s.area() L = shapes = {0:Circle, 1: Square} for i in range(10): L.append(shapes[i%2](i)) print L[4] L.append(shapes[i%2](i)) print L[4] print f(L) 4) The following two formulas can be used to formalize a 0-1 knapsack problem. 1) 2) 4.1) What do each of n, pi, xi, wi, and C represent? https://www.programminghomeworkhelp.com https://www.programminghomeworkhelp.com
  • 6. 4.2) Use the formulas (refer to them as “formula 1” and “formula 2”) to describe the optimization problem to be solved. 5. Write pseudo code describing merge sort. 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 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.""" Write a Python implementation of findNumber that guesses the magic number defined by cmpGuess. Your program should have the lowest time complexity possible. https://www.programminghomeworkhelp.com https://www.programminghomeworkhelp.com
  • 7. Problem 1 1. False. 2. True. 3. False. 4. False. 5. True. 6. False. Problem 2 def findMedian(L): if len(L) == 0: raise ValueError("Empty list") copy = L[:] copy.sort() if len(copy) % 2 == 1: return copy[len(copy) / 2] else: return (copy[len(copy) / 2] + copy[len(copy) / 2 - 1]) / 2 Solution Solution return (copy[len(copy) / 2] + copy[len(copy) / 2 - 1]) / 2 Problem 3 Problem 4 1. n — total number of items •pi — value of item i •xi — value is 1 if item i is taken; 0 otherwise 16.0 Circle with radius 4 Circle with radius 8 https://www.programminghomeworkhelp.com https://www.programminghomeworkhelp.com
  • 8. •wi — weight of item i •C — maximum weight allotted 2. Maximize formula 1 while obeying the constraint of formula 2. Probem 5 If the list is of length 0 or 1, then return the list Otherwise, Divide list into left and right subsets of about the same size Sort each sublist recursively by re-applying merge sort Merge the returned (sorted) sublists sublists Problem 6 def findNumber(maxVal): """ Assumes that maxVal is a positive integer. Returns a number, num, such that cmpGuess(num) == 0 """ s = range(0, maxVal) return bsearch(s, 0, len(s) – 1) https://www.programminghomeworkhelp.com https://www.programminghomeworkhelp.com
  • 9. def bsearch(s, first, last): if (last - first) < 2: if cmpGuess(s[first]) == 0: return first else: return last mid = first + (last - first)/2 if cmpGuess(s[mid]) == 0: return s[mid] if cmpGuess(s[mid]) == -1: return bsearch(s, first, mid - 1) return bsearch(s, mid + 1, last) def cmpGuess(guess): def cmpGuess(guess): """ Assumes that guess is an integer in range(maxVal). Returns -1 if guess is < magic number, 0 if ==, 1 if > "“” https://www.programminghomeworkhelp.com https://www.programminghomeworkhelp.com