Download presentation
Presentation is loading. Please wait.
Published byMaurice Collins Modified over 9 years ago
1
12/9/2010 Course A201: Introduction to Programming
2
About the final test Thursday December 16, 5-7pm Ballantine Hall (BH) 228
3
Review – Part 1 String, string method Boolean Operators List, list method
4
String Ex: “all letters”, ‘1982478’, ‘*%#$%#@’ Anything you can input from keyboard, begins and ends with double or single quote Special cases: backslash escape character – print “\’” result: ’ – print “\”” result: ” – print “\n” a new line – print “\\” result: \
5
String: Indexing and slicing Indexing and slicing: str=“killer rabbit” Ex: str[0] is “k”; str[1:2] is “i”; str[3:] is “ler rabbit”; str[:6] is “killer” str[x:y] is to show the characters from x to y-1 killerrabbit 0123456789101112 index y not included in the result!
6
String: concatenation and str() iaminteger = 45 iamstring = “1075” iamresult = iaminteger + iamstring iamresult = str(iaminteger) + iamstring Use + to concatenate two strings together Type conversion function: str() Error! Correct. iamresult becomes “451075”
7
String: duplication iamstar = “*” result = iamstar * 6 numberstr = “12” result = numberstr * 3 def right_justify(n, string): return ' ' * (n - len(string)) + string result becomes “******” result becomes “121212”
8
String: not mutable str = “killer rabbit” Mission: change the first letter of str to ‘l’ str[0] = ‘l’ Correct solution: generate a new string! newstr = ‘l’ + str[1:] Error!
9
String: character ordering 1>2 will return False, how about ‘a’>’z’? In Python: lowercase letters > uppercase letters > digits > symbols > empty string ‘a’ … ‘z’ > ‘A’ … ‘Z’ > ‘9’ … ‘1’ > ‘&%@$’… > “”
10
String: method – find(), index() str=“I am string I am” >>>str.find(‘a’)2 >>>str.find(‘i’)8 >>>str.find(‘b’)-1 >>>str.index(‘a’)2 >>>str.index(‘b’)Error! >Return the position of first ‘a’ >case sensitive >str does not contain ‘b’ >same with find() >different from find()
11
String: method – rfind() str=“I am string I am” >>>str.rfind(‘a’)14 >>>str.find(‘i’)8 >>>str.find(‘b’)-1 Are the last characters of str equal to “ am”? return str[str.rfind(“ am”):] == “ am” >Return the position of last ‘a’ >also case sensitive >also return -1 when str does not contain ‘b’
12
Practice: find out if str1 contains str2 1. if str2 in str1: return True 2. if str1.find(str2)<0: return True 3. You can always write a loop, but … it will be more complicated.
13
String: method – isdigit() str1=“1987372”str2=“9.3”str3=“-5” >>>str1.isdigit()True >>>str2.isdigit() False >>>str3.isdigit() False anystring.isdigit() returns True => anystring only contains digits, no dots, no any other symbols
14
String: method – islower() str1=“aaa”str2=“a 8 %, ”str3=“A” >>>str1.islower()True >>>str2.islower() False >>>str3.islower() False anystring. islower() returns True => anystring only contains lower letters, no spaces, no symbols, no digits
15
String: method – lower() str=“I AM string ** 12” >>>str.lower()“i am string ** 12” >>>str “I AM string ** 12” str.lower() returns a new string that contains the same characters with str, but all letter will be in lowercase, str itself doesn’t change!
16
String: method – replace() str=“I AM string **” >>>str.replace(‘A’, ‘a’)“I aM string **” >>>str.replace(‘*’, ‘hi’)“I AM string hihi” >>>str.replace(‘b’, ‘c’)“I AM string **” >>>str “I AM string **” Again, str itself doesn’t change! Not error.
17
String: method – split() str1=“I am separated by spaces” str2=“I am-separated by-some other-thing” result1=str1.split() result2=str2.split() result3=str2.split(‘-’) >>>result1 ['I', 'am', 'separated', 'by', 'spaces'] >>>result2 ['I', 'am-separated', 'by-some', 'other-thing']
18
String: method – split() >>>result3 ['I am', 'separated by', 'some other', 'thing'] >>>str1 “I am separated by spaces” >>>str2 “I am-separated by-some other-thing” The original strings do not change!!
19
Chained method calls Remember raw_input() ? Ex: radius = float(raw_input(‘Radius: ’)) – This is a combination of two functions: radius = raw_input (‘Radius: ’) # radius now contains a string value radius = float(radius) # radius now contains a float value From inside to outside 2. type conversion1. Read input
20
String Chained method calls >>>str=“I AM string” >>>result = str.upper().lower() >>>result “i am string” From left to right
21
Boolean operators InputsOutput ABA or BA and Bnot A False True FalseTrueFalse True FalseTrue False
22
Boolean operators def is_am(time): """ >>> is_am('12:00A') True >>> is_am('12:00') # military time False >>> is_am('12:00P') False >>> is_am('10:45P') False """ 1. If the length of input is 6, exam whether there is an “A” at the end; 2. If length is 5, then exam whether the first two digits are smaller than 12
23
Boolean operators def is_am(time): if len(time) == 6: if time[5] == ‘A’: return True else: return False elif len(time) == 5: if int(time[0:2])<12: return True else: return False 1. If there is an “A” at the end of input, then return True; 2. If no “A”, then exam whether the first two digits are smaller than 12
24
Boolean operators def is_am(time): if len(time) == 6: if time[5] == ‘A’: return True else: return False elif len(time) == 5: if int(time[0:2])<12: return True else: return False if len(time)==6 and time[5]==‘A’: return True elif len(time)==5 and int(time[0:2])<12: return True
25
Boolean operators def is_am(time): if len(time) == 6 and time[5] == ‘A’: return True elif len(time) == 5 and int(time[0:2])<12: return True else: return False if len(time)==6 and time[5]==‘A’ or len(time)==5 and int(time[0:2])<12: return True
26
Boolean operators def is_am(time): if len(time)==6 and time[5]==‘A’ or len(time)==5 and int(time[0:2])<12: return True else: return False And finally: def is_am(time): return len(time) == 6 and time[5] == ‘A’ or len(time)==5 and int(time[0:2])<12 If this is true, return True If this is false, return False == return itself
27
Boolean operators def is_am(time): if CONDITION_1: if CONDITION_2: return True else: return False elif CONDITION_3: if CONDITION_4: return True else: return False
28
Boolean operators def is_am(time): return CONDITION_1 and CONDITION_2 or CONDITION_3 and CONDITION_4
29
Boolean operators def oneline(a, b): """ if a < 3: if b: return True else: return False else: return False """ # USE ONE LINE def oneline(a, b): """ if CONDITION_1: if CONDITION_2: return True else: return False else: return False """ # USE ONE LINE
30
Boolean operators def oneline(a, b): return CONDITION_1 and CONDITION_2 def oneline(a, b): return a<3 and b Any condition statement will generate a certain boolean value according to the input b will be converted to boolean value
31
List Ex: [1, 2, ‘string’, 9.08, None, True] A sequence of any type of values Some built-in functions for list: list1 = [1,2,3] >>>max(list1) >>>min(list1)
32
List: Indexing and slicing Similar to string: list1= [1, ‘str’, 9.08, None] Ex: list1[0] is integer 1; list2[1:2] is [‘str’]; list3[3:] is [None]; list4[:2] is [1, ‘str’] list1[x:y] is to show the elements from x to y-1 1‘str’9.08None 0123 index y not included in the result!
33
List: Indexing/slicing and concatenation list1= [1, ‘str’, 9.08, None] Notice: Indexing returns an element; Slicing returns a sublist (may only contain one element) Ex: list1=list1+list1[0] list1=list1+list1[0:1] Error! list[0] is an integer Correct. List1 becomes [1, ‘str’, 9.08, None, 1]
34
List: convert to list >>>str = “abcd” >>>lst = list(str) lst becomes [‘a’,’b’,’c’,’d’] result = lst + str result = lst + list(str) result = lst + [str] Error! result becomes [1, ‘str’, 9.08, None, ‘a’, ’b’, ’c’, ’d’] result becomes [1, ‘str’, 9.08, None, ‘abcd’]
35
List: duplication list1 = [‘*’] result = list1 * 3 list1 = [1, 2] result = list1 * 2 However, if list1 is a nested list, NEVER do this Try:list1=[[1,2]] result = list1 * 2 result[0]=result[0]+[1] result becomes [‘*’, ‘*’, ‘*’] result becomes [1, 2, 3, 4] result becomes [[1,2], [1,2]] result becomes ???
36
List: mutable list1= [1, ‘str’, 9.08, None] Mission: change the first element of list1 to True list1[0] = True >>>list1 [True, ‘str’, 9.08, None]
37
List: method – index() List doesn’t have method find(), but it does have method index(). list1= [1, 2, ‘hi’, None] >>>list1.index(2)1 >>>list1.index(None)3 >>>list1.index(4)Error!
38
List: method – append() append() will alter the original list: add one element, but the return value is None. list1= [1, ‘str’, 9.08] >>>list1.append(34)No output >>>list1[1,’str’,9.08,34] >>>list1+list1.append(5)Error!
39
List: method – append() >>>list1= [1] >>>list1+[list1.append(5)][1, 5, None] >>>list2=[2] >>>list2.append(list1)No output >>>list2[2, [1, 5, None]] Use append() when you want to add something as one element on to the list. The whole list is one element.
40
List: method – pop() pop() will alter the original list: delete one element at the position that you indicate, and the return value is the deleted element. list1= [1, ‘str’, 9.08] >>>list1.pop(0)1 >>>list1[’str’,9.08]
41
List: method – pop() list1= [1, ‘str’, 9.08] >>>list1.pop(len(list1))Error! If you want to get the value of a certain element, use indexing, not method pop(). pop() will be used only when you want to delete the element from the original list.
42
Method: join() join() is a string method, but its argument must be a list of string. It joins these elements together, back to one string, using the target string as separator. >>> '.'.join(['1','2','3'])'1.2.3' >>> ' '.join([1,2,3])Error! >>> ‘no'.join(['spam', 'eggs'])'spamnoeggs‘ The list can only contain strings as elements
43
List in List >>>list1 = [1, 2] >>>list2 = [3, 4] >>>list1.append(list2) >>>list1[1, 2, [3, 4]] How to index the first element in this sublist? 1. >>>sublist=list1[2]>>>element=sublist[0] 2. >>>list1[2][0] The whole list2 is now one element of list1
44
List in List vs string in list >>>list1 = [1] >>>list2 = [1, 2] >>>list3 = “ab” >>>list1.append(list2) >>>list1.append(list3) >>>list1[1, [1, 2], “ab”] First element in the sublist:list1[1][0] First character in the string: list1[2][0] The way of indexing is actually the same. Nothing complicated. The sublist is just an element in list.
45
List in List vs string in list >>>list1 = [1] >>>list2 = [1, 2] >>>list3 = “ab” >>>list1.append(list2) >>>list1.append(list3) >>>list1[1, [1, 2], “ab”] First element in the sublist:list1[1][0] First character in the string: list1[2][0] The way of indexing is actually the same. Nothing complicated. The sublist is just an element in list.
46
List vs Matrix >>> make_matrix([0, 1, 2, 3, 4, 5], 3) [[0, 1, 2], [3, 4, 5]] def make_matrix(lst, width): answer = [] index = 0 while index < len(lst): answer.append(lst[index : index + width]) index = index + width return answer List slicing returns a sublist Use append() to add a whole list as one element
47
List vs Matrix >>> flatten_matrix([[1, 2, 3], [4, 5, 6]]) [1, 2, 3, 4, 5, 6] def flatten_matrix(table): index=0 result=[] while index<len(table): result = result + table[index] index = index + 1 return result Use concatenation to get a flat list: it doesn’t contain any sublists.
48
List vs Matrix >>> table = [[0, 1, 2], [3, 4, 5]] How to get the first element in the first list in table? table[0][0] >>> table[0][1] 1 >>> table[1][0] 3
49
List vs Matrix >>> matrix = [[0, 1, 2], [3, 4, 5], [6,7,8]] 3 rows, 3 columns First row: matrix[0]=[0,1,2] First column: [0,3,6] matrix[0][0]+matrix[1][0]+matrix[2][0] row_index coloumn_index
50
List vs Matrix >>> matrix = [[0, 1, 2], [3, 4, 5], [6,7,8]] How to add 10 to each element in this matrix? def add_ten(matrix): row_index=0 while row_index<len(matrix): row=matrix[row_index] column_index=0 while column_index<len(row): row[column_index]=row[column_index]+10 column_index= column_index+1 row_index=row_index+1 Basic loop structure to iterate every element in a matrix
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.