You are on page 1of 6

Problem Set 1

Handedout:Monday,September12,2016.

Due:11:59PM,Tuesday,September20,2016

ThisproblemsetwillintroduceyoutousingcontrolflowinPythonandformulatingacomputational
solutiontoaproblem.Itwillalsogiveyouachancetoexplorebisectionsearch.Thisproblemsethas
threeproblems.Youshouldsaveyourcodeforthefirstproblemasps1a.py,thesecondproblemas
ps1b.pyandthethirdproblemasps1c.py,andmakesuretohandinallthreefiles.Don'tforgetto
includecommentstohelpusunderstandyourcode!

Collaboration
You may work with other students however, each student should write up and hand in his or her
assignmentseparately. Be sure toindicatewith whomyouhave worked in a commentatthestartof
eachfile.

BeforeYouStart:ReadtheStyleGuide

Readthestyleguidesections1,2,and3.

PartA:HouseHunting

YouhavegraduatedfromMITandnowhaveagreatjob!YoumovetotheSanFranciscoBayAreaand
decidethatyouwanttostartsavingtobuyahouse.AshousingpricesareveryhighintheBayArea,
yourealizeyouaregoingtohavetosaveforseveralyearsbeforeyoucanaffordtomakethedown
paymentonahouse.InPartA,wearegoingtodeterminehowlongitwilltakeyoutosaveenough
moneytomakethedownpaymentgiventhefollowingassumptions:

1. Callthecostofyourdreamhometotal_cost.
2. Calltheportionofthecostneededforadownpaymentportion_down_payment.For
simplicity,assumethatportion_down_payment=0.25(25%).
3. Calltheamountthatyouhavesavedthusfarcurrent_savings.Youstartwithacurrent
savingsof$0.
4. Assumethatyouinvestyourcurrentsavingswisely,withanannualreturnofr(inotherwords,
attheendofeachmonth,youreceiveanadditionalcurrent_savings*r/12fundstoputinto
yoursavingsthe12isbecauserisanannualrate).Assumethatyourinvestmentsearna
returnofr=0.04(4%).
5. Assumeyourannualsalaryisannual_salary.
6. Assumeyouaregoingtodedicateacertainamountofyoursalaryeachmonthtosavingfor
thedownpayment.Callthatportion_saved.Thisvariableshouldbeindecimalform(i.e.0.1
for10%).
7. Attheendofeachmonth,yoursavingswillbeincreasedbythereturnonyourinvestment,
plusapercentageofyourmonthlysalary(annualsalary/12).

Writeaprogramtocalculatehowmanymonthsitwilltakeyoutosaveupenoughmoneyforadown
payment.Youwillwantyourmainvariablestobefloats,soyoushouldcastuserinputstofloats.
1
Yourprogramshouldasktheusertoenterthefollowingvariables:
1. Thestartingannualsalary(annual_salary)
2. Theportionofsalarytobesaved(portion_saved)
3. Thecostofyourdreamhome(total_cost)

Hints

Tohelpyougetstarted,hereisaroughoutlineofthestagesyoushouldprobablyfollowinwritingyour
code:
Retrieveuserinput.Lookatinput()ifyouneedhelpwithgettinguserinput.Forthisproblemset,
youcanassumethatuserswillentervalidinput(e.g.theywontenterastringwhenyouexpect
anint)
Initializesomestatevariables.Youshoulddecidewhatinformationyouneed.Becarefulabout
valuesthatrepresentannualamountsandthosethatrepresentmonthlyamounts.

Trydifferentinputsandseehowlongittakestosaveforadownpayment.Pleasemakeyour
programprintresultsintheformatshowninthetestcasesbelow.

TestCase1
>>>
Enteryourannualsalary:120000
10
Enterthepercentofyoursalarytosave,asadecimal:.
Enterthecostofyourdreamhome:1000000
Numberofmonths:183
>>>

TestCase2
>>>
Enteryourannualsalary:80000
Enterthepercentofyoursalarytosave,asadecimal:. 15
Enterthecostofyourdreamhome:500000
Numberofmonths:105
>>>

PartB:Saving,witharaise

Background

InPartA,weunrealisticallyassumedthatyoursalarydidntchange.ButyouareanMITgraduate,and
clearlyyouaregoingtobeworthmoretoyourcompanyovertime!Sowearegoingtobuildonyour
solutiontoPartAbyfactoringinaraiseeverysixmonths.

Inps1b.py,copyyoursolutiontoPartA(aswearegoingtoreusemuchofthatmachinery).Modify
yourprogramtoincludethefollowing
1. Havetheuserinputasemi-annualsalaryraisesemi_annual_raise(asadecimalpercentage)

2. Afterthe6thmonth,increaseyoursalarybythatpercentage.Dothesameafterthe12th
month,the18thmonth,andsoon.

Writeaprogramtocalculatehowmanymonthsitwilltakeyousaveupenoughmoneyforadown
payment.LIkebefore,assumethatyourinvestmentsearnareturnofr=0.04(or4%)andthe
requireddownpaymentpercentageis0.25(or25%).Havetheuserenterthefollowingvariables:
1. Thestartingannualsalary(annual_salary)
2
2. Thepercentageofsalarytobesaved(portion_saved)
3. Thecostofyourdreamhome(total_cost)
4. Thesemiannualsalaryraise(semi_annual_raise)

Hints

