Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Introductiontoprogramming usingPython Session4 MatthieuChoplin [email protected] http://moodle.city.ac.uk/ 1 Objectives Tocomebackonthenotionofobjectandtype. Tointroducetothetype"List"anditsmethods. Tousethelen,min/max,sum,andrandom.shufflefunctionsforalist. Todevelopandinvokefunctionswithlistargumentsandreturnvalue. Toaccesslistelementsusingindexedvariables. Toobtainasublistusingtheslicingoperator[start:end]. Touse+,*,andin/notinoperatorsonlists. Totraverseelementsinalistusingafor-eachloop. Tocreatelistsusinglistcomprehension. Tosplitastringtoalistusingthestr’ssplitmethod. Tocopycontentsfromonelisttoanother. 2 Whatisthedifferencebetweenanobject andatype? Atypeoraclassiswhatisgoingtocreateanobject Typeandobjectseensofar: Types Objects Constructor Integer 1,3,4,5,999,-3,-4 int() Float 1.333,-0.5,0.001 float() String "Foo",'bar',"" str() 3 Anobjecthasmethods Youcanfindthemethodofanobjectwiththefunctiondir(), whichreturnstheattributesofanobject. >>>dir("abc") ['__add__','__class__','__contains__','__delattr__','__dir__','__doc__','__eq__','__format_ NB:thedundermethods(withdoubleunderscore),are "specialmethods"inpythonthatcanbeoverridden.Wewill comebackonthatlater. 4 Differencebetweenmethodsofobjectsand builtinfunctions Themethodsofanobjectcanonlybecalledonanobject. >>>"speaklouder".upper() 'SPEAKLOUDER' Abuiltinfunctiondoesnotneedanobjecttobecalled. >>>len("numberofcharacter") 19 NB:len()givethenumberofelementinasequence 5 ThetypeList Creatinglistusingthelistconstructor list1=list()#Createanemptylist list2=list([2,3,4])#Createalistwithelements2,3,4 list3=list(["red","green","blue"])#Createalistofstrings list4=list(range(3,6))#Createalistwithelements3,4,5 list5=list("abcd")#Createalistwithcharactersa,b,c Thatistheequivalentof: list1=[]#Sameaslist() list2=[2,3,4]#Sameaslist([2,3,4]) list3=["red","green"]#Sameaslist(["red","green"]) 6 TheListmethods Youcanfindthedifferentmethodsofalistthankstothe functiondir() >>>dir([]) ['__add__','__class__','__contains__','__delattr__','__delitem__','__dir__','__doc__','__eq Wearegoingtolookat:'append','clear','copy','count', 'extend','index','insert','pop','remove','reverse','sort' 7 Howtoseewhatamethodcando Lookatthebuiltinhelp: >>>help([].append) Helponbuilt-infunctionappend: append(...)methodofbuiltins.listinstance L.append(object)->None--appendobjecttoend Experimentintheinterpreter: main.py 1 2 3 4 Remix my_list = ["foo", "bar", 124, []] print(my_list) my_list.append("abc") print(my_list) 8 Summaryofthelistmethods append(x:object):None Addanitemxtotheendofthelist. insert(index:int,x: object):None Insertanitemxatagivenindex.Notethatthefirstelementin thelisthasindex0. remove(x:object):None Removethefirstoccurrenceoftheitemxfromthelist. index(x:object):int Returntheindexoftheitemxinthelist. count(x:object):int Returnthenumberoftimesitemxappearsinthelist. sort():None Sorttheitemsinthelist. reverse():None Reversetheitemsinthelist. extend(L:list):None AppendalltheitemsinlistLtothelist. pop([i]):object Removetheitematthegivenpositionandreturnit.The squarebracketdenotesthatparameterisoptional.Ifnoindex isspecified,list.pop()removesandreturnsthelastiteminthe list. 9 Exercise1 Writeaprogramthatreadsintegersfromtheuserandstorestheminalist(use input()andappend()).Yourprogramshouldcontinuereadingvaluesuntiltheuser enters'q'(thesentinelvalue).Thenitshoulddisplayallofthevaluesenteredbythe userinorderfromsmallesttolargest,withonevalueappearingoneachline.Use eitherthesortmethodorthesortedbuiltinfunctiontosortthelist. Solution 10 Builtinfunctionforlistorsequences >>>list1=[2,3,4,1,32] >>>len(list1) 5 >>>max(list1) 32 >>>min(list1) 1 >>>sum(list1) 42 >>>importrandom >>>random.shuffle(list1)#Shuffletheitemsinthelist >>>list1 [4,1,2,32,3] 11 Iteratingonalist Thelistisasequenceonwhichyoucaniterate. Withfor: main.py 1 2 Remix for element in ["foo", 11, "bar"]: print(element) Withwhile: main.py 1 2 3 4 5 Remix my_list = ["foo", 11, "bar"] i=0 while i < len(my_list): print(my_list[i]) i+=1 12 Reminderaboutfunctions Wedefinethefunctionlikethis: defmain(): print('Thefunction',main.__name__,'hasbeencalled') Andwecallthefunctionslikethis: main() NB:noticethebrackets:whenwedefineandwhenwecall! Trytousefunctionsinthenextexercises. 13 Exercise2:ChineseZodiacsignwithlist Simplifytheexercisewesawattheendofsession2byusinga listofstringstoringalltheanimalsname,insteadofmultipleif andelifstatement. Solution 14 PassingListstoFunctions main.py 1 2 3 4 5 6 7 Remix def printList(lst): for element in lst: print(element) # Invoke the function lst = [3, 1, 2, 6, 4, 2] printList(lst) 15 ReturningaListfromaFunction Example:afunctionthatreturnsareversedlist main.py 1 2 3 4 5 6 7 8 9 Remix def reverse(lst): result = [] for element in lst: result.insert(0, element) return result list1 = [1, 2, 3, 4, 5, 6] list2 = reverse(list1) print(list2) Thefunctionreverseactuallyexistsfordoingthesamething 16 Exercise3: Completethisprogramtogettheminimumnumberofthelist anditsindex importrandom random_list=[random.choice(list(range(1,100)))for_inrange(10)] defget_min(random_list): #tocomplete pass get_min(random_list) 17 Solutionwithoutusingbuiltinfunctionsnon listmethods Solution 18 Solutionusingbuiltinfunctionsandlist methods Solution 19 Reminder Thestringisasequence Theitemsofasequencecanbeaccessedthroughindexes Items (characters) a b r a c a d a b r a Indexes 0 1 2 3 4 5 6 7 8 9 10 Getthefirstelementofthesequence: my_string_variable="abracadabra" first_elem=my_string_variable[0] 20 ManipulateelementofaListwithindexes YoucanalsoaccesselementofalistwithindexesBUTyou canalsomodifythem: main.py 1 2 3 4 Remix my_list = ["foo", 11, "bar"] print(my_list) my_list[1] = "eleven" print(my_list) contrarytothestringtype. main.py 1 2 3 Remix my_string = "abracadabra" my_string[0] = "O" print(my_string) 21 Differencebetweenmutableandimmutable objects Youcannotmodifyanimmutableobjectsuchasastring. Youcanmodifyamutableobjectsuchasalist. 22 The+,*,[:],andinOperators(1/2) +isforconcatenatinglist *isforrepeatingalist [:]isthesliceoperator,forextractingasublistfromalist >>>list1=[2,3] >>>list2=[1,9] >>>list3=list1+list2 >>>list3 [2,3,1,9] >>>list3=2*list1 >>>list3 [2,3,2,3] >>>list4=list3[2:4] >>>list4 [2,3] 23 The+,*,[:],andinOperators(2/2) Getthelastelementofalistwithanegativeindex Checkifanelementisinalistwiththeinoperator >>>list1=[2,3,5,2,33,21] >>>list1[-1] 21 >>>list1[-3] 2 >>>list1=[2,3,5,2,33,21] >>>2inlist1 True >>>list1=[2,3,5,2,33,21] >>>2.5inlist1 False 24 Listcomprehensions Listcomprehensionsprovideaconcisewaytocreatelists Transformingalistwithoperationoneachelement Filteringalist,keepingonlyelementsthatsatisfya condition >>>list1=[xforxinrange(0,5)] >>>list1 [0,1,2,3,4] >>>list2=[0.5*xforxinlist1] >>>list2 [0.0,0.5,1.0,1.5,2.0] >>>list3=[xforxinlist2ifx<1.5] >>>list3 [0.0,0.5,1.0] 25 SplittingaStringtoaList Youcanconvertastringtoalistwiththesplitfunctionon string. >>>items="WelcometotheUK".split() >>>print(items) ['Welcome','to','the','UK'] >>>items="34#13#78#45".split("#") >>>print(items) ['34','13','78','45'] Youcanconvertbackalisttoastringwiththejoinfunction onstring >>>print(items) ['Welcome','to','the','UK'] >>>print("".join(items)) 'WelcometotheUK' 26 Exercise4-Eliminateduplicates Writeafunctionthatreturnsanewlistbyeliminatingthe duplicatevaluesinthelist.Usethefollowingfunctionheader: defeliminateDuplicates(lst): Writeatestprogramthatreadsinalistofintegers,invokes thefunction,anddisplaystheresult.Hereisthesamplerunof theprogram: Entertennumbers:1232163452 Thedistinctnumbersare:123645 27 Solution Solution 28 Exercise5=Anagrams Writeafunctionthatcheckswhethertwowordsare anagrams.Twowordsareanagramsiftheycontainthesame letters.Forexample,silentandlistenareanagrams.The headerofthefunctionis: defisAnagram(s1,s2): (Hint:Obtaintwolistsforthetwostrings.Sortthelistsand checkiftwolistsareidentical.) Writeatestprogramthatpromptstheusertoentertwo stringsand,iftheyareanagrams,displaysisananagram; otherwise,itdisplaysisnotananagram. 29 Solution Solution 30 CopyingLists Often,inaprogram,youneedtoduplicatealistorapartofa list.Insuchcasesyoucouldattempttousetheassignment statement(=): list1=[1,2,3] list2=list1 Butyouarenotcopyingthelisthere!Youarecopyingits reference. 31 Whatishappeninginmemory Python3.3 1 2 3 4 5 list1=[1,2,3] list2=list1 list2.append('four') print(list1) print(list2) linethathasjustexecuted nextlinetoexecute Printoutput(draglowerrightcornertoresize) [1,2,3,'four'] [1,2,3,'four'] Frames Globalframe list1 list2 Objects list 0 1 1 2 2 3 3 "four" <Back Programterminated Forward> VisualizedusingOnlinePythonTutorbyPhilipGuo 32 Copyingalistthecorrectway >>>list2=[xforxinlist1] >>>list2=list1[:] >>>list2=list(list1) >>>list2=list(list1) >>>importcopy >>>list2=copy.copy(list1) >>>list2=copy.deepcopy(list1)#willcopytheobjectaswell 33 Whatishappeninginmemoryforareal copy Python3.3 1 2 3 4 5 list1=[1,2,3] list2=list1[:] list1.append('four') print(list1) print(list2) linethathasjustexecuted nextlinetoexecute <Back Programterminated Forward> VisualizedusingOnlinePythonTutorbyPhilipGuo Printoutput(draglowerrightcornertoresize) [1,2,3,'four'] [1,2,3] Frames Globalframe list1 list2 Objects list 0 1 1 2 2 3 3 "four" list 0 1 1 2 2 3 34 PassByValue Thereareimportantdifferencesbetweenpassingimmutable ormutableobjectsasargumentstoafunction. Stringandnumericvalues(integerandfloat)areimmutable, theydonotgetchanged Listsaremutable,theycanbechanged 35 Example Python3.3 1 2 3 4 5 6 7 8 9 10 11 12 defm(number,list_of_numbers): number=1001 list_of_numbers[0]=5555 defmain(): x=1 y=[1,2,3] m(x,y) print("xis",str(x)) print("y[0]is",str(y[0])) main() Printoutput(draglowerrightcornertoresize) xis1 y[0]is5555 Frames Globalframe m main Objects function m(number,list_of_numbers) function main() linethathasjustexecuted nextlinetoexecute <Back Programterminated Forward> VisualizedusingOnlinePythonTutorbyPhilipGuo 36 Exercise6:Hangman Writeahangmangamethatrandomlygeneratesawordandpromptstheusertoguessoneletteratatime,as showninthesamplerun. Eachletterinthewordisdisplayedasanasterisk.Whentheusermakesacorrectguess,theactualletteris thendisplayed.Whentheuserfinishesaword,displaythenumberofmissesandasktheuserwhetherto continueplaying.Createalisttostorethewords,asfollows: words=["write","that","program",...] (Guess)Enteraletterinword*******>p (Guess)Enteraletterinwordp******>r (Guess)Enteraletterinwordpr**r**>p pisalreadyintheword (Guess)Enteraletterinwordpr**r**>o (Guess)Enteraletterinwordpro*r**>g (Guess)Enteraletterinwordprogr**>n nisnotintheword (Guess)Enteraletterinwordprogr**>m (Guess)Enteraletterinwordprogr*m>a Thewordisprogram.Youmissed1time Doyouwanttoguessanotherword?Enteryorn> 37 Solution 38