SlideShare una empresa de Scribd logo
1 de 20
For any help regarding Python Homework Help
visit : - https://www.pythonhomeworkhelp.com/,
Email :- support@pythonhomeworkhelp.com or
call us at :- +1 678 648 4277
Here are some practice quiz questions (taken mostly from last year’s final).
1)Is each of the following True or False
1. In Python, the method sortof class listhas a side effect.
2.When run on the same inputs, an exponential algorithm will always
take longer than a polynomial algorithm.
3. Newton’s method is based upon successive approximation.
4.Constructing a black box test suite involves looking at the control flow
of the code to be tested.
5. Python classes enforce data hiding.
2) The code below produces three plots. Match each of the plots on
the next page with the appropriate figure (Figure 1, Figure 2, or
Figure 3).
import pylab y1 = []
y2 = []
y3 = []
for i in range(20):
y1.append(300*i)
y2.append(i**3)
Problem
pythonhomeworkhelp.com
y2.append(i**3) y3.append(2**i)
pylab.figure(1) pylab.plot(y1)
pylab.figure(2) pylab.plot(y2)
pylab.figure(3) pylab.plot(y3)
pylab.semilogy()
pythonhomeworkhelp.com
3) Can the following specification be implemented? If not,
explain why.
def f(x, e):
“““ x and e are floats
returns y, a float, such that x-e <= y*y <= x+e”””
4) Write a Python program that satisfies the following
specification.
def f(L1, L2):
“““ L1 and L2 are lists of integers
returns the element-wise product of L1 and L2. If
the lists are of different length, it uses 1 for the
missing coefficients.
E.g., if L1 = [2, 2, 3] and L2 = [7, 5, 6, 7]
it returns [14, 10, 18, 7] side
effects: none ”””
pythonhomeworkhelp.com
The following questions all refer to the code you were asked to study in preparation
for this exam. They also assume that the following code is used to test the program.
(For your convenience, a copy of the posted code is at the end of this quiz. Feel free
to separate it from the rest of the quiz.)
Warning: The code at the end of this is NOT the same as the code you have been
given to study. It may not be worth your time to study this code carefully enough
to answer all of the practice questions, but these questions should give you the
flavor of the kinds of questions we might ask about the code supplied this term.
numDays = 500 bias = 0.11/200.0 numSectors
= 1
sectorSize = 500
numTrials = 5
print 'Testing Model on', numDays, 'days' mean = 0.0
for i in range(numTrials): pylab.figure(1)
mkt = generateMarket(numSectors, sectorSize, bias)
endPrices = simMkt(mkt, numDays) mean += endPrices[-1]
title = 'Closing Prices With ' + str(numSectors) + ' Sectors'
plotValueOverTime(endPrices, title)
pylab.figure(2) plotDistributionAtEnd(mkt, title)
meanClosing = mean/float(numTrials)
print 'Mean closing with', numSectors, 'sectors is', meanClosing
pythonhomeworkhelp.com
1) If, in class Stock, the line
self.price = self.price * (1.0 + baseMove)
were replaced with the line
self.price = self.price * baseMove
which of the following best describes the expected mean value of
the market after 200 days:
a.Close to 111
b.Close to 100
c.Close to 50
d.Close to 0
e.About the same as with the original code
2)Consider running the above test code twice, once with numSectors = 1 and once
with numSectors = 20. Each will produce a Figure 1. Now consider running a linear
regression to fit a line to each of the curves produced in the Figure 1’s for each test.
Would you expect the average mean square error of the fits for numSectors =
20to be:
pythonhomeworkhelp.com
a.Smaller than the average mean square error of the fits for
numSectors = 1.
b.Larger than the average mean square error of the fits for
numSectors = 1.
c.About the same as the average mean square error of the fits
for
numSectors = 1.
d.None of the above.
5.3) Characterize the algorithmic efficiency of generateMarket.
5.4) If in Stock.makeMove, the line
baseMove=bias+random.uniform(-self.volatility, self.volatility)
were replaced by the line
baseMove = bias
which of the following Figure 2’s is most likely to be produced by
the test code? (10 points)
pythonhomeworkhelp.com
A B
C D
pythonhomeworkhelp.com
import pylab import
random
# Global constant
TRADING_DAYS_PER_YEAR = 200
class Stock:
def init (self, ticker, volatility): self.volatility =
volatility self.ticker = ticker
self.price = None self.history
= []
def setPrice(self, price): self.price =
price
self.history.append(price) def
getPrice(self):
return self.price def
getTicker(self):
return self.ticker def
makeMove(self, bias):
if self.price == 0.0: return
baseMove = bias + random.uniform(-self.volatility, self.volatility)
self.price = self.price * (1.0 + baseMove)
if self.price < 0.01: self.price =
0.0
self.history.append(self.price)
pythonhomeworkhelp.com
class Market:
def init (self): self.sectors =
[] self.tickers = set()
def addSector(self, sect):
if sect.getName() in self.sectors:
raise ValueError('Duplicate sector')
for t in sect.getTickers(): if t in
self.tickers:
raise ValueError('A ticker in sect already in
market') else: self.tickers.add(t)
self.sectors.append(sect)
def getSectors(self):
return self.sectors def
getStocks(self):
stocks = []
for s in self.sectors:
stocks = stocks + s.getStocks()
return stocks
def moveAllStocks(self):
vals = []
for s in self.sectors:
vals = vals + s.moveAllStocks()
return vals
pythonhomeworkhelp.com
class Sector:
def init (self, sectorName, bias): self.tickers =
set() self.sectorName = sectorName
self.stocks = []
self.bias = bias self.origBias =
bias
def addStock(self, stk):
if stk.getTicker() in self.tickers: raise
ValueError('Duplicate ticker')
self.tickers.add(stk.getTicker())
self.stocks.append(stk)
def getStocks(self): return
self.stocks
def getTickers(self): return
self.tickers
def setBias(self, newBias): self.bias =
newBias
def getBias(self): return
self.bias
def getOrigBias(self): return
self.origBias
def sameSector(self, other):
return self.sectorName == other.sectorName def
getName(self):
return self.sectorName def
pythonhomeworkhelp.com
moveAllStocks(self):
vals = []
for stock in self.stocks:
stock.makeMove(self.bias)
vals.append(stock.getPrice()
)
return vals
def generateSector(sectorSize,
sectorName, bias): sect =
Sector(sectorName, bias)
for i in range(sectorSize):
ticker = sectorName + 'Ticker ' + str(i)
volatility = random.uniform(0.01,
0.04) stk = Stock(ticker, volatility)
stk.setPrice(100)
try:
sect.addStock(stk)
except ValueError:
# Tickers are all different by construction, so this should
never # happen
print 'Error in generate stocks, should never reach
here.' raise AssertionError
return sect
pythonhomeworkhelp.com
def simMkt(mkt, numDays):
endPrices = []
for i in range(numDays):
if i%(TRADING_DAYS_PER_YEAR/4) == 0:
for s in mkt.getSectors():
newBias = s.getOrigBias() + random.gauss(0, 2*s.getOrigBias())
s.setBias(newBias)
vals = mkt.moveAllStocks() vals =
pylab.array(vals)
mean = vals.sum()/float(len(vals))
endPrices.append(mean)
return endPrices
def plotValueOverTime(endPrices, title):
pylab.plot(endPrices) pylab.title(title)
pylab.xlabel('Days') pylab.ylabel('Price')
def
generateMarket(numSe
ctors, sectorSize, bias):
mkt = Market()
for n in range(numSectors):
sect = generateSector(sectorSize,
'Sector ' + str(n), bias)
mkt.addSector(sect)
return mkt
pythonhomeworkhelp.com
def
plotDistributionAtEnd(m
kt, title): prices = []
for s in
mkt.getStocks():
prices.append(s.ge
tPrice())
pylab.hist(prices, bins =
20) pylab.title(title)
pylab.xlabel('Last Sale')
pylab.ylabel('Number of
Securities')
pythonhomeworkhelp.com
import pylab, random
class Stock(object):
def __init__(self, price, distribution, vol):
self.price = price
self.history = [price]
self.distribution = distribution
self.vol = vol
self.lastChangeInfluence = 0.0
def setPrice(self, price):
self.price = price
self.history.append(price)
def getPrice(self):
return self.price
def makeMove(self, bias, mo):
oldPrice = self.price
baseMove = self.distribution(self.vol) + bias
self.price = self.price * (1.0 + baseMove)
self.price += mo*random.choice([0.0,
1.0])*self.lastChangeInfluence
self.history.append(self.price)
change = self.price - oldPrice
if change >= 0:
self.lastChangeInfluence = min(change, oldPrice*0.01)
else:
self.lastChangeInfluence = max(change, -oldPrice*0.01)
pythonhomeworkhelp.com
Solution
def showHistory(self, fig, test):
pylab.figure(fig)
pylab.plot(self.history)
pylab.title('Closing Prices, Test ' + test)
pylab.xlabel('Day')
pylab.ylabel('Price')
class SimpleMarket(object):
def __init__(self, numStks, volUB):
self.stks = []
self.bias = 0.0
for n in range(numStks):
volatility = random.uniform(0, volUB)
distribution = lambda vol: random.gauss(0.0, vol)
stk = Stock(100.0, distribution, volatility)
self.addStock(stk)
def addStock(self, stk):
self.stks.append(stk)
def setBias(self, bias):
self.bias = bias
def getBias(self):
return self.bias
def getStocks(self):
return self.stks[:]
pythonhomeworkhelp.com
def move(self, mo):
prices = []
for s in self.stks:
s.makeMove(self.bias, mo)
prices.append(s.getPrice())
return prices
class Market(SimpleMarket):
def __init__(self, numStks, volUB,
dailyBiasRange):
SimpleMarket.__init__(self, numStks, volUB)
self.dailyBiasRange = dailyBiasRange
def move(self, mo):
prices = []
dailyBias =
random.gauss(self.dailyBiasRange[0],
self.dailyBiasRange[1])
for s in self.stks:
s.makeMove(self.bias + dailyBias, mo)
prices.append(s.getPrice())
return prices
def simMkt(mkt, numDays, mo):
endPrices = []
for i in range(numDays):
pythonhomeworkhelp.com
vals = mkt.move(mo)
vals = pylab.array(vals)
mean = vals.sum()/float(len(vals))
endPrices.append(mean)
return endPrices
def plotAverageOverTime(endPrices, title):
pylab.plot(endPrices)
pylab.title(title)
pylab.xlabel('Days')
pylab.ylabel('Price')
def plotDistributionAtEnd(mkt, title, color):
prices = []
sumSoFar = 0
for s in mkt.getStocks():
prices.append(s.getPrice())
sumSoFar += s.getPrice()
mean = sumSoFar/float(len(prices))
prices.sort()
pylab.plot(prices, color)
pylab.axhline(mean, color = color)
pylab.title(title)
pylab.xlabel('Stock')
pylab.ylabel('Last Sale')
pylab.semilogy()
pythonhomeworkhelp.com
def runTrial(showHistory, test, p):
colors = ['b','g','r','c','m','y','k']
mkt = Market(p['numStocks'], p['volUB'],
p['dailyBiasRange'])
mkt.setBias(p['bias'])
endPrices = simMkt(mkt, p['numDays'],
p['mo'])
pylab.figure(1)
plotAverageOverTime(endPrices, 'Average
Closing Prices')
pylab.figure(2)
plotDistributionAtEnd(mkt, 'Distribution of Prices', colors[test%len(colors)])
if showHistory:
for s in mkt.getStocks():
s.showHistory(test+2, str(test))
def runTest(numTrials):
#Constants used in testing
numDaysPerYear = 200.0
params = {}
params['numDays'] = 200
params['numStocks'] = 500
params['bias'] = 0.1/numDaysPerYear #General market bias
pythonhomeworkhelp.com
params['volUB'] = 12.0/numDaysPerYear
#Upper bound on volatility for a stock
params['mo'] = 1.1/numDaysPerYear
#Momentum factor
params['dailyBiasRange'] = (0.0, 4.0/200.0)
for t in range(1, numTrials+1):
runTrial(True, t, params)
runTest(3)
pylab.show()
pythonhomeworkhelp.com

Más contenido relacionado

La actualidad más candente (20)

Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
Multidimensional arrays in C++
Multidimensional arrays in C++Multidimensional arrays in C++
Multidimensional arrays in C++
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Python
PythonPython
Python
 
06.Loops
06.Loops06.Loops
06.Loops
 
Python programming : Abstract classes interfaces
Python programming : Abstract classes interfacesPython programming : Abstract classes interfaces
Python programming : Abstract classes interfaces
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Dive Into PyTorch
Dive Into PyTorchDive Into PyTorch
Dive Into PyTorch
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
C tech questions
C tech questionsC tech questions
C tech questions
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
Scientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
Scientific Computing with Python Webinar March 19: 3D Visualization with MayaviScientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
Scientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
 
Python programing
Python programingPython programing
Python programing
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
13 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp0213 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp02
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Parameters
ParametersParameters
Parameters
 

Similar a Quality Python Homework Help

20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
200 Open Source Projects Later: Source Code Static Analysis Experience
200 Open Source Projects Later: Source Code Static Analysis Experience200 Open Source Projects Later: Source Code Static Analysis Experience
200 Open Source Projects Later: Source Code Static Analysis ExperienceAndrey Karpov
 
Optimization in the world of 64-bit errors
Optimization  in the world of 64-bit errorsOptimization  in the world of 64-bit errors
Optimization in the world of 64-bit errorsPVS-Studio
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for SpeedYung-Yu Chen
 
Idea for ineractive programming language
Idea for ineractive programming languageIdea for ineractive programming language
Idea for ineractive programming languageLincoln Hannah
 
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
 
MATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdfMATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdfahmed8651
 
do ruby ao golang: o que aprendi criando um microserviço depois de 5000 commits
do ruby ao golang: o que aprendi criando um microserviço depois de 5000 commitsdo ruby ao golang: o que aprendi criando um microserviço depois de 5000 commits
do ruby ao golang: o que aprendi criando um microserviço depois de 5000 commitsAndreLeoni1
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyKimikazu Kato
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentationManchireddy Reddy
 
Testing in those hard to reach places
Testing in those hard to reach placesTesting in those hard to reach places
Testing in those hard to reach placesdn
 

Similar a Quality Python Homework Help (20)

How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Cc code cards
Cc code cardsCc code cards
Cc code cards
 
Xgboost
XgboostXgboost
Xgboost
 
Gans
GansGans
Gans
 
GANs
GANsGANs
GANs
 
200 Open Source Projects Later: Source Code Static Analysis Experience
200 Open Source Projects Later: Source Code Static Analysis Experience200 Open Source Projects Later: Source Code Static Analysis Experience
200 Open Source Projects Later: Source Code Static Analysis Experience
 
Optimization in the world of 64-bit errors
Optimization  in the world of 64-bit errorsOptimization  in the world of 64-bit errors
Optimization in the world of 64-bit errors
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
 
Java Unit 1 Project
Java Unit 1 ProjectJava Unit 1 Project
Java Unit 1 Project
 
Idea for ineractive programming language
Idea for ineractive programming languageIdea for ineractive programming language
Idea for ineractive programming language
 
Klee and angr
Klee and angrKlee and angr
Klee and angr
 
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
 
MATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdfMATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdf
 
do ruby ao golang: o que aprendi criando um microserviço depois de 5000 commits
do ruby ao golang: o que aprendi criando um microserviço depois de 5000 commitsdo ruby ao golang: o que aprendi criando um microserviço depois de 5000 commits
do ruby ao golang: o que aprendi criando um microserviço depois de 5000 commits
 
Oct27
Oct27Oct27
Oct27
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPy
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentation
 
Testing in those hard to reach places
Testing in those hard to reach placesTesting in those hard to reach places
Testing in those hard to reach places
 

Más 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
 
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
 

Más 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
 
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
 
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

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
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
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
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
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 

Último (20)

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
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 ...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
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
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
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
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 

Quality 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. Here are some practice quiz questions (taken mostly from last year’s final). 1)Is each of the following True or False 1. In Python, the method sortof class listhas a side effect. 2.When run on the same inputs, an exponential algorithm will always take longer than a polynomial algorithm. 3. Newton’s method is based upon successive approximation. 4.Constructing a black box test suite involves looking at the control flow of the code to be tested. 5. Python classes enforce data hiding. 2) The code below produces three plots. Match each of the plots on the next page with the appropriate figure (Figure 1, Figure 2, or Figure 3). import pylab y1 = [] y2 = [] y3 = [] for i in range(20): y1.append(300*i) y2.append(i**3) Problem pythonhomeworkhelp.com
  • 3. y2.append(i**3) y3.append(2**i) pylab.figure(1) pylab.plot(y1) pylab.figure(2) pylab.plot(y2) pylab.figure(3) pylab.plot(y3) pylab.semilogy() pythonhomeworkhelp.com
  • 4. 3) Can the following specification be implemented? If not, explain why. def f(x, e): “““ x and e are floats returns y, a float, such that x-e <= y*y <= x+e””” 4) Write a Python program that satisfies the following specification. def f(L1, L2): “““ L1 and L2 are lists of integers returns the element-wise product of L1 and L2. If the lists are of different length, it uses 1 for the missing coefficients. E.g., if L1 = [2, 2, 3] and L2 = [7, 5, 6, 7] it returns [14, 10, 18, 7] side effects: none ””” pythonhomeworkhelp.com
  • 5. The following questions all refer to the code you were asked to study in preparation for this exam. They also assume that the following code is used to test the program. (For your convenience, a copy of the posted code is at the end of this quiz. Feel free to separate it from the rest of the quiz.) Warning: The code at the end of this is NOT the same as the code you have been given to study. It may not be worth your time to study this code carefully enough to answer all of the practice questions, but these questions should give you the flavor of the kinds of questions we might ask about the code supplied this term. numDays = 500 bias = 0.11/200.0 numSectors = 1 sectorSize = 500 numTrials = 5 print 'Testing Model on', numDays, 'days' mean = 0.0 for i in range(numTrials): pylab.figure(1) mkt = generateMarket(numSectors, sectorSize, bias) endPrices = simMkt(mkt, numDays) mean += endPrices[-1] title = 'Closing Prices With ' + str(numSectors) + ' Sectors' plotValueOverTime(endPrices, title) pylab.figure(2) plotDistributionAtEnd(mkt, title) meanClosing = mean/float(numTrials) print 'Mean closing with', numSectors, 'sectors is', meanClosing pythonhomeworkhelp.com
  • 6. 1) If, in class Stock, the line self.price = self.price * (1.0 + baseMove) were replaced with the line self.price = self.price * baseMove which of the following best describes the expected mean value of the market after 200 days: a.Close to 111 b.Close to 100 c.Close to 50 d.Close to 0 e.About the same as with the original code 2)Consider running the above test code twice, once with numSectors = 1 and once with numSectors = 20. Each will produce a Figure 1. Now consider running a linear regression to fit a line to each of the curves produced in the Figure 1’s for each test. Would you expect the average mean square error of the fits for numSectors = 20to be: pythonhomeworkhelp.com
  • 7. a.Smaller than the average mean square error of the fits for numSectors = 1. b.Larger than the average mean square error of the fits for numSectors = 1. c.About the same as the average mean square error of the fits for numSectors = 1. d.None of the above. 5.3) Characterize the algorithmic efficiency of generateMarket. 5.4) If in Stock.makeMove, the line baseMove=bias+random.uniform(-self.volatility, self.volatility) were replaced by the line baseMove = bias which of the following Figure 2’s is most likely to be produced by the test code? (10 points) pythonhomeworkhelp.com
  • 9. import pylab import random # Global constant TRADING_DAYS_PER_YEAR = 200 class Stock: def init (self, ticker, volatility): self.volatility = volatility self.ticker = ticker self.price = None self.history = [] def setPrice(self, price): self.price = price self.history.append(price) def getPrice(self): return self.price def getTicker(self): return self.ticker def makeMove(self, bias): if self.price == 0.0: return baseMove = bias + random.uniform(-self.volatility, self.volatility) self.price = self.price * (1.0 + baseMove) if self.price < 0.01: self.price = 0.0 self.history.append(self.price) pythonhomeworkhelp.com
  • 10. class Market: def init (self): self.sectors = [] self.tickers = set() def addSector(self, sect): if sect.getName() in self.sectors: raise ValueError('Duplicate sector') for t in sect.getTickers(): if t in self.tickers: raise ValueError('A ticker in sect already in market') else: self.tickers.add(t) self.sectors.append(sect) def getSectors(self): return self.sectors def getStocks(self): stocks = [] for s in self.sectors: stocks = stocks + s.getStocks() return stocks def moveAllStocks(self): vals = [] for s in self.sectors: vals = vals + s.moveAllStocks() return vals pythonhomeworkhelp.com
  • 11. class Sector: def init (self, sectorName, bias): self.tickers = set() self.sectorName = sectorName self.stocks = [] self.bias = bias self.origBias = bias def addStock(self, stk): if stk.getTicker() in self.tickers: raise ValueError('Duplicate ticker') self.tickers.add(stk.getTicker()) self.stocks.append(stk) def getStocks(self): return self.stocks def getTickers(self): return self.tickers def setBias(self, newBias): self.bias = newBias def getBias(self): return self.bias def getOrigBias(self): return self.origBias def sameSector(self, other): return self.sectorName == other.sectorName def getName(self): return self.sectorName def pythonhomeworkhelp.com
  • 12. moveAllStocks(self): vals = [] for stock in self.stocks: stock.makeMove(self.bias) vals.append(stock.getPrice() ) return vals def generateSector(sectorSize, sectorName, bias): sect = Sector(sectorName, bias) for i in range(sectorSize): ticker = sectorName + 'Ticker ' + str(i) volatility = random.uniform(0.01, 0.04) stk = Stock(ticker, volatility) stk.setPrice(100) try: sect.addStock(stk) except ValueError: # Tickers are all different by construction, so this should never # happen print 'Error in generate stocks, should never reach here.' raise AssertionError return sect pythonhomeworkhelp.com
  • 13. def simMkt(mkt, numDays): endPrices = [] for i in range(numDays): if i%(TRADING_DAYS_PER_YEAR/4) == 0: for s in mkt.getSectors(): newBias = s.getOrigBias() + random.gauss(0, 2*s.getOrigBias()) s.setBias(newBias) vals = mkt.moveAllStocks() vals = pylab.array(vals) mean = vals.sum()/float(len(vals)) endPrices.append(mean) return endPrices def plotValueOverTime(endPrices, title): pylab.plot(endPrices) pylab.title(title) pylab.xlabel('Days') pylab.ylabel('Price') def generateMarket(numSe ctors, sectorSize, bias): mkt = Market() for n in range(numSectors): sect = generateSector(sectorSize, 'Sector ' + str(n), bias) mkt.addSector(sect) return mkt pythonhomeworkhelp.com
  • 14. def plotDistributionAtEnd(m kt, title): prices = [] for s in mkt.getStocks(): prices.append(s.ge tPrice()) pylab.hist(prices, bins = 20) pylab.title(title) pylab.xlabel('Last Sale') pylab.ylabel('Number of Securities') pythonhomeworkhelp.com
  • 15. import pylab, random class Stock(object): def __init__(self, price, distribution, vol): self.price = price self.history = [price] self.distribution = distribution self.vol = vol self.lastChangeInfluence = 0.0 def setPrice(self, price): self.price = price self.history.append(price) def getPrice(self): return self.price def makeMove(self, bias, mo): oldPrice = self.price baseMove = self.distribution(self.vol) + bias self.price = self.price * (1.0 + baseMove) self.price += mo*random.choice([0.0, 1.0])*self.lastChangeInfluence self.history.append(self.price) change = self.price - oldPrice if change >= 0: self.lastChangeInfluence = min(change, oldPrice*0.01) else: self.lastChangeInfluence = max(change, -oldPrice*0.01) pythonhomeworkhelp.com Solution
  • 16. def showHistory(self, fig, test): pylab.figure(fig) pylab.plot(self.history) pylab.title('Closing Prices, Test ' + test) pylab.xlabel('Day') pylab.ylabel('Price') class SimpleMarket(object): def __init__(self, numStks, volUB): self.stks = [] self.bias = 0.0 for n in range(numStks): volatility = random.uniform(0, volUB) distribution = lambda vol: random.gauss(0.0, vol) stk = Stock(100.0, distribution, volatility) self.addStock(stk) def addStock(self, stk): self.stks.append(stk) def setBias(self, bias): self.bias = bias def getBias(self): return self.bias def getStocks(self): return self.stks[:] pythonhomeworkhelp.com
  • 17. def move(self, mo): prices = [] for s in self.stks: s.makeMove(self.bias, mo) prices.append(s.getPrice()) return prices class Market(SimpleMarket): def __init__(self, numStks, volUB, dailyBiasRange): SimpleMarket.__init__(self, numStks, volUB) self.dailyBiasRange = dailyBiasRange def move(self, mo): prices = [] dailyBias = random.gauss(self.dailyBiasRange[0], self.dailyBiasRange[1]) for s in self.stks: s.makeMove(self.bias + dailyBias, mo) prices.append(s.getPrice()) return prices def simMkt(mkt, numDays, mo): endPrices = [] for i in range(numDays): pythonhomeworkhelp.com
  • 18. vals = mkt.move(mo) vals = pylab.array(vals) mean = vals.sum()/float(len(vals)) endPrices.append(mean) return endPrices def plotAverageOverTime(endPrices, title): pylab.plot(endPrices) pylab.title(title) pylab.xlabel('Days') pylab.ylabel('Price') def plotDistributionAtEnd(mkt, title, color): prices = [] sumSoFar = 0 for s in mkt.getStocks(): prices.append(s.getPrice()) sumSoFar += s.getPrice() mean = sumSoFar/float(len(prices)) prices.sort() pylab.plot(prices, color) pylab.axhline(mean, color = color) pylab.title(title) pylab.xlabel('Stock') pylab.ylabel('Last Sale') pylab.semilogy() pythonhomeworkhelp.com
  • 19. def runTrial(showHistory, test, p): colors = ['b','g','r','c','m','y','k'] mkt = Market(p['numStocks'], p['volUB'], p['dailyBiasRange']) mkt.setBias(p['bias']) endPrices = simMkt(mkt, p['numDays'], p['mo']) pylab.figure(1) plotAverageOverTime(endPrices, 'Average Closing Prices') pylab.figure(2) plotDistributionAtEnd(mkt, 'Distribution of Prices', colors[test%len(colors)]) if showHistory: for s in mkt.getStocks(): s.showHistory(test+2, str(test)) def runTest(numTrials): #Constants used in testing numDaysPerYear = 200.0 params = {} params['numDays'] = 200 params['numStocks'] = 500 params['bias'] = 0.1/numDaysPerYear #General market bias pythonhomeworkhelp.com
  • 20. params['volUB'] = 12.0/numDaysPerYear #Upper bound on volatility for a stock params['mo'] = 1.1/numDaysPerYear #Momentum factor params['dailyBiasRange'] = (0.0, 4.0/200.0) for t in range(1, numTrials+1): runTrial(True, t, params) runTest(3) pylab.show() pythonhomeworkhelp.com