Tohelpyougetstarted,hereisaroughoutlineofthestagesyoushouldprobablyfollowinwritingyour
code:
Retrieveuserinput.
Initializesomestatevariables.Youshoulddecidewhatinformationyouneed.Besuretobe
carefulaboutvaluesthatrepresentannualamountsandthosethatrepresentmonthlyamounts.
,18th
Becarefulaboutwhenyouincreaseyoursalarythisshouldonlyhappenafterthe6th,12th
month,andsoon.

lease
Trydifferentinputsandseehowquicklyorslowlyyoucansaveenoughforadownpayment.P
makeyourprogramprintresultsintheformatshowninthetestcasesbelow.

TestCase1
>>>
Enteryourstartingannualsalary:120000
Enterthepercentofyoursalarytosave,asadecimal:. 05
Enterthecostofyourdreamhome:500000
Enterthesemiannualraise,asadecimal:.03
Numberofmonths:142
>>>

TestCase2
>>>
Enteryourstartingannualsalary:80000
1
Enterthepercentofyoursalarytosave,asadecimal:.
Enterthecostofyourdreamhome:800000
Enterthesemiannualraise,asadecimal:.03
Numberofmonths:159
>>>

TestCase3
>>>
Enteryourstartingannualsalary:75000
05
Enterthepercentofyoursalarytosave,asadecimal:.
Enterthecostofyourdreamhome:1500000
Enterthesemiannualraise,asadecimal:.05
Numberofmonths:261
>>>

PartC:Findingtherightamounttosaveaway

InPartB,youhadachancetoexplorehowboththepercentageofyoursalarythatyousaveeachmonth
andyourannualraiseaffecthowlongittakesyoutosaveforadownpayment.Thisisnice,but
supposeyouwanttosetaparticulargoal,e.g.tobeabletoaffordthedownpaymentinthreeyears.
Howmuchshouldyousaveeachmonthtoachievethis?Inthisproblem,youaregoingtowritea
programtoanswerthatquestion.Tosimplifythings,assume:
3
1. Yoursemiannualraiseis.07(7%)
2. Yourinvestmentshaveanannualreturnof0.04(4%)
3. Thedownpaymentis0.25(25%)ofthecostofthehouse
4. Thecostofthehousethatyouaresavingforis$1M.

Youarenowgoingtotrytofindthebestrateofsavingstoachieveadownpaymentona$1Mhousein
36months.Sincehittingthisexactlyisachallenge,wesimplywantyoursavingstobewithin$100of
therequireddownpayment.

Inps1c.py,writeaprogramtocalculatethebestsavingsrate,asafunctionofyourstartingsalary.
Youshouldusebisectionsearchtohelpyoudothisefficiently.Youshouldkeeptrackofthenumberof
stepsittakesyourbisectionssearchtofinish.Youshouldbeabletoreusesomeofthecodeyouwrote
forpartBinthisproblem.

Becausewearesearchingforavaluethatisinprincipleafloat,wearegoingtolimitourselvestotwo
decimalsofaccuracy(i.e.,wemaywanttosaveat7.04%or0.0704indecimalbutwearenot
goingtoworryaboutthedifferencebetween7.041%and7.039%).Thismeanswecansearchforan
integerbetween0and10000(usingintegerdivision),andthenconvertittoadecimalpercentage
(usingfloatdivision)tousewhenwearecalculatingthecurrent_savingsafter36months.Byusing
thisrange,thereareonlyafinitenumberofnumbersthatwearesearchingover,asopposedtothe
infinitenumberofdecimalsbetween0and1.Thisrangewillhelppreventinfiniteloops.Thereasonwe
use0to10000istoaccountfortwoadditionaldecimalplacesintherange0%to100%.Yourcode
shouldprintoutadecimal(e.g.0.0704for7.04%).

Trydifferentinputsforyourstartingsalary,andseehowthepercentageyouneedtosavechangesto
reachyourdesireddownpayment.Alsokeepinminditmaynotbepossiblefortosaveadown
paymentinayearandahalfforsomesalaries.Inthiscaseyourfunctionshouldnotifytheuserthatit
isnotpossibletosaveforthedownpaymentin36monthswithaprintstatement.P leasemakeyour
programprintresultsintheformatshowninthetestcasesbelow.

Note:Therearemultiplerightwaystoimplementbisectionsearch/numberofstepssoyour
resultsmaynotperfectlymatchthoseofthetestcase.

Hints

Theremaybemultiplesavingsratesthatyieldasavingsamountthatiswithin$100ofthe
requireddownpaymentona$1Mhouse.Inthiscase,youcanjustreturnanyofthepossible
values.
Dependingonyourstoppingconditionandhowyoucomputeatrialvalueforbisectionsearch,
yournumberofstepsmayvaryslightlyfromtheexampletestcases.
Watchoutforintegerdivisionwhencalculatingifapercentagesavedisappropriateandwhen
calculatingfinaldecimalpercentagesavingsrate.
Remembertoresettheappropriatevariable(s)totheirinitialvaluesforeachiterationofbisection
search.

TestCase1
>>>
Enterthestartingsalary:150000
Bestsavingsrate:0.4411
Stepsinbisectionsearch:12
>>>

4
TestCase2
>>>
Enterthestartingsalary:300000
Bestsavingsrate:0.2206
Stepsinbisectionsearch:9
>>>

TestCase3
>>>
Enterthestartingsalary:10000
Itisnotpossibletopaythedownpaymentinthreeyears.
>>>

5
MIT OpenCourseWare
https://ocw.mit.edu

6.0001 Introduction to Computer Science and Programming in Python


Fall 2016

For information about citing these materials or our Terms of Use, visit: https://ocw.mit.edu/terms.

You might also like