【第2章】《计算思维》实验报告1 Python【上海理工】_第1页
【第2章】《计算思维》实验报告1 Python【上海理工】_第2页
【第2章】《计算思维》实验报告1 Python【上海理工】_第3页
【第2章】《计算思维》实验报告1 Python【上海理工】_第4页
【第2章】《计算思维》实验报告1 Python【上海理工】_第5页
已阅读5页,还剩13页未读, 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

实验报告实验2-《计算思维》实验过程题目:Theareaofarectangleis

wh,where

w

and

h

arethelengthsofitssides.Notethatthemultiplicationoperationisnotshownexplicitlyinthisformula.Thisisstandardpracticeinmathematics,butnotinprogramming.WriteaPythonstatementthatcalculatesandprintstheareainsquareinchesofarectanglewithsidesoflength

4

and

7

inches.代码:print4*7运行结果:题目:Thecircumferenceofacircleis

2πr

where

r

istheradiusofthecircle.WriteaPythonstatementthatcalculatesandprintsthecircumferenceininchesofacirclewhoseradiusis

8

inches.Assumethattheconstant

π=3.14.代码:print2*3.14*8运行结果:题目:Theareaofacircleis

πr2

where

r

istheradiusofthecircle.(Theraised

2

intheformulaisanexponent.)WriteaPythonstatementthatcalculatesandprintstheareainsquareinchesofacirclewhoseradiusis

8

inches.Assumethattheconstant

π=3.14.代码:print3.14*8**2运行结果:题目:Given

p

dollars,thefuturevalueofthismoneywhencompoundedyearlyatarateof

r

percentinterestfor

y

yearsis

p(1+0.01r)y.WriteaPythonstatementthatcalculatesandprintsthevalueof

1000

dollarscompoundedat

7

percentinterestfor

10

years.代码:print1000*(1+0.01*7)**10或a=1c=1b=(1+0.01*7)p=1000whilea<=10:c=c*ba=a+1p=p*cprintp运行结果:题目:WriteasinglePythonstatementthatcombinesthethreestrings

"Mynameis",

"Joe"

and

"Warren"

(plusacoupleofothersmallstrings)intoonelargerstring

"MynameisJoeWarren."

andprintstheresult.代码:print"Mynameis"+"Joe"+""+"Warren"+"."运行结果:题目:WriteaPythonexpressionthatcombinesthestring

"JoeWarrenis52yearsold."

fromthestring

"JoeWarren"

andthenumber

52

andthenprintstheresult(Hint:Usethefunction

str

toconvertthenumberintoastring.)代码:print"JoeWarren"+"is"+str(52)+"yearsold."运行结果:题目:Thedistancebetweentwopoints

(x0,y0)

and

(x1,y1)

is

√(x0-x1)2+(y0-y1)2

代码:print((2-5)**2+(2-6)**2)**0.5或a=(2-5)*(2-5)+(2-6)*(2-6)printpow(a,0.5)运行结果:WriteaPythonfunction

is_lunchtime

thattakesasinputtheparameters

hour

(anintegerintherange

[1,12])and

is_am

(aBoolean“flag”thatrepresentswhetherthehourisbeforenoon).Thefunctionshouldreturn

True

whentheinputcorrespondsto11amor12pm(noon)and

Falseotherwise.Iftheproblemspecificationisunclear,lookatthetestcasesintheprovidedtemplate.Oursolutiondoesnotuseconditionalstatements.代码:defis_lunchtime(hour,is_am): """ Returnswhetherthegiventime,asrepresentedbythehour andis_am,islunchtime. """ return(hour==11andis_am)or(hour==12andnotis_am)deftest(hour,is_am): """Teststheis_lunchtimefunction.""" printhour, ifis_am: print"AM", else: print"PM", ifis_lunchtime(hour,is_am): print"islunchtime." else: print"isnotlunchtime."test(11,True)test(12,True)test(11,False)test(12,False)test(10,False)运行结果:WriteaPythonfunction

is_leap_year

thattakeasinputtheparameter

year

andreturns

True

if

year

(aninteger)isaleapyearaccordingtotheGregoriancalendarand

False

otherwise.TheWikipediaentryfor

leapyears

containsasimplealgorithmicrulefordeterminingwhetherayearisaleapyear.YourmaintaskwillbetotranslatethisruleintoPython.代码:defis_leap_year(year): """ ReturnswhetherthegivenGregorianyearisaleapyear. """ return((year%4)==0and((year%100)!=0or(year%400)==0))deftest(year): """Teststheis_leapyearfunction.""" ifis_leap_year(year): printyear,"isaleapyear." else: printyear,"isnotaleapyear."test(2000)test(1996)test(1800)test(2013)运行结果:WriteaPythonfunction

interval_intersect

thattakesparameters

a,

b,

c,and

d

andreturns

True

iftheintervals

[a,b]

and

[c,d]

intersectandFalse

