### Create a StudySoup account

#### Be part of our community, it's free to join!

Already have a StudySoup account? Login here

# Concepts of Computing ECS 010

UCD

GPA 3.75

### View Full Document

## 47

## 0

## Popular in Course

## Popular in Engineering Computer Science

This 52 page Class Notes was uploaded by Ashleigh Dare on Tuesday September 8, 2015. The Class Notes belongs to ECS 010 at University of California - Davis taught by Michael Gertz in Fall. Since its upload, it has received 47 views. For similar materials see /class/187735/ecs-010-university-of-california-davis in Engineering Computer Science at University of California - Davis.

## Reviews for Concepts of Computing

### What is Karma?

#### Karma is the currency of StudySoup.

#### You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 09/08/15

10 Basic Concepts of Computing Prof Michael Gertz gertzcsucdavisedu April 14 2008 Announcements l Assignment 2 will be posted tomorrow Tuesday I For programming in Python make also use of online sources eg tutorial at htt docs thonor tut tuthtml see also httpq wwwpythonorgg docg I Information about 1st midterm Monday April 21 will be posted starting Wednesday this week I Sample midterm l Solutions to sample midterm l Sections of the textbook to study I 1st midterm has a multiplechoice and a program part 2 In the previous lecture I Strings are indexed 0 length of the string 1 lenx c OMP U T E R s c1 ENC E O 2345678910lll2131413 l Individual characters and substrings can be accessed and assigned to variables lt stringgt startend ltstringgt position var COMPUTER lenvar is 8 subvar var25 MPU l strX 9 string return a string containing a nicely printable representation of an object I For all the builtin functions see also htt docs thonor lib built in funcshtml Sections I Loop Structures 26amp81 I So far Algorithm Recipe Program I Linear sequence of instructions Python statements typically input sequence of computations output I In practice one often needs to repeat the same sequence of instructions several times l depending on the user input I depending on some computation I Sum ofN numbers NI Loop Structures I There are different types of loops l Definite loops for loops typically based on some computed number I Inde nite loops while loops typically based on some condition that is evaluated to true or false I Example algorithm for computing average I Input the count of the numbers n I Initialize sum to O l Loop n times I Input a number x I Add x to sum l Output average as sumn Forloops l Pattern Note the indentationll for ltvaria in ltsequencegt lt oop bodygt some computations input etc I A useful built in function to compute a sequence list of integers is the range function gtgtgtrange10 0 1 2 3 4 5 6 7 8 9 gtgtgt range1113 mum Elle Edlt Format Bun gamma Wmdows Help 1 4 7 10 Most simple example for i in range 10 Debug ggnons Wlndows Help IDLE 1 21 gtgtgt for 1 Ln rangel print 1 print i Note that here i starts with 0 This is always the case if you don t specify a start explicitly A more complex example Eile Edit Fgrmat Run thinns windows Help n inputquotHow many numbers do you have sum U for i in rangem inputquotEnte a number gtgt quot Su x print quotnThe average of thequot n quotnumbers isquot sumn Python Shell Elle Edit Shell Debug thions lndows Help gtgtgt A How many numbers do you have 3 Enter a number gtgt 55 The average of the 3 numbers is 37 gtgtgt and one more I Compute the sum of N integers N is input by the user h N Ehould I arld up quot range 1N1 i m U inputquotUp to whi 1 i n sum sum quoti quot sum yNy quot quotI ii sum of the tlLStquot poSltl ie int Up to which N should I ad up 5 i 1 5 i 2 s i 3 E l 4 1D 1 5 s 15 The lsum of the first 5 positive integers is 15 gtgtgt Comments on the previous loop sum 0 N 39inputquotUp to which N should I add up quot for 39i 39in range1N1 sum s m 39i pr39int quot39i quot 39i quotsum quot sum print quotThe sum of the firstquot N quotpositive integers 39isquot I When programming it is sometimes useful to add some HdebugH info I adding print statements can help to find problems I Concepts to understand I Variable initialization sun 0 I iteration variable the one bound Via for ltvaxiablegt in l Hacculnulator VariableH sun is updated in each round of the loop the loop is de nite or bounded before entering We know how many times we39ll go through the loop ie how often We iterate I block structure indent the loop body in Sometimes we don39t need a loop 39 Carl Friedrich Gauss GauB 30 April 1777725 Februag 1855 was a German mathemaucian and scientist of profound genius who contributed signitiiandy to many elds induding number theog anal sis differential gometgz eode mm an m Semetimes known as the prinoe of mathematicians and greatest mathematician since in uenuai mathematicians Gauss was a child prodigy ofwhom there are many anecdotes pertaining to his astounding precocity while a mere toddier an made his rst groundbreiiring mathematicai discoveries while sun a teenager making them add up the integers from 1 to 100 The young Gauss produced the correct answer Within seconds by a ash of Wlk mm in mm w it mathematical insight to the astonishment ofall Q How do you compute the sum of1 2 n without a for loop Sequences 4 3 I A sequence IS an ordered collection of objects I Printed enclosed in brackets the brackets are not part of the sequence I Examples I Lists I 5113 7 no reason they have to be in sorted order I r p s e a se uence ofonerletter strin s I yar Haye nice day 7 asequence Ofstrmgs I for experts only y lists can be nested I Strings I abcd 7 this is a sequence of characters indexed I Operations note that sequences are indexed l we can a u sequences 1e concatenate them I ab cd 9 ab d remember the 1 1 gt I print yar1yar3 9 aday n More forloop examples Pymquot Shell 39 Edt D b D t W d H for 1 ln Urllz393 ix eug j oh imows ep print quot1 quotF i No Subprocess gtgtgt for x in l234 print quot2 x y print y quot y for i in rangel print0vr i quotIn 392ir quotJquot quotUnrollingquot a for loop for X in 123 10 Basic Concepts of Computing Prof Michael Gertz gertzcsucdavisedu April 11 2008 Announcements I Assignment 1 is due today at 10pm I Assignment 2 will be posted this upcoming Monday Tuesday I Read recommended secnons in the textbook I indicated on slides and on Web page with lecture notes I Try the examples I present in class get a feeling for different concepts in Python In the previous lecture I IDLE Programming versus IDLE Script window I Program resides in programming window and interaction with program user input and output occurs in shell window gtgtgt I Integers and oating point data types I Type conversions int oat l roundlt oatgt decimal points I Strings yet another data type I are uninterpreted eg 25 l 25 Section I Strings are Uninterpreted 41 l l Hblah blah blahH just a string of characters gtgtgt typeC39blah blah blahquot lttype str gt l 2 5 l H2 5quot l means does not equal I type25 is 39int39 and type 25 is 39str39 gtgtgt mydog HRoverH gtgtgt print mydog Rover gtgtgt print HmydogH mydog Conversion between numbers and strings I The builtrin functions int oat and Str allow you to convert from a number to a string and vice versa l int 5 is the integer 5 l oat 38 is the oatingrpoint number 38 l Str5 is the string quot5quot The program window and shell window provide some help Untitled39 KNEE Ewe gar Format Bun ggnons Windows Help n nEL H nrLgtltr hasEN 7gt nLEger info 39int is a function returning an integer Builtin Functions I int oat and str are functions purple in IDLE I Like in algebra y fX I Python computes the value of a function just like it computes the value of an expression I The value of intquot5quot is the integer 5 int l Similar The Value of str6 I smn is the string quot 6quot Overloading When Does 1 1 11 l Two uses ofthe sign I integer division 7 2 3 l oat division 70 20 35 I Python is smart I 70 2 35 I It quotconvertsquot 2 to 20 then does oat division I Two uses of the sign I 1 1 2 l quot1quot quot1quot quot11quot quot1quot 1 gt999 Common String Mistakes print 39My dog39s name is mydog He39s always hungry pull variable must escape must escape out of quotes quOte quote print 39My dog39s name is 39 mydog 39 He39s always hungryV print quotMy dog39s name is quot mydog quot He39s always hungryquot Section One more note on strlngs 41 l A string is a sequence of characters such a sequence is indexed by numbers Index starts with 0 and ends with 71 1 where 74 is the length of the string gtgtgt lenquotCOMPUTER SCIENCEquot 16 gtgtgt Var quotCOMPUTER SCIENCE gtgtgt print lenVar 16 len is a builtein function gtgtgt my1en lenVar gtgtgt print my1en 10 160 Section One more note on strlngs 42 var COMPUTER SCIENCE COMIPIUITER ISICII ENCE 0 1 2 3 45 6 7 89101112131415 print Var2Var4var9var11Var14 9 MUSIC One can access individual characters and substrings using ltstringgtstartend from start to end excluding end Var08 9 COMPUTER mm mpg 9 PUTER 9 9 SCIENCE Var916 Var Var 1 9 E Var92 9 C Vare16 9 C Summary I Differences between Integers and Strings I They actually mean different things I Strings are not quotinterpretedquot l and also does different things when it39s between two strings and when it39s between two integers I this is called overloading of symbols l similarly between ints and between oats is sth different I between lists is again different I and another one X Y is very different depending on whether X Y are ints or oats I Loop Structures 26amp81 I So far Algorithm Recipe Program I Linear sequence of instructions Python statements typically input sequence of computations output I In practice one often needs to repeat the same sequence of instructions several times I depending on the user input l depending on some computation I I Sum ofN numbers NI Loop Structures I There are different types of loops l Definite loops for loops typically based on some computed number I Inde nite loops while loops typically based on some condition that is evaluated to true or false I Example algorithm for computing average I Input the count of the numbers n I Initialize sum to O l Loop n times I Input a number x I Add x to sum l Output average as sumn Forloops l Pattern Note the indentationll for ltvaria in ltsequencegt lt oop bodygt some computations input etc I A useful built in function to compute a sequence list of integers is the range function gtgtgtrange10 0 1 2 3 4 5 6 7 8 9 gtgtgt range1113 mum Elle Edlt Format Bun gamma Wmdows Help 1 4 7 10 Most simple example for i in range 10 21 gtgtgt far 1 Ln rangel print 1 print i Note that here i starts with 0 This is always the case if you don t specify a start explicitly 10 Basic Concepts of Computing Prof Michael Gertz gertzcsucdavisedu April 16 2008 Announcements I Assignment 2 has been posted due Wednesday next week 10pm I Informanon about 1st midterm Monday April 21 has been posted to class Web site I sample midterm plus solutions I relevant sections in the textbook I Get a Scantron 2000 buy at the bookstore ll l the midterm is open books and open notes no electronic devises are allowed I know your section number In the previous lecture I Forloop structures l for i in ltsequencegt lt10 op b odygt Sections l Iterator variable i ranges over a sequence of objects objects can be numbers strings etc I Builtein function rangestartendLstep generates a list of integers eg rangel9 9 12345678 l Iterator variable i takes on the values of the objects in ltsequencegt from the beginning to the end of the list I A list is a sequence of indexed objects 0 lenGist 1 I L Z 3579 LO Z 3 L3 Z 9 l R Z LO2 25 9 Rbecornes 3525 More forloop examples Elle Edlt Debug thlons andows Help for i in 0lr253ll print 39 u in l l IDLE 121 No Subprocess gtgtgt 1 Z El 1 Z l 1 Z 2 for x in 1234 gt3 print Zquot 2 Wm x x print quot3 Zquot 3 for i in range printm if n Izii39 n1 quotUnrollingquot a for loop 1 s M for X in 123 3321 x 1 4 Axum 7 EVquot 7F Using lists beastList quotcowquotquotsheepquotquotduckquot for i in beastList print quotAquot i His an animalquot beastLiSt quotcowquot quotsheepquot quotduckquot for i in range lenbeastList print quotAquot beastListi quotis an animalquot Computing N 1 2 N in a for loop quot numbers 7 multlpl N input quotHow n P l f r i Ln rangslN1 wrm i quot1 P 9 4 i punt quotnquot N quotf ts39 P HM quotDONEnquot Exercls modify the program so that it does not it prlnt Im last Py hunShell EHe det Debug gamma andows gtgtgt How many numbers to multlply 5 leg 3 4e5eee7ea 80110quot 1D factorlal 15 BEZEEDD 33 DONE Some more forloop patterns Return s new llst wlth every other element from L New 1 for 1 1n rsnge1renL2 New New L1 1 print NewiL etur s 39zlpped39 verslon of L1 and L2 stopping at snorter llst Ll 5152535 L2 1n2n3n4n enl len 1 L1 len2 enL2 shortilen m1nlenly len2 Zipped L 1 f z 1 In range shortilen Zipped lepediL L11 L2 1 1 prmt lepediL bulltrrn funcuon minarguments Wrth a angle argument r return the smallest 1tem of a nonrempty sequence such as a stung Lnteger or hst Wrth more than one argument return the smallest of the arguments max works analogous Summary Forloops and sequences I A string is a sequence of characters I 39Here I use single quotes I quotAnd now I use double quotesquot I A list is a sequence oflist elements objects I 3143gt quotaquot Hword gt Hplease yeahquot I Sequences are indexed and objects can be accessed directly using index position I The function range creates a list ofintegers I We can loopiterate over a list of objects numbers or strings using a for loop Section 82 From for to Whileloops Whileloops I General form while ltcanditiongtz ltbodygt l repeatedly executes ltbodygt as long as the ltcanditiangt remains True I Conditions can be built from I variables constants expressions I Comparison operators lt gt lt gt and l boolean operators and or not Let39s try it out in IDLE farwhile cInamalganznaacningnuwqo EEJ EHe Ed t Format Run QDUONS WmeWS deb N 1nputquotHow many loops today quot good old foriloop prlnt quotnbefore foriloopquot for 1 1n range N prlht 1 quotsquared 13quot 1 1 pr1n quotafter foriloopquot now another way to do the same punt quotnbefore whlleiloopquot 1 n while 1 lt nt 1 quotsquared 15quot 1 1 1 whlleiloopquot 1 1 pr1n quotafter A simple forloop and its two hard workingtedious while quotcousinsquot furwhilelpy Chnmgen1Teaching10WQOEEcviptsandlugsmzvwhi 39 Elle Edlt Format Bun QDUOHE Wlndows d p t and lterate over it for e lD L print e nL end lnd lt N while the l e ge he current elenent int print e ome c putsti 4 on and move on to the next list element and another one using while p L for bookkeeping let39s use Litmp Litmp 39 while there are more get the flrst one 4 print e L tnpu elements into e e itmp Litmpll dlscard the first element LitmpE whileloops vs forloops I forloop I always terminates l eg for x in L detelmlne lenL 9 as many ltelauons I cannot handle all situations 9 next exalnple I whileloop I very powerful loop construct I does not always terminate 9 well see an exalnple 10 Basic Concepts of Computing Prof Michael Gertz gertzcsucdavisedu June 2 2008 Announcements I Assignment 6 is due this Wednesday at 10pm I Final l Thursdayune 12 1030am1230pm l Open book and open notes get Scantton form I Sample nal and solutions will be posted in the next couple of days I Further information about nal in particular topics will be posted on class Web site I Pick up midterms in extra of ce hours to be announced In the previous lecture I Matrix operations I Determine suitable data structure to mange matrices list of lists I Check for correct matrix and develop operations such as matrix addition multiplication scalar multiplication etc that are just useride ne functions that do some list processing l Trick Know how to represent a matrix lKnow how to access elements in a 11st ofhsts IL 123987434 L12 9 7 How to represent a matrix whyu matrix a n mmmns I A m X n matrix has m in rows and n columns an an a 7 I What Python data a 577 an V a a i a structure canwe use to represent a matrixgt l Let s use a 11st structure 1e a matrix A is represented as a 11st ofhsts Each hst element represents a row 9 8 A 1 2 7 A986 127 492 6051 4 9 2 6 0 5 Matrix Multiplication 2 lExample 31 10 1217 1x30gtlt22gtlt1 1gtlt10gtlt12gtlt0 7 51 71 31 1 0 71x33gtlt21gtlt171gtlt13gtlt11gtlt0 4 2 l HA is a m X 71 matrix and B is a 71 Xi matrix then the result matrix C A B is of dimension 7 Xi l Let s first think about how to check that number of columns in A is the same as the number of rows in B Matrix Multiplication 3 l Check Whether matrices match manixmultpy cnumeuenznexmnguow BEE Elle Edit FQrmat film thlona indowa Help 21H False 3 l I mam program 1 O 2 matA 1n21 71311 1 3 l matE 311 211 1011 1 D matchMul v quotTth iop39t matchquot mimme umzuenzneuhmgno lotus p nd EHe ijt Fq39mat Run QDtxons Windows Help 7 39 mamuluma T owsA rowsE ientA lenE 39 colsA c0155 lHADly munch Matnx c 1 Multiplication r 1 n rangerowsA Jew v39 3 ranglcols c139 u L r k n rangecolsA 150 be tom3E can a can c1j 0111ch leumw Cirow append c ij Cappendc7row r H c 4e warn mam mam1n21713111 1x30gtlt22gtlt1 1x10gtlt12gtlt0 matE 31y 21 10 71X33X2lxl 71x13x11x0 E Resultnatrix ma MultlmaEA meta r matchmultmam mat is n r ResulCMatrix Hut quot391 ltu39v maulquot Ln 1815 Finishing the library I Have all useridefined functions in a single file named say myMatriXpy I In your program you then include this library like any other library import myMatriX Materials for Study I Lecture material I Textbook I All assignments I Midterm 1 and midterm 2 I Sample nal I Discussion notes Topics l Chapter 2 Simple programs I Names expressions statements I Assignment statements assigning input I Chapter 3 The number data gape l Math library type conversions oat int l Chapter 4 Computing with strings I Simple string processing l Strings and lists operations and functions on strings and lists split upper 0 lower l File processing Topics 2 I Chapter 5 Objects and graphics I Concept of objects and methods I Graphics objects I Simple drawing methods I Chapter 6 Defining functions I User de ned functions and parameters l Local versus global variables I Functions and program structure Topics 3 l Chapter 7 Decision Structures l If then else elif structures I Chapter 8 Loop Structures and Booleans l In nite while loops l Finite for loops range function I Nested loops see also matrix examples I Boolean operators and algebra I W l Lists and list operations sort reverse l Dictionaries non sequential collections Boolean Variables X 5 a xgt2 b Xlt4 print not a or not b lWhat does this program do Boolean Variables x 5 a Xgt2 b xlt4 priLt not a or not b lThe value ofa is True lThe value ofb False lThe value of not b is not False is True I So the program prints True Dictionaries D frequency of letters in English D e l Dcct9 2 D a 3 for i in range3 print D il I What does this program do Dictionaries D frequency of letters in English Dcce 1 D t33 2 D a 3 for i in range3 print D il I It crashes because D1 does not exist I Keys here are letters not integers I How could you store this data and print it out 16 When to use a List D frequency of letters in English ea t a for i in range14 print D i I Better to use a list since we want to access the data using a small range of integer indices in order Dictionaries key rawinput Choose a letter if key in D print D key I Use this construct ifyou can t be sure the key is in the dictionary I Keys are letters not integers I Indexing with a non key causes a crash Dictionaries D letters 2 abcdefg for i in rangelenletters Dlettersi i print D C I What does this program do Dictionaries D letters abcdefg for i in rangelenletters Dlettersi 1 print D c I D is a dictionary letters are keys values are ints I rangeaenaetters is O123456 D a 0 D b 1 I Prints 2 Lists of Lists L 3 0 for i in range3 L L i i1 I What is L after these lines Lists of Lists L 3 0 for 139 in range3 L L i i1 I i i 1 is a list ofintegers with length 2 I i i1 is a list oflists with length 1 L is 3 0 0 1 1 2 2 3 I L is a list ofintegers and lists with length 5 I How would you get a list of lists Lists of Lists L 3 0 for i in range3 L L i i1 I Now L begins as a list oflists with length 1 I We concatenate a list oflists with a list oflists I Usually a good idea to concatenate lists of the same type of objects but not required by Python Functions def cleanStrings out sreplace inStr 34308 cleanStringinStr x int0ut I What does this program do Func ons def c1eanStrings out sreplace inStr 34308 clem1StringinStr x int0ut I Crashes I The local variable out is unde ned in the main program it has not been declared Func ons def cleanStrings 5 Sl eplace 3gt my inStr 34308 cleanStringinStr x intinStr I How about this one Func ons def c1eanStrings S SI 1laequotquot9393 my inStr 34308 cleanStringinStr X inti115tr I Also crashes Functions don t change their arguments inStr is de ned but cannot be converted I How do you write this program correctly Func ons def cleanStrings S SI39eplace my l39Etlll39ll S inStr 34308 newStt cleanStringinStr x intneWStr I Information is sent back to the main program With the return value I In the main pro ram it has to be assigned to a variable newStr 10 Basic Concepts of Computing Prof Michael Gertz gertzcsucdavisedu April 18 2008 Announcements l Assignment 2 is due Thursday April 24 at 10pm electronically through MyUCDaVis l Information about midterm 1 has been posted at http rlhi nrrlq i win r mlr P PC 107 OUR 9 am html I Sample midterm solutions 50 mins midterm l Relevant sections in the textbook l You ll need a Scantron 2000 form buy at bookstore and a pencil I You can use your books and notes but no electronic devices such as a pocket calculator laptop etc I Know your section number I Midterm 15 multiplechoxce own 5 Mmmmemmnwm queenene to be answered x on Scantron 2000 form 1 punt y yw 231 ShortP then to mm y P g m munwkmn39lcmvcmenmewquc nrwvlhw to be answered on paper rm 2 my 4 b and enar mm out m range my 232 0 LE nmr m me we Whilelo Op 5 E General foun while ltmnditiangt ltbodygt repeatedly executes ltbodygt as long as the ltcmlditiangt remzms Tm l Condmons can be built from variables constants expxessions comparison opemm Boolexn opemou and or not Let39s try it out in IDLE a now another way ro at the same ll 39 quot nb f lr Whl ouLquot N l quotejuated isquot l t l wtglerlowpquot A simple forloop and its two hard workingtedious while quotcousinsquot furwhile2py ChnmegenxTeaching10WQO chiptsandlngsmzvwhi El E18 e un thlons WmeWS Help and move on to the next 115 element and another one uslng lle L f0 bookkeepl l l 7 p Whila Litmp 1e 1 whlle there are more elements e LitmpE get the flrst one 1nto e print e prlnt e Litmp Litmpl dlscard the flrst element LitmpE Ln 2 al 33 Whileloops vs forloops I forloop l always terminates l eg forx in L determine 1enL as many iterations l cannot handle all srtuattons 9 next example I Whileloop l very powerful loop construct l does not always terminate 9 we ll see an example Example HRe alH Whileloop ter iniciar Capltal get 1nputquotEnter target Capltal quot rate 1nputquotEnter luterest ate quot in percent Capltal initial earu thls Capltal lt target Capltal Capltal 1rate1EIEIEI year year 1 print quotafter yearquot year quot77gtquot roundcap1tal2 hrlnl quotr rakesquot year quotyears to reachquot roundcap1tal2 l Earlrer examples stulate for usrng While I Here number of roundsH 1s not known ahead of ume ar pr1or1 but only afterwards Whileloops Python Shell H H 39 Ed Debug m0 WWW deb j I when number of rounds 15 Enter 1n1t1a1 Capltal 1mm 39 m m t ital m not known 1n advance 9 use nter 1ntereet rate 111 percent 3 arter year 1 77gt 1u3n Whlle loop else for loop afte ear 2 i gt 1U6 U9 2 Y j gt 333 I Termlnatlon becomes a aft year 5 gt 115 93 after year 6 a gt 11941 P10 em afte year 7 a gt 122 99 after year 8 r gt 12668 I what happens for negat1ve rate aft year 9 gt 13D 48 aft ye r 1U gt 13439 39 39 39 39 39 39 39 after year 11 gt RE I What 1f1n1t1al cap1tal 1s negatlve afte yea 12 gt 14258 after year 13 gt 14685 I Showmg that a Whlle loop ft ear 14 15126 I ft yer1 rgt155a after year 16 gt 1m terminates can be hard afte yea 17 gt 16528 after year 18 gt 17n24 l for the sav1ngs program we can ft e r 19 17535 d 111 21 39 ft ye r 2 r gt 1Ene1 0 e 211 y515 after year 21 gt 186U3 afte yea 22 gt 19161 I 1n general we m1ght not be able after year 23 gt 19736 after year 24 a 21328 to do that 9 Halt1ng Problem It takes 24 years to reach 21328 gtgtgt A 1n CS IT 54571 3 9 Emergency Brake l Inde nite loops often lead to a classical programming bug I What do you doesn t stop do if you have programmed a While loop that l Repeat after me Ctrl c 1 U while i lt D rint i quotI am stuckllquot never gets here print quotI am outlquot Sections 831 amp 83 One more simple example test CIDncumEnts and SettingslMichaellDlsktnpltest F un gamma Windows He p gt var 1nputquotPlease enter a number n for endl quot total total var prlnt total I Here we make the teiInination condition dependant on the user input I But better let the user know about this behavior Summary I Definite and indefinite loops provide important programing language constructs l forloops I always terminate l iterator variable takes on values of objects in a list I Whileloops I Do not always terminate it is easy to introduce such a Programming bug I Often provide more flexibility especially if I number of iterations is not known in advance temnahon depends on a complex condmon Decision structures I Introduce control structures in your program code that allow the program to execute different sequences of instructions for different cases I 75 Mr I if temperature gt 90 print quotI need a cold drinkH print or hot chaiH I if ltconditiongt statement Input Celsms Tempevalme Favenherl 95 elsius 32 Fun Fahrewlhewt I Example Temperature Warning I Two conditions I with one BLOCK each ifthen statement Pattern if ltconditiongt rim to convert Ce151us tem eratur input quotwhat 3 m 9 D celsi H a quotThI myL 39ML A y fa quot gt 90 be CELL fullquot m an E sue to u Waiml lquot if thenelse if temperature gt 90 print quotI need a drinkH else print quotI39m fineH This is called a twoiway decision if thenelse if reply 22 quotaquot points 1 else points 0 Note else is NOT indented Use backspace key to get back to left side if thenelifelse if temperature gt 90 print quotI need a cold drinkquot eh39f temperature lt 30 print quotI need a hot teaH else print quotI39m neH This would be a three way decision 10 Basic Concepts of Computing Michael Gertz gertzcsucdavisedu May 9 2008 Announcements I Assignment 4 is due Wed May 14 at 10pm electronically through MyUCDavis I Informanon about midterm 2 Monday May 12 in class has been posted I Open book and open notes I Don t forget your Scantron 2000 forml I All very similar to midterm 1 multiplechoice questions and one programming problem Sample Midterm cuminquot 7 mm In tumor u 2i I Focus on I Userede ned functions I Decision structures I Booleans Ir 1 n mummy m m mums Mun dws 122 L remmquot I F11e processmg 1A1 newnewgeumwewuml range I Dictionanes as us hawkmanme I Lists 1 the maximum aim values m I D UH nulll mum Hi the ulnn in L and everythmg that was Ev nommnwrume relevant for midterm 1 What does this function do v v g n u Ei e Edit quat gun Qotions Windows Heb barL 11 m tr quotner Fe m m m x t update In yr quotm upda x quottquot m Do you understand everything v v v 7 w N that happens when you call eg no update 1 lt 3 y ba13142gt gt gt Sidiiii e 2 4 gtgtgt Ln SEM 4 4 In the previous lecture I Dictionary D I ef cient association key 9 041 I not so they other way round we ll see later I order in a dictionary is normally irrelevant l system makes sure kg9mlue lookups are ef cient I Dltkeygtvaluegt VDltkeygtgt l Dkeysgt Dvalues both are lists Ditems list of tuples l val in D Dgetltkeygtltdefault valuegtgt del Bltkeygt I List Array L I access via numerical index Li or via for e in L 9 order is important and essential for access More on dictionaries I Dictionaries provide for ef cient lookups of keys I What if you want to lookup the key for a value I Convert dictionary to list of tuples and loop through that list checking for the 2nd component of each tuple 9 tedious and time consuming if you do this type of operation often I Better take the dictionary and convert it ie values become keys and keys become values You then have two dictionaries that work in both directions Swapping dictionaries c0nt swap ict py ChomegertzTeanhing10 WQ08Sriptsandlngskwapdict py EHe 39 Fgrmt Kun Qotions ows e Edit W nd HID nynictionary 12345 quotJ ffquot 432432 quotJoanquot 967654 565656 quotR 121234 swapnictionary ltgt fir key val in myDictionaryitemsM swapDictionaryfval key print swapDiCtionary A What problems can occur gran to analyze the frequency of words in a text file Illustrates Python dictionaries import string using some functions on strings 7 r FUNCTIONS 7777777 is compareltemswlcl 1 gt camp w2cm Wrapping up i Dictionaries fer MAIN print quotThis program analyzes word frequency in a filequot p quotand prints a report on the n nost frequen words c1 7 return get the sequence of rds from the file ane raw wo ilnputquotElle to analyze quot openfnane 39r39 d 1nf11eread text1ower repiace speciai cnaracte s with a blank K r cn in 391quot5s ext textrepiacecn words textspiit Frequency construct a dictionary of word counts counts ltgt for w in words countsw countsgetwu 1 output analysis of n most frequent words n inputquot0utput analysis of how many words quot itens countsitems itens sort compareltems cr i in rangen 8 print itens i1 W1 KlPhblA YiurvueDmtrrpt u 7 an M mggus39smn Albert Einstein Fvum kamema me quot22 antNunema 39wg w gsmg39w NWT Emszew redneczs news For other uses see Emszem disambiguation Alberl E s12il Gevman PA x A mum amstamJ Mamm memencaw physwms H2 5 bes massrenevgy bet agn ay 1 Audm mg 1879Apm 18 1955 We heavy Mummy and spem caHy Emstem vecewed the 1921 Nube Pnze m Physms m m semces tuTheuveHn Physms and espemaHy m m mscuveyy n We aw mum phmue ecm EWEE W a he v mm Enghsh 4 Gevmanrbum sa equwdenca ich mm Wm vecunc ed mechamcs W echumagnehsm and m geneu heuvy a RED mchanges VE aWNy Whmh E Ended 01 pvmmp e UV M y m 7 quotNEW mmm cveatmg a cammwmma n Wtheuvy a mn H mm on nbmmns meme ve awwsu nus u ugy I Danmemvw pema capmavy acuun mma upe escence c a ma pmb E UV s aHSH mechamcs Hem and the apphcanun m quanum theuvy an 2xp anahun mum Emwman muvemem mm phumn Menny 3 Manny uhamauun mc udmg sumu ate um gen aem ssmm me Eptmn um um ed e d heuvy and me hysms memzauun an W m b 2 m x 12 man my mama papevs a a s u s y A ben Emstem mm D an n nunrsmenmc bunks PM Enstem s veveved by We phys cummumy I we magazme named m m Pevsun mum 02mm m pupu a name Emstem has became synunymuus Wm gemus and vcuhuve mg m Comems we Mum and schuuhnu 2 Pammmoe Mamage and Yarm v We Mwabms 3 Armus 3 Lou III Cleme account Alben Elnsteln mm m 19H Ham May2h 9 mm Wumemhevg eemany med Apmm sq m Pun21 NewJevsewU mm Gemanv na v Swnzenanm magmas cmmsmu Geman mum 191ml ms 1 Amen23H 1 aom p FH File 0 Output w 39 iki39 39relaC1 Y hun ell e Ed t Debug thjons andows help nalyze 11139 55 vity39 54 Pymon Shell He Ed t Debug 39relativicy39 39retrieved39r a y Einsteintxt analysis of how many words mu 867 39world39 35 39american 34 gptions Mndows Heb E 54 4 1 Ln mm a 10 Word frequency I Let s look at the program step by step prlnt quotThis program analyzes word frequency in a filequot prlL quotand prints a te n muet frequent wot It on the get the sequence of words from the file fneme rawiinputUE lle to analyze infile openlfname39r39 text infile read text text lower replace special Characters with a blank for Ch in 39lquot5ampf 39 3 7 139 rquot A e t textreplacech words textsplit Construct a dictionary of word counts counts fot w in words countsw countsgetw 1 Remember Dgetlt keygt gtltdef2ultnvaluegt 1 1 Word frequency I If we would print the dictionary after that wardfreq2py ChumegertzTeahing10WQOEScri E EI Eile Edit Fgrmat gun thions windows Help Construct a dictionary of word counts counts for w in wards countsw countsgetw0 l and print the dictionary C counteitem5 for 1 in C Python 5n n EJEEEQ deb PLlUC quotmordquot iD quotegt CountZquot evaluatlng t never if 77gt count 1 count 4 12 Word frequency l but we want the most frequent words printed out rst Eile Edit Format Bun thlo n5 urx 1 n inputquot0utput anal items countitems items sort compareltems Fct i 1v rangen itint itemsi wordfreql py C hamegertzTeahing1 0WQ08Scripts 39 windows Output analysis of n most fr 39 a of FREE deb clet compareltems wlcl w2 can F 1 gt c2 muent we rds Msny Word frequency l but we want the most frequent words printed out rst sorted I Now we only have a dictionary which can be mapped to a list of tuples word being the key and count pairs I That is we want to sort these tuples based on the value component I Why not just do items countsitems itemssort I There is no natural order among tuples E1nste1ntxt of how many words 2n

### BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.

### You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

## Why people love StudySoup

#### "I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

#### "I used the money I made selling my notes & study guides to pay for spring break in Olympia, Washington...which was Sweet!"

#### "I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

#### "It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

### Refund Policy

#### STUDYSOUP CANCELLATION POLICY

All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email support@studysoup.com

#### STUDYSOUP REFUND POLICY

StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here: support@studysoup.com

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to support@studysoup.com

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.