Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · •...
Transcript of Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · •...
OperationsonStrings,ListsIntroductiontoFunctions
CS8:IntroductiontoComputerScience,Spring2019Lecture#4
ZiadMatni,Ph.D.
Dept.ofComputerScience,UCSB
Administrative• Hw02–dueTuesdayinclass• Lab01– dueonSundaybymidnight(11:59pm)onGradescope!
4/12/19 Matni,CS8,Sp19 2
LectureOutline• OperationsonStrings
• IntrotoLists&Tuple
4/12/19 Matni,CS8,Sp19 3
Yellow Band = Class Demonstration! J
Strings• Thesearealloktouse:
S='hello!'S="hello!"S="Isaid\"hello\"!"S='Isaid"hello"!'S="Isaid'hello'!"
4/12/19 Matni,CS8,Sp19 4
Notethealternateuseof“and‘
AddingaNewlineCharacter• Ifyouwanttoprintastringwitha“newline”characterin
it…– i.e.equivalenttohittingthe“Return”key
print("Hello!\nMynameisZed")Thiswillprintout:Hello!MynameisZed
4/12/19 Matni,CS8,Sp19 5
Recall:Indexing• Everycharacterinastringhasanindexassociatedwithit
• InPython,indexingalwaysstartsat0.– Sothe1stcharacterinthestringischaracter#0– Indexingiscalledoutwithsquarebrackets[n]
4/12/19 Matni,CS8,Sp19 6
I ' m h e r e !
0 1 2 3 4 5 6 7 8
IndicesandSlices• Tosliceastringintoasmallerstring,use[i:j]– Wherei=startingindex,j=endingindex(NOTincluded)– Example:"Gaucho"[2:4]is"uc"
• Combinationsarepossible!– Example,whatdoesthisspellout?(("o"+"Gaucho"[2:5]+"")*3)+"!"
4/12/19 Matni,CS8,Sp19 7
NegativeIndicesinStrings• If s="hello"• Then s[-1]="o" s[-2]="l",etc…
• Intheexampleabove, s[-2:]="lo" etc…
4/12/19 Matni,CS8,Sp19 8
Exercise1• Whatisthevalueofsafterthefollowingcoderuns?
s='abc'
s='d'*3+ss=s+e*2
4/12/19 Matni,CS8,Sp19 9
A.‘abcd3e2’B.‘abcdddabc’C.‘dddabcee’D.‘abcdddabce2’E.Error
Exercise2• Whatisthevalueofsafterthefollowingcoderuns?
s='abc'
s='d'*3+ss=s+'e'*2
4/12/19 Matni,CS8,Sp19 10
A.‘abcd3e2’B.‘abcdddabc’C.‘dddabcee’D.‘abcdddabce2’E.Error
SomeOperationsonStrings• GivenastringS,forexample,"Tunneling":
len(S) Lengthofstring e.g.9 S.upper() Makestringallupper-case e.g.“TUNNELING” S.lower() Makestringalllower-case e.g.“tunneling” S.find('n') Findthe1stoccurrenceof e.g.2 S.find('z') ifnotfound… e.g.-1
4/12/19 Matni,CS8,Sp19 11
Thesearecalled
methods
MoreStringMethodsAssume:name=‘Bubba’
• name.count(‘b’)is 2 ßcountshowmanytimes‘b’occurs
• name.count(‘ubb’)is 1 ßcountshowmanytimes‘ubb’occurs
• name.center(9)is ‘Bubba’ ßcentersw/spacesoneachside
• name.ljust(9)is ‘Bubba’ ßleftjustifiesnamein9spaces
• name.rjust(9)is ‘Bubba’ ßrightjustifiesnamein9spaces
• name.replace(‘bb’,‘dd’)is‘Budda’ ßReplacesonesub-stringforanother
4/12/19 Matni,CS8,Sp19 12
More(Fun)ctionswecanusewithStrings!
• Booleanoperatorsinandnotinaregreatwaystocheckifasub-stringisfoundinsidealongerstring
Examples:• “fun”in“functions” =• “fun”in“Functions” =• “Fan”notin“Functions” =
4/12/19 Matni,CS8,Sp19 13
True
True
False
ExampleAssumestrings=“hownowbrowncowmeow!”Whatis:• s.find(‘m’) =• s.find(‘r’) =• s.find(‘ow’) =• s.find(‘s’) =• s.replace(‘meow’,‘moo?’)=• ‘nc’ins =
4/12/19 Matni,CS8,Sp19 14
h o w n o w b r o w n c o w m e o w !0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
“ ”
1891-1
“hownowbrowncowmoo?!”True
note:onespacebeforemeownote:spacebetweennandc
Lists• Alistisacollectionofmultiplevalues
– Similartohowastrisacollectionofcharacters
• Note:InPython,listscanbeofheterogenous– Ofdifferenttypes(i.e.intsorstringsoretc…)
• Listscanalsohaveduplicatevalues• Listsaremutable:elementsofalistcanbemodified4/12/19 Matni,CS8,Sp19 15
ExampleofListsNameList=[“Abby”,“Bruce”,“Chris”]Student=[“JillJillson”,19,3.7,“F”]
NameListandStudentarevariablesoftypelist
• YoucancalluplistelementsbyindexingthelistExample:NameList[0]=“Abby”4/12/19 Matni,CS8,Sp19 16
SomeOperationsonLists• GivenalistL,forexample,[1,2,-5,9,0,1]:
len(L) Lengthoflist e.g.6 max(L) Maxvalueinalist e.g.9 min(L) Minvalueinalist e.g.-5 sum(L) Sumofallvaluesinalist e.g.8
4/12/19 Matni,CS8,Sp19 17
Mostlyusedonlistsof
numbers
Tuples• Tuplesareavariabletypethat’sverysimilartolists
– Excepttheyareimmutable!
– Thatis,oncethey’reset,theycannotchange
• Exampleofatuple:
collection=(1,2,“bucklemyshoe”,3,4)
• Youcancalluplistelementsbyindexingthelist
Example:collection[1]=2
4/12/19 Matni,CS8,Sp19 18
Functions
4/12/19 Matni,CS8,Sp19 19
FUNCTION
Input
Output
ProceduralAbstraction:TheFunction
• A“blackbox”–apieceofcodethatcantakeinputsandgivesmesomeexpectedoutput
• Afunction,forexample,isakindofproceduralabstraction 25àSquareRootFunctionà5
• What’shappeninginsidethefunction?• Doesn’talwaysmatter!...Aslongasitworks!!
4/12/19 Matni,CS8,Sp19 20
ProgrammedFunction• Does“something”toinput(s)andsendsbackoutput(s)
– Alwayshasparenthesesto“carry”theinputs– Theseinputsarecalledthefunctionarguments
• Example:thesqrt()function(findthesquareroot)– Withaninputof25,Iexpectanoutputof5– Thatis,sqrt(25)willgiveme(RETURNStome)5
4/12/19 Matni,CS8,Sp19 21
Function
Input
Output
MoreAboutFunctions
4/12/19 Matni,CS8,Sp19 22
• Definition:“Selfcontained”modulesofcodethataccomplishaspecifictask.
• Thefunctionoften(althoughnotalways)“returns”anoutput(result)• The“returned”outputislinkedtothefunctionname(examplescoming…)
• Sometimesthefunctiondoesnotreturnanything…
• Functionscanbe“calledfrom”themainblockofaprogram– Orfrominsideotherfunctions!
Function
Input
Output
MoreAboutFunctions
4/12/19 Matni,CS8,Sp19 23
• Afunctioncanbeusedoverandoveragain.
• Example:Considerafunctioncalled“distance”thatreturnsthevalueofthedistancebetweenapointw/coordinates(a,b)andtheCartesianorigin(0,0)
Wecan“reuse”thisfunctionwithdifferentvaluesforaandb!distance(2,4) distance(92,-41) distance(distance(1,1),4)
distance(a,b)=squarerootof(a2+b2)
DefiningYourOwnFunction• TodefineafunctioninPython,thenecessarysyntaxis: def functionName (parameters): # a block of statements appear here
# all of them must be indented (with tabs)
– def –amandatorykeywordthatdefinesafunction– functionName –anylegalPythonidentifier(e.g.myLittleFunction)– ( ):–mandatorysetofparenthesesandcolon– parameters –objectnames(canbenone,1param.,ormultipleparams.)
4/12/19 Matni,CS8,Sp19 24
ExampleDefinition#Myfirstfunction!Yay!defdbl(x):
"""Thisfunctionreturnsdoubleitsinputx"""print(“I’mdoublingthenumberto:”,2*x)return2*x #Ineedto“return”theresult
4/12/19 Matni,CS8,Sp19 25
Let’s try it out!
FUNCTIONRULES!#Myfirstfunction!Yay!defdbl(x):
"""Thisfunctionreturnsdoubleitsinputx"""print(“I’mdoublingthenumberto:”,2*x)return2*x #Ineedto“return”theresult
4/12/19 Matni,CS8,Sp19 26
Function header x is the input parameter (also called argument)
docstring: a comment that becomes part of Python's built-in help system! With each function be sure to include one that: a) describes overall what the function does, and b) explains what the inputs mean/are
Function body
Indentation: VERY IMPORTANT Achieved with a tab character or just spaces All the lines in the function body are indented from the function header, and all to the same degree
MoreExampleDefinitions#Thisfunctioncalculatesthedistancebetween(a,b)and(0,0)defdistance(a,b):
x=a**2 #Notethetabindent!!!y=b**2 #Recall**means“tothepowerof”z=(x+y)**0.5returnz #Ineedto“return”theresult
!!!Alternatively,Icanalsodothis!!!
defdistance(a,b):return((a**2)+(b**2))**0.5
4/12/19 Matni,CS8,Sp19 27
Let’s try it out!
FlowofExecutionofaFunction• DEFININGvs.CALLINGafunction• Callingishowyougetto“run”it
fromanotherplaceinthecode
• UseitsnameandargumentsASDEFINED
• Example:tocallthedblfunctionforaninputof21,you’dhavetocallitlikethis:dbl(21)
4/12/19 Matni,CS8,Sp19 28
defdbl(x):y=2*xreturny
……a=dbl(21)print(a)……
FunctionDefinition
FunctionCall
comesbeforethecall
WhatifThereareMultipleParameters??
• Whenyoucallafunction,thevaluesyouputinparenthesishavetobeintheorderinwhichtheyarelistedinthedefinition!
• Example:defsubtract(m,n):returnm–n
4/12/19 Matni,CS8,Sp19 29
Whenyoucallthisfunctiontodoasubtractionof5–99,then:mhastobe5andnhastobe99
So,it’scalledas:subtract(5,99)i.e.notsubtract(99,5)
WhatAbout…NOParameters?!• Sure,youcandothat!
• Example:deffortyTwo():return42
4/12/19 Matni,CS8,Sp19 30
Allthisfunctiondoesisreturnthenumber42towhoevercalledit!Whichwayshouldwecallit?
fortyTwofortyTwo()
Wow.FunctionsareCool.CanTheyCALLEACHOTHER????
Yes!!!!!!!!!!!!!!!Becarefulthatyougettheordercorrect…!
defhalve(x):"""returnshalfitsinput,x"""
returndiv(x,2)defdiv(y,x):"""returnsy/x"""
returny/xWhathappenswhenIsay:>>>halve(85)
4/12/19 Matni,CS8,Sp19 31
Let’s try it out!
A. Iget42B. Iget42.5C. 0D. 0.02352(i.e.,2dividedby85)
YOURTO-DOsq FinishreadingChapter2q StartreadingChapter3q FinishupHW2(dueTuesday)q FinishupLab1(dueSunday)
q Rememberofficehours/openlabs!J
q Eatyourgreens…
4/12/19 Matni,CS8,Sp19 32
4/12/19 Matni,CS8,Sp19 33