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
2/26/13 ECS15, Lecture 14 Topic 4: Programming in Python, cont. -- Arrays, strings, indexing Staying up to speed with Python RESOURCES • Python Primer, Introduction. • Python Primer, Chap 1, Chap 2, Chap 3. • Links to simple example programs (under “Lectures” tab of course homepage.) • Python Programming for the Absolute Beginner (the recommended text). • Run your programs, line-by-line, in IDLE! 1 2/26/13 Mac OSX keyboard shortcuts: • Right-click = “cntrl-click” (press both at once) • Scroll between open applications = “Apple-tab” • Scroll between open windows of an application = “Apple-`” More Python Resources • the command line help function: >>> help() >>> help(str) returns all the information about strings, including all string methods. >>> help(help) • Search the web!!! • e.g. “sort in python” • e.g. “NameError: name 'e' is not defined” (in other words, type in the error message to a search engine). 2 2/26/13 Highlights/Review • Variable: an object you define who’s value may change • Types of variables • int • float • str • Functions: Take an argument (see next page) raw_input(“print this to the screen\n”) • Nested functions: int(raw_input(“print to screen\n”)) • Methods: functions that operate on variables (see next page) (Labs 6 and 7 deal quite a bit with strings… Lets look at Lab 7 after we understand strings a little better) Highlights/Review: Functions • Functions: very basic methods built into python, typically operate on type “int” or “float” >>> b = -1000 • abs(b) = 1000 # returns absolute value • float(b) # changes b to type float • raw_input(‘prompt’) # writes “prompt” to terminal and reads in input from terminal and assigns it type str. Note calling a function has different syntax than calling a method: >>> function(argument) >>> object.method(argument) (Sometimes no argument is necessary, esp for methods) 3 2/26/13 Example functions thus far: print(“string to print”) raw_input(‘string to print to screen\n’) len(variable) # length of array, list, etc # In case of str, number of characters (Note double quote versus single quote) Nested functions: A function can take another (compatible) function as the argument. aChar = raw_input(‘Please enter a number\n') aInt = int(raw_input(‘Please enter a number\n')) aFloat = float(raw_input(‘Please enter a number\n')) 4 2/26/13 Methods (like functions but invoked by variables of proper type) For instance string methods (methods/functions that can be invoked by “str” variables): a = “example string” a.upper() a.lower() Invoke a method by varible.method() Important Methods • Methods: functions that can be invoked by different types of objects, e.g. (from Chap 1 of Primer): >>> exString = “This is a test string” • exString.strip() • exString.lower() • exString.replace(‘sub1’,‘sub2’,n) (Note: “ >>> help(str)” lists all built in string methods) 5 2/26/13 Variables: From scalars to lists/arrays • Name a variable well! (so that you remember what it represents and it helps people reading your code.) • As we saw, In python, declare variables as you go (the first time they are needed). For instance: # My first python program a = 10 b = 30 c=a+b print(c) • Most basic distinction beyond “type”: • Scalar – a single number, letter, or word • Vector or array or list -- a collection of numbers, words, etc. [item1, item2, …, item m, …, ]. The m-th slot holds the m-th element. Using arrays rather than scalars Student_names = “Allison”, “Amy”, “Peter”, “Wendy” Lab1_score = 25, 30, 20, 15 Lab2_score = 30, 25, 30, 25 Etc….. A list of elements: a = ( item1 , item2 , item3 , ….. , item n ) a[i] returns the i’th element Student_names[0] = “Allison”, Lab2_score[2]=30 NOTE: FIRST ELEMENT ASSIGNED INDEX “0”!! 6 2/26/13 Variables “scalar” versus “list” • exampleList = [1,2,4,10,5,8] • exampleList2 = [“John”, “Mary”, “Fred”] exampleList[i] returns the ith element of the list, for instance: exampleList[0] = ….. (NOTE! The first element is element “0”!!! Scalar (left) Array (right) 7 2/26/13 • Variables can be a scalar or an array • scalar: a single element • s = 10 # a scalar of type int • s = “This is a phrase” # a scalar of type str* • array: a collection of items of the same type, and where the elements of the collection are variable (changeable). • s = [1, 5, 10, 9, 7] # array of type int • s = [“This”, “is”, “a”, “phrase”] # array of type str • s = [“This is a”, “phrase”] # array of type str • lists: very similar to array (*python actually considers a str as list of letters; len(s) returns the length of the phrase s.) Tuples: • Note: the structure tuple is like an array, but immutable (contents can’t be changed unless the whole list/tuple redefined). This is like ROM. In a list or array can change each element, e.g. array[i]=2. • We will likely not need tuples but they are covered in Chap 2 of Primer. 8 2/26/13 Example program: ENCRYPTION With all the private data streaming over email and web forms we want a cypher that encrypts a string. # This program converts all “A”s in a string to 1’s, # “B”s to 2’s and “C”s to 3’s s = raw_input(‘Enter a phrase: \n’) m = s.replace(‘A’,’1’) m = m.replace(‘B’,’2’) m = m.replace(‘C’,’3’) Can we do anything more elegant than sequential instructions? Types of command flow in computer programs: With a little sophistication we can often turn sequential into a looping (repeating) set of code instructions (next lecture). But first, have to understand strings, lists and arrays better: 9 2/26/13 Highlights/Review: Syntax • Syntax: The proper grammer (if not grammatically correct, the code cannot be understood). • Be careful with use of single ‘’ and double “” quotes ‘’’. Though they are often interchangeable: • print “test phrase” • print ‘test phrase’ • Don’t forget Python is case sensitive myExampleVariable not equal MyExampleVariable Primer Chap 1: Indexing and slicing strings • String is considered a list of length m = len(str) s = “This is an example string.” s[0] = “T” s[1] = “h” s[4] = “ ” # the blank space s[-1] = “.” # negative index reads from the right s[-2] = “g” 10 2/26/13 • Selecting a subset from a string: s[i:j:k] # start at position i, up to (but not including) j, in increments of k. s[i:j:] # the same as s[i:j] and as s[i:j:1] (k=1 by default) s[::] # selects to whole string What does this following command do? (Recall s[::] selects the whole string.) b = s[::-1] (Run it in IDLE to find out. Experiment!!!) 11 2/26/13 s = “This is an example string.” >>> b = s[::-1] >>> print b ‘.gnirts elpmaxe na si sihT’ Almost equivalent: b = s[len(s):0:-1] Explain the difference…. • What does the following assign to b ? (# if not possible returns empty list) >>> b = s[3:20:2] >>> b = s[3:20:-2] >>> b = s[20:3:-2] Also in Chapter 2 Another useful general function: range() >>> range(10) [0,1,2,3,4,5,6,7,8,9] >>> range(10,21) [10,11,12,13,14,15,16,17,18,19,20] >>> range(1,10,2) [1,3,5,7,9] (As with string slicing str[1:20] selects elements 1 to 19) 12 2/26/13 A string is a list of individual characters: • Easy: Reversing the string: ‘.gnirts elpmaxe na si sihT’ • But what is want to reverse word order? “string. example an is This” Need to group the string into words not letters! (converting strings to lists and lists to strings next) Chap 1 content on manipulating strings: Python treats a string as a list of individual characters: • Easy: Reversing the string: ‘.gnirts elpmaxe na si sihT’ • But what is want to reverse word order? “string. example an is This” Need to group the string into words not letters! 13 2/26/13 Formally converting a string to a list (By default python considers a string a list of characters) • (Converting a list to a string in Chap 2) • Using the split() method. • exString = “This is a test string” • exString.split() = [‘This’, ‘is’, ‘a’, ‘test’, ‘string’] (Note len(exString) = 21, len(exString.split()) = 5) • split(sep), sep = “ ” (blank space) by default. • exString.split(“ ”) = [‘This’, ‘is’, ‘a’, ‘test’, ‘string’] • exString.split(“i”) = [‘Th’, ‘s’, ‘s a test str’, ‘ng’] So, now reversing the word order is easy! • exString = “This is a test string.” • m = exString.split() = [‘This’, ‘is’, ‘a’, ‘test’, ‘string.’] • m[::-1] = ['string.', ’test', ’a', 'is', 'This'] (Note indexing and slicing lists analogous to strings) We could do something more sophisticated using loops…. Chapter 3. 14 2/26/13 Using Different Separator Characters. • paragraph = “Here is an example of a string with multiple sentences. Multiple sentences grouped together are defined as a paragraph in the English language. Let’s break the paragraph down into different granularity.” >>> len(paragraph) # Returns the number of characters in the whole statement in quotes. (paragraph is considered a list of individual characters.) • sentence = paragraph.split(“.”) # period separates • words = paragraph.split(“ ”) # blank space separates Different Separator Characters; different granularity. • len(paragraph) # returns the number of characters in the full paragraph. (Recall a str is a list of characters by default in python.) • sentence = paragraph.split(“.”) len(sentence) # returns number of sentences # i.e. sentence[0] is the first sentence of the paragraph. # i.e. sentence[1:3:] extracts the second and third sentences. • words = paragraph.split(“ ”) len(words) # returns the number of words. # i.e. words[1] is the second word of the paragraph # i.e. words[-1] is the last word of the paragraph 15 2/26/13 Highlights, Primer Chap 2 • Chap 2: More on tuples, lists, arrays and dictionaries • array manipulation, sub-setting and indexing is essentially identical to string indexing and slicing (a few slides back) • See Chap 2, 4.3 for a table of methods for arrays (sorting, extending, inserting, length, number of occurrences….) Converting a list to a string (Recall exString.split(sep) converts a string to a list.) • converting a list to a string >>> exampleString=‘’.join(exampleList) exList = [‘This’, ‘is’, ‘an’, ‘example’] ‘’.join(exList) returns “Thisisanexample” ‘ ’.join(exList) returns “This is an example” ‘ 1’.join(exList) returns “This 1is 1an 1example • General use: ‘insertBetweenElements’.join(list) 16