SlideShare uma empresa Scribd logo
1 de 10
For any help regarding Python Homework Help
visit : - https://www.pythonhomeworkhelp.com/,
Email :- support@pythonhomeworkhelp.com or
call us at :- +1 678 648 4277
Questions:
1. Are each of the following True or False:
(a) Any program that can be written using only function definitions and calls, the basic
arithmetic operators, assignment, and conditionals will run in constant time.
(b) Newton’s method will always converge on a correct root of a function.
(c) In Python, dictionaries are immutable.
(d) The value of ‘math.sqrt(2.0)*math.sqrt(2.0) == 2.0’ is True.
(e) One should always avoid iteration when a recursive solution is possible.
(f) Typically, the use of functions in a program reduces the total number of lines of code.
(g) In Python, retrieving the value associated with a dictionary key takes roughly constant time.
2. Consider the implementations of compare1 and compare 2, where a and b are
floats.
2.1) Do compare1 and compare2 return the same value for all possible inputs? If
not, give a pair of inputs for which they return a different value.
2.2) Do compare1 and compare2 print the same thing for all possible inputs? If not,
give a pair of inputs for which they print different things.
def compare1(a, b):
if a < 0:
a = -a
if b < 0:
b = -b
res = (a == b)
if res:
print a, 'and', b, 'have the same absolute value.'
else:
print a, 'and', b, 'have different absolute values.'
return res
def absolute_value(n):
if n < 0:
n = -n
return n
def compare2(a, b):
res = absolute_value(a) == absolute_value(b)
if res:
print a, 'and', b, 'have the same absolute value.'
else:
print a, 'and', b, 'have different absolute values.'
return res
3) Consider the following implementation of a function f, where x is a positive
integer:
def f(x):
xs = str(x)
if len(xs) == 1:
return int(xs)
n = int(xs[0]) + int(xs[1])
if len(xs) == 2:
return n
else:
return n + f(xs[2:])
(3.1) What does f(2112) return?
3.2) Write a specification of f.
4) Provide a Python implementation of a function first_N that takes a positive
integer, n, as its only argument. The function should print the first n perfect
squares that are not even numbers. E.g., if n were 2 it should print the perfect
squares 1 and 9.
5) Write pseudo code for an exhaustive enumeration variant of guess and check.
6) Provide a Python implementation for the function findSide specified below
def findSide():
"""asks the user to enter the area of a rectangle and the length of one side
of the rectangle. Returns a floating point number that is the length of the adjacent
side."""
7) Does the following function meet its specification? If not, change the program so
that it is consistent with the specification.
def f(L):
"""Returns a copy of the list L without modifying L."""
result = []
for e in L: result.append (e)
return result
8) At McDonalds one can buy chicken nuggets in packages containing 6, 9 or 20
pieces. Write a Python function that accepts an integer, num, as an argument and
decides whether or not it is possible to buy num nuggets at McDonalds.
9) Write an appropriate specification for the function below. Assume that n is an
integer.
def f(n):
s = str(n)
if len(s) <= 1: return s
return s[-1] + f(int(s[:-1]))
Solution:
a) False. Recursion means your program can run indefinitely.
b) False. You may end up jumping back and forth between the same two forever,
given an S-shaped function.
c) False. mydict[somekey] = somevalue.
d) False. Precision is finite.
e) False. Recursion may be a more natural way to express certain problems (e.g.:
fib, Towers of Hanoi).
f) True. Code reuse.
g) True. A quick lookup.
2)
2.1) Yes, they return the same value for all possible inputs.
2.2) No, they print different things for negative inputs. This is because a and b are
updated to refer to a different number in compare1, whereas they are not
updated in compare2.
3) Note about this function: it is a bit strange in that it handles multiple argument
types.
3.1) f(2112) returns 2+1+f(’12’) ==> 2+1+1+2 ==> 6.
3.2) Given an integer or a string representation of an integer, f returns the sum of its
digits.
4)
def first_N(n):
count = 0
current_sqrt = 1
while count < n:
square = current_sqrt * current_sqrt
# If square is not even
if square % 2 != 0:
print square
count += 1
current_sqrt += 1
5)
def guess_and_check(criteria):
for a in range(...):
for b in range(...):
for c in range(...):
...
if satisfies_criteria(a, b, c, ..., criteria):
return a, b, c,...
6.)
def findSide():
area = float( raw_input(’Enter the area of the rectangle: ’) )
side1 = float( raw_input(’Enter the length of one side of the rectangle: ’) )
return area / side1
7.)
Yes, it meets its specification, because the list being modified is a brand-new list
(result) that is created inside the function, then returned. L is only traversed.
8)
Note the resemblance to the exhaustive enumeration for guess-and-check, in
Problem 5.
We’re assuming that by “decides,” we just need to return True/False.
def nuggets(num):
for a in range(num/6+1):
for b in range(num/9+1):
for c in range(num/20+1):
if 6*a + 9*b + 20*c == num:
return True
return False
9)
Given an integer, take the string representation of that integer and reverse its
digits (returning this as a string).

