SlideShare a Scribd company logo
1 of 9
For any help regarding Python Homework Help
visit : - https://www.pythonhomeworkhelp.com/,
Email :- support@pythonhomeworkhelp.com or
call us at :- +1 678 648 4277
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 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.
pythonhomeworkhelp.com
Problem
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. """
pythonhomeworkhelp.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 '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)
pythonhomeworkhelp.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]
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?
pythonhomeworkhelp.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 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.
pythonhomeworkhelp.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
Problem 3
16.0
Circle with radius 4
Circle with radius 8
Problem 4
1.
•n — total number of items
•pi — value of item i
•xi — value is 1 if item i is taken; 0 otherwise
Solution
pythonhomeworkhelp.com
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
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)
Probem 5
If the list is of length 0 or 1, then return the list Otherwise,
•wi — weight of item i
•C — maximum weight allotted
2. Maximize formula 1 while obeying the constraint of
formula 2.
pythonhomeworkhelp.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):
"""
Assumes that guess is an integer in
range(maxVal). Returns -1 if guess
is < magic number, 0 if ==, 1 if > """
pythonhomeworkhelp.com

More Related Content

Similar to Perfect Python Homework Help

Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Python for Scientific Computing
Python for Scientific ComputingPython for Scientific Computing
Python for Scientific ComputingAlbert DeFusco
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Polymorphism.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptxVijaykota11
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional ProgrammingFrancesco Bruni
 
Python lab manual all the experiments are available
Python lab manual all the experiments are availablePython lab manual all the experiments are available
Python lab manual all the experiments are availableNitesh Dubey
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptAnishaJ7
 
CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfUmarMustafa13
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Bryan O'Sullivan
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance HaskellJohan Tibell
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approachFrancesco Bruni
 
chapter1.pdf ......................................
chapter1.pdf ......................................chapter1.pdf ......................................
chapter1.pdf ......................................nourhandardeer3
 
phuong trinh vi phan d geometry part 2
phuong trinh vi phan d geometry part 2phuong trinh vi phan d geometry part 2
phuong trinh vi phan d geometry part 2Bui Loi
 
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docxSAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docxanhlodge
 
A MATLAB project on LCR circuits
A MATLAB project on LCR circuitsA MATLAB project on LCR circuits
A MATLAB project on LCR circuitssvrohith 9
 
Dynamic programming - fundamentals review
Dynamic programming - fundamentals reviewDynamic programming - fundamentals review
Dynamic programming - fundamentals reviewElifTech
 
This assignment is about creating and using heaps. Implement a heap .docx
 This assignment is about creating and using heaps.  Implement a heap .docx This assignment is about creating and using heaps.  Implement a heap .docx
This assignment is about creating and using heaps. Implement a heap .docxKomlin1
 
Name ____________________________ Calculus 2 Mike Huff .docx
Name ____________________________ Calculus 2   Mike Huff  .docxName ____________________________ Calculus 2   Mike Huff  .docx
Name ____________________________ Calculus 2 Mike Huff .docxrosemarybdodson23141
 

Similar to Perfect Python Homework Help (20)

Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Python for Scientific Computing
Python for Scientific ComputingPython for Scientific Computing
Python for Scientific Computing
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Polymorphism.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptx
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
Python lab manual all the experiments are available
Python lab manual all the experiments are availablePython lab manual all the experiments are available
Python lab manual all the experiments are available
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
 
CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdf
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6
 
Array
ArrayArray
Array
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approach
 
chapter1.pdf ......................................
chapter1.pdf ......................................chapter1.pdf ......................................
chapter1.pdf ......................................
 
phuong trinh vi phan d geometry part 2
phuong trinh vi phan d geometry part 2phuong trinh vi phan d geometry part 2
phuong trinh vi phan d geometry part 2
 
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docxSAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
SAMPLE QUESTIONExercise 1 Consider the functionf (x,C).docx
 
A MATLAB project on LCR circuits
A MATLAB project on LCR circuitsA MATLAB project on LCR circuits
A MATLAB project on LCR circuits
 
Dynamic programming - fundamentals review
Dynamic programming - fundamentals reviewDynamic programming - fundamentals review
Dynamic programming - fundamentals review
 
This assignment is about creating and using heaps. Implement a heap .docx
 This assignment is about creating and using heaps.  Implement a heap .docx This assignment is about creating and using heaps.  Implement a heap .docx
This assignment is about creating and using heaps. Implement a heap .docx
 
Algorithms DM
Algorithms DMAlgorithms DM
Algorithms DM
 
Name ____________________________ Calculus 2 Mike Huff .docx
Name ____________________________ Calculus 2   Mike Huff  .docxName ____________________________ Calculus 2   Mike Huff  .docx
Name ____________________________ Calculus 2 Mike Huff .docx
 

More from Python Homework Help

Introduction to Python Dictionary.pptx
Introduction to Python Dictionary.pptxIntroduction to Python Dictionary.pptx
Introduction to Python Dictionary.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 

More from Python Homework Help (20)

Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Complete my Python Homework
Complete my Python HomeworkComplete my Python Homework
Complete my Python Homework
 
Introduction to Python Dictionary.pptx
Introduction to Python Dictionary.pptxIntroduction to Python Dictionary.pptx
Introduction to Python Dictionary.pptx
 
Basic Python Programming.pptx
Basic Python Programming.pptxBasic Python Programming.pptx
Basic Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Quality Python Homework Help
Quality Python Homework HelpQuality Python Homework Help
Quality Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Quality Python Homework Help
Quality Python Homework HelpQuality Python Homework Help
Quality Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Programming Homework Help
Python Programming Homework HelpPython Programming Homework Help
Python Programming Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 

Recently uploaded

MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
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
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 

Recently uploaded (20)

MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
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
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
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🔝
 
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
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 

Perfect Python Homework Help

  • 1. For any help regarding Python Homework Help visit : - https://www.pythonhomeworkhelp.com/, Email :- support@pythonhomeworkhelp.com or call us at :- +1 678 648 4277
  • 2. 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 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. pythonhomeworkhelp.com Problem
  • 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 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. """ pythonhomeworkhelp.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 '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) pythonhomeworkhelp.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] 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? pythonhomeworkhelp.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 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. pythonhomeworkhelp.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 Problem 3 16.0 Circle with radius 4 Circle with radius 8 Problem 4 1. •n — total number of items •pi — value of item i •xi — value is 1 if item i is taken; 0 otherwise Solution pythonhomeworkhelp.com
  • 8. 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 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) Probem 5 If the list is of length 0 or 1, then return the list Otherwise, •wi — weight of item i •C — maximum weight allotted 2. Maximize formula 1 while obeying the constraint of formula 2. pythonhomeworkhelp.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): """ Assumes that guess is an integer in range(maxVal). Returns -1 if guess is < magic number, 0 if ==, 1 if > """ pythonhomeworkhelp.com