Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · •...

33
Operations on Strings, Lists Introduction to Functions CS 8: Introduction to Computer Science, Spring 2019 Lecture #4 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

Transcript of Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · •...

Page 1: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

OperationsonStrings,ListsIntroductiontoFunctions

CS8:IntroductiontoComputerScience,Spring2019Lecture#4

ZiadMatni,Ph.D.

Dept.ofComputerScience,UCSB

Page 2: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

Administrative•  Hw02–dueTuesdayinclass•  Lab01– dueonSundaybymidnight(11:59pm)onGradescope!

4/12/19 Matni,CS8,Sp19 2

Page 3: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

LectureOutline•  OperationsonStrings

•  IntrotoLists&Tuple

4/12/19 Matni,CS8,Sp19 3

Yellow Band = Class Demonstration! J

Page 4: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

Strings•  Thesearealloktouse:

S='hello!'S="hello!"S="Isaid\"hello\"!"S='Isaid"hello"!'S="Isaid'hello'!"

4/12/19 Matni,CS8,Sp19 4

Notethealternateuseof“and‘

Page 5: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

AddingaNewlineCharacter•  Ifyouwanttoprintastringwitha“newline”characterin

it…–  i.e.equivalenttohittingthe“Return”key

print("Hello!\nMynameisZed")Thiswillprintout:Hello!MynameisZed

4/12/19 Matni,CS8,Sp19 5

Page 6: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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

Page 7: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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

Page 8: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

NegativeIndicesinStrings•  If s="hello"•  Then s[-1]="o" s[-2]="l",etc…

•  Intheexampleabove, s[-2:]="lo" etc…

4/12/19 Matni,CS8,Sp19 8

Page 9: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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

Page 10: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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

Page 11: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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

Page 12: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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

Page 13: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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

Page 14: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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

Page 15: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

Lists•  Alistisacollectionofmultiplevalues

–  Similartohowastrisacollectionofcharacters

•  Note:InPython,listscanbeofheterogenous–  Ofdifferenttypes(i.e.intsorstringsoretc…)

•  Listscanalsohaveduplicatevalues•  Listsaremutable:elementsofalistcanbemodified4/12/19 Matni,CS8,Sp19 15

Page 16: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

ExampleofListsNameList=[“Abby”,“Bruce”,“Chris”]Student=[“JillJillson”,19,3.7,“F”]

NameListandStudentarevariablesoftypelist

•  YoucancalluplistelementsbyindexingthelistExample:NameList[0]=“Abby”4/12/19 Matni,CS8,Sp19 16

Page 17: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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

Page 18: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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

Page 19: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

Functions

4/12/19 Matni,CS8,Sp19 19

FUNCTION

Input

Output

Page 20: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

ProceduralAbstraction:TheFunction

•  A“blackbox”–apieceofcodethatcantakeinputsandgivesmesomeexpectedoutput

•  Afunction,forexample,isakindofproceduralabstraction 25àSquareRootFunctionà5

•  What’shappeninginsidethefunction?•  Doesn’talwaysmatter!...Aslongasitworks!!

4/12/19 Matni,CS8,Sp19 20

Page 21: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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

Page 22: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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

Page 23: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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)

Page 24: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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

Page 25: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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!

Page 26: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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

Page 27: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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!

Page 28: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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

Page 29: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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)

Page 30: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

WhatAbout…NOParameters?!•  Sure,youcandothat!

•  Example:deffortyTwo():return42

4/12/19 Matni,CS8,Sp19 30

Allthisfunctiondoesisreturnthenumber42towhoevercalledit!Whichwayshouldwecallit?

fortyTwofortyTwo()

Page 31: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

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)

Page 32: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

YOURTO-DOsq  FinishreadingChapter2q  StartreadingChapter3q  FinishupHW2(dueTuesday)q  FinishupLab1(dueSunday)

q  Rememberofficehours/openlabs!J

q  Eatyourgreens…

4/12/19 Matni,CS8,Sp19 32

Page 33: Operations on Strings, Lists Introduction to Functions · 2019. 9. 25. · • name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.center(9) is ‘ Bubba

4/12/19 Matni,CS8,Sp19 33