Mais conteúdo relacionado

Semelhante a Introduction to Python Programming.pptx

B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentationManchireddy Reddy
 
Computer science ms
Computer science msComputer science ms
Computer science msB Bhuvanesh
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxAaliyanShaikh
 
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
 
Sample Exam Questions on Python for revision
Sample Exam Questions on Python for revisionSample Exam Questions on Python for revision
Sample Exam Questions on Python for revisionafsheenfaiq2
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2docSrikanth
 
Pydiomatic
PydiomaticPydiomatic
Pydiomaticrik0
 
Ee693 sept2014midsem
Ee693 sept2014midsemEe693 sept2014midsem
Ee693 sept2014midsemGopi Saiteja
 
PYTHON-PROGRAMMING-UNIT-II (1).pptx
PYTHON-PROGRAMMING-UNIT-II (1).pptxPYTHON-PROGRAMMING-UNIT-II (1).pptx
PYTHON-PROGRAMMING-UNIT-II (1).pptxgeorgejustymirobi1
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013amanabr
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Kurmendra Singh
 
MATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdfMATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdfahmed8651
 
A peek on numerical programming in perl and python e christopher dyken 2005
A peek on numerical programming in perl and python  e christopher dyken  2005A peek on numerical programming in perl and python  e christopher dyken  2005
A peek on numerical programming in perl and python e christopher dyken 2005Jules Krdenas
 

Semelhante a Introduction to Python Programming.pptx (20)

1.2 matlab numerical data
1.2  matlab numerical data1.2  matlab numerical data
1.2 matlab numerical data
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentation
 
Computer science ms
Computer science msComputer science ms
Computer science ms
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptx
 
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
 
Sample Exam Questions on Python for revision
Sample Exam Questions on Python for revisionSample Exam Questions on Python for revision
Sample Exam Questions on Python for revision
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
 
Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01
 
1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Mechanical Engineering Homework Help
Mechanical Engineering Homework HelpMechanical Engineering Homework Help
Mechanical Engineering Homework Help
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
Ee693 sept2014midsem
Ee693 sept2014midsemEe693 sept2014midsem
Ee693 sept2014midsem
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
PYTHON-PROGRAMMING-UNIT-II (1).pptx
PYTHON-PROGRAMMING-UNIT-II (1).pptxPYTHON-PROGRAMMING-UNIT-II (1).pptx
PYTHON-PROGRAMMING-UNIT-II (1).pptx
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
MATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdfMATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdf
 
A peek on numerical programming in perl and python e christopher dyken 2005
A peek on numerical programming in perl and python  e christopher dyken  2005A peek on numerical programming in perl and python  e christopher dyken  2005
A peek on numerical programming in perl and python e christopher dyken 2005
 

Mais de 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
 
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
 
Python Programming Homework Help.pptx
Python Programming Homework Help.pptxPython Programming Homework Help.pptx
Python Programming Homework Help.pptxPython Homework Help
 

Mais de 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
 
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
 
Python Programming Homework Help.pptx
Python Programming Homework Help.pptxPython Programming Homework Help.pptx
Python Programming Homework Help.pptx
 
Quality Python Homework Help
Quality Python Homework HelpQuality Python Homework Help
Quality Python Homework Help
 
Perfect Python Homework Help
Perfect Python Homework HelpPerfect Python Homework Help
Perfect Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 

Último

Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
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
 
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
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
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
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
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
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
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
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 

Último (20)

Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
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
 
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
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
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
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
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
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
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 ...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 