otherwise.Whilethistestmayseemtricky,thesolutionisactuallyverysimpleandconsistsofonelineofPythoncode.(Youmayassumethat

a≤b

and

c≤d.)代码:definterval_intersect(a,b,c,d):"""Returnswhethertheintervals[a,b]and[c,d]intersect."""return(c<=b)and(a<=d)deftest(a,b,c,d):"""Teststheinterval_intersectfunction."""print"Intervals["+str(a)+","+str(b)+"]and["+str(c)+","+str(d)+"]",ifinterval_intersect(a,b,c,d):print"intersect."else:print"donotintersect."test(0,1,1,2)test(1,2,0,1)test(0,1,2,3)test(2,3,0,1)test(0,3,1,2)运行结果:WriteaPythonfunction

name_and_age

thattakeasinputtheparameters

name

(astring)and

age

(anumber)andreturnsastringoftheform

"%is%yearsold."

wherethepercentsarethestringformsof

name

and

age.Thefunctionshouldincludeanerrorcheckforthecasewhen

age

islessthanzero.Inthiscase,thefunctionshouldreturnthestring

"Error:Invalidage".代码:defname_and_age(name,age): """Returnsastringstatingtheperson'sage.""" ifage>=0: returnname+"is"+str(age)+"yearsold." else: return"Error:Invalidage"deftest(name,age): """Teststhename_and_agefunction.""" printname_and_age(name,age) test("JoeWarren",52)test("ScottRixner",40)test("JohnGreiner",-46)运行结果:WriteaPythonfunction

print_digits

thattakesaninteger

number

intherange

[0,100)

andprintsthemessage

"Thetensdigitis%andtheonesdigitsis%"

wherethepercentsshouldbereplacedwiththeappropriatevalues.Thefunctionshouldincludeanerrorcheckforthecasewhend

isnegativeorgreaterthanorequalto

100.Inthosecases,thefunctionshouldinsteadprint

"Error:Inputisnotatwo-digitnumber.".代码:defprint_digits(number): """Printsthetensandonesdigitofanintegerin[0,100).""" if0<=number<100: print"Thetensdigitis"+str(number//10)+",", print"andtheonesdigitis"+str(number%10)+"." else: print"Error:Inputisnotatwo-digitnumber." print_digits(42)print_digits(99)print_digits(5)print_digits(459)运行结果:WriteaPythonfunction

name_lookup

thattakesastring

first_name

thatcorrespondstooneof("Joe",

"Scott",

"John"

or

"Stephen")andthenreturnstheircorrespondinglastname("Warren",

"Rixner",

"Greiner"

or

"Wong").If

first_name

doesn'tmatchanyofthosestrings,returnthestring

"Error:Notaninstructor".代码:defname_lookup(first_name): """Returnstheinstructor'slastname.""" iffirst_name=="Joe": return"Warren" eliffirst_name=="Scott": return"Rixner" eliffirst_name=="John": return"Greiner" eliffirst_name=="Stephen": return"Wong" else: return"Error:Notaninstructor"deftest(first_name): """Teststhename_lookupfunction.""" printname_lookup(first_name) test("Joe")test("Scott")test("John")test("Stephen")test("Mary")运行结果:PigLatin

isalanguagegamethatinvolvesalteringwordsviaasimplesetofrules.WriteaPythonfunction

pig_latin

thattakesastring

word

andappliesthefollowingrulestogenerateanewwordinPigLatin.Ifthefirstletterin

word

isaconsonant,appendtheconsonantplus

"ay"

totheendoftheremainderoftheword.Forexample,

pig_latin("pig")wouldreturn

"igpay".Ifthefirstletterin

word

isavowel,append

"way"

totheendoftheword.Forexample,

pig_latin("owl")

returns

"owlway".Youcanassumethat

word

isinlowercase.Theprovidedtemplateincludescodetoextractthefirstletterandtherestof

word

inPython.Notethat,infullPigLatin,theleadingconsonantclusterismovedtotheendoftheword.However,wedon'tknowenoughPythontoimplementfullPigLatinjustyet.代码:defpig_latin(word): """Returnsthe(simplified)PigLatinversionoftheword.""" first_letter=word[0] rest_of_word=word[1:] #Studentshouldcompletefunctiononthenextlines. if(first_letter=="a"orfirst_letter=="e"orfirst_letter=="i"or first_letter=="o"orfirst_letter=="u"): returnword+"way" else: returnrest_of_word+first_letter+"ay"deftest(word): """Teststhepig_latinfunction.""" printpig_latin(word) test("pig")test("owl")test("python")运行结果:Challenge:

Givennumbers

a,

b,and

c,the

quadraticequation

ax2+bx+c=0

canhavezero,oneortworealsolutions(i.e;valuesfor

x

thatsatisfytheequation).The

quadraticformulax=−b±b2−4ac√2acanbeusedtocomputethesesolutions.Theexpression

b2−4ac

isthe

discriminant

associatedwiththeequation.Ifthediscriminantispositive,theequationhastwosolutions.Ifthediscriminantiszero,theequationhasonesolution.Finally,ifthediscriminantisnegative,theequationhasnosolutions.WriteaPythonfunction

smaller_root

thattakesaninputthenumbers

a,

b

and

c

andreturnsthesmallersolutiontothisequationifoneexists.Iftheequationhasnorealsolution,printthemessage

"Error:Norealsolutions"

andsimplyreturn.Notethat,inthiscase,thefunctionwillactuallyreturnthespecialPythonvalue

None.代码:defsmaller_root(a,b,c):"""Returnsthesmallerrootofaquadraticequationwiththegivencoefficients."""disc

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论