Introduction to Python Programming.pptx

  • 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. Questions: 1. Are each of the following True or False: (a) Any program that can be written using only function definitions and calls, the basic arithmetic operators, assignment, and conditionals will run in constant time. (b) Newton’s method will always converge on a correct root of a function. (c) In Python, dictionaries are immutable. (d) The value of ‘math.sqrt(2.0)*math.sqrt(2.0) == 2.0’ is True. (e) One should always avoid iteration when a recursive solution is possible. (f) Typically, the use of functions in a program reduces the total number of lines of code. (g) In Python, retrieving the value associated with a dictionary key takes roughly constant time.
  • 3. 2. Consider the implementations of compare1 and compare 2, where a and b are floats. 2.1) Do compare1 and compare2 return the same value for all possible inputs? If not, give a pair of inputs for which they return a different value. 2.2) Do compare1 and compare2 print the same thing for all possible inputs? If not, give a pair of inputs for which they print different things. def compare1(a, b): if a < 0: a = -a if b < 0: b = -b res = (a == b) if res: print a, 'and', b, 'have the same absolute value.' else: print a, 'and', b, 'have different absolute values.' return res
  • 4. def absolute_value(n): if n < 0: n = -n return n def compare2(a, b): res = absolute_value(a) == absolute_value(b) if res: print a, 'and', b, 'have the same absolute value.' else: print a, 'and', b, 'have different absolute values.' return res 3) Consider the following implementation of a function f, where x is a positive integer: def f(x): xs = str(x) if len(xs) == 1: return int(xs) n = int(xs[0]) + int(xs[1])
  • 5. if len(xs) == 2: return n else: return n + f(xs[2:]) (3.1) What does f(2112) return? 3.2) Write a specification of f. 4) Provide a Python implementation of a function first_N that takes a positive integer, n, as its only argument. The function should print the first n perfect squares that are not even numbers. E.g., if n were 2 it should print the perfect squares 1 and 9. 5) Write pseudo code for an exhaustive enumeration variant of guess and check. 6) Provide a Python implementation for the function findSide specified below def findSide(): """asks the user to enter the area of a rectangle and the length of one side of the rectangle. Returns a floating point number that is the length of the adjacent side."""
  • 6. 7) Does the following function meet its specification? If not, change the program so that it is consistent with the specification. def f(L): """Returns a copy of the list L without modifying L.""" result = [] for e in L: result.append (e) return result 8) At McDonalds one can buy chicken nuggets in packages containing 6, 9 or 20 pieces. Write a Python function that accepts an integer, num, as an argument and decides whether or not it is possible to buy num nuggets at McDonalds. 9) Write an appropriate specification for the function below. Assume that n is an integer. def f(n): s = str(n) if len(s) <= 1: return s return s[-1] + f(int(s[:-1]))
  • 7. Solution: a) False. Recursion means your program can run indefinitely. b) False. You may end up jumping back and forth between the same two forever, given an S-shaped function. c) False. mydict[somekey] = somevalue. d) False. Precision is finite. e) False. Recursion may be a more natural way to express certain problems (e.g.: fib, Towers of Hanoi). f) True. Code reuse. g) True. A quick lookup. 2) 2.1) Yes, they return the same value for all possible inputs. 2.2) No, they print different things for negative inputs. This is because a and b are updated to refer to a different number in compare1, whereas they are not updated in compare2. 3) Note about this function: it is a bit strange in that it handles multiple argument types.
  • 8. 3.1) f(2112) returns 2+1+f(’12’) ==> 2+1+1+2 ==> 6. 3.2) Given an integer or a string representation of an integer, f returns the sum of its digits. 4) def first_N(n): count = 0 current_sqrt = 1 while count < n: square = current_sqrt * current_sqrt # If square is not even if square % 2 != 0: print square count += 1 current_sqrt += 1 5) def guess_and_check(criteria): for a in range(...):
  • 9. for b in range(...): for c in range(...): ... if satisfies_criteria(a, b, c, ..., criteria): return a, b, c,... 6.) def findSide(): area = float( raw_input(’Enter the area of the rectangle: ’) ) side1 = float( raw_input(’Enter the length of one side of the rectangle: ’) ) return area / side1 7.) Yes, it meets its specification, because the list being modified is a brand-new list (result) that is created inside the function, then returned. L is only traversed. 8) Note the resemblance to the exhaustive enumeration for guess-and-check, in Problem 5.
  • 10. We’re assuming that by “decides,” we just need to return True/False. def nuggets(num): for a in range(num/6+1): for b in range(num/9+1): for c in range(num/20+1): if 6*a + 9*b + 20*c == num: return True return False 9) Given an integer, take the string representation of that integer and reverse its digits (returning this as a string).