12/9/2010 course a201: introduction to programming

50
12/9/2010 Course A201: Introduction to Programming

Upload: maurice-collins

Post on 04-Jan-2016

229 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 12/9/2010 Course A201: Introduction to Programming

12/9/2010

Course A201:Introduction to Programming

Page 2: 12/9/2010 Course A201: Introduction to Programming

About the final test

• Thursday December 16, 5-7pm• Ballantine Hall (BH) 228

Page 3: 12/9/2010 Course A201: Introduction to Programming

Review – Part 1

• String, string method• Boolean Operators• List, list method

Page 4: 12/9/2010 Course A201: Introduction to Programming

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: \

Page 5: 12/9/2010 Course A201: Introduction to Programming

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

k i l l e r r a b b i t0 1 2 3 4 5 6 7 8 9 10 11 12index

y not included in the result!

Page 6: 12/9/2010 Course A201: Introduction to Programming

String: concatenation and str()

iaminteger = 45iamstring = “1075”

iamresult = iaminteger + iamstring iamresult = str(iaminteger) + iamstring

• Use + to concatenate two strings together• Type conversion function: str()

Error!

Correct. iamresult becomes “451075”

Page 7: 12/9/2010 Course A201: Introduction to Programming

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”

Page 8: 12/9/2010 Course A201: Introduction to Programming

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!

Page 9: 12/9/2010 Course A201: Introduction to Programming

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’ > ‘&%@$’… > “”

Page 10: 12/9/2010 Course A201: Introduction to Programming

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()

Page 11: 12/9/2010 Course A201: Introduction to Programming

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’

Page 12: 12/9/2010 Course A201: Introduction to Programming

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.

Page 13: 12/9/2010 Course A201: Introduction to Programming

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

Page 14: 12/9/2010 Course A201: Introduction to Programming

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

Page 15: 12/9/2010 Course A201: Introduction to Programming

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!

Page 16: 12/9/2010 Course A201: Introduction to Programming

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.

Page 17: 12/9/2010 Course A201: Introduction to Programming

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']

Page 18: 12/9/2010 Course A201: Introduction to Programming

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!!

Page 19: 12/9/2010 Course A201: Introduction to Programming

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 conversion 1. Read input

Page 20: 12/9/2010 Course A201: Introduction to Programming

String Chained method calls

>>>str=“I AM string”>>>result = str.upper().lower()>>>result“i am string”

From left to right

Page 21: 12/9/2010 Course A201: Introduction to Programming

Boolean operators

Inputs Output

A B A or B A and B not A

False False False False True

True False True False False

False True True False True

True True True True False

Page 22: 12/9/2010 Course A201: Introduction to Programming

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

Page 23: 12/9/2010 Course A201: Introduction to Programming

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 Trueelse:

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

Page 24: 12/9/2010 Course A201: Introduction to Programming

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 Trueelse:

return False

if len(time)==6 and time[5]==‘A’:return True

elif len(time)==5 and int(time[0:2])<12:return True

Page 25: 12/9/2010 Course A201: Introduction to Programming

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 Trueelse:

return False

if len(time)==6 and time[5]==‘A’ or len(time)==5 and int(time[0:2])<12:return True

Page 26: 12/9/2010 Course A201: Introduction to Programming

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 Trueelse:

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 TrueIf this is false, return False==return itself

Page 27: 12/9/2010 Course A201: Introduction to Programming

Boolean operators

def is_am(time): if CONDITION_1:

if CONDITION_2:return True

else:return False

elif CONDITION_3:if CONDITION_4:

return Trueelse:

return False

Page 28: 12/9/2010 Course A201: Introduction to Programming

Boolean operators

def is_am(time): return CONDITION_1 and CONDITION_2 or CONDITION_3 and CONDITION_4

Page 29: 12/9/2010 Course A201: Introduction to Programming

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

Page 30: 12/9/2010 Course A201: Introduction to Programming

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

Page 31: 12/9/2010 Course A201: Introduction to Programming

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)

Page 32: 12/9/2010 Course A201: Introduction to Programming

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.08 None0 1 2 3index

y not included in the result!

Page 33: 12/9/2010 Course A201: Introduction to Programming

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]

Page 34: 12/9/2010 Course A201: Introduction to Programming

List: convert to list

>>>str = “abcd”>>>lst = list(str) lst becomes [‘a’,’b’,’c’,’d’]

result = lst + strresult = 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’]

Page 35: 12/9/2010 Course A201: Introduction to Programming

List: duplication

list1 = [‘*’]result = list1 * 3list1 = [1, 2]result = list1 * 2

However, if list1 is a nested list, NEVER do thisTry: list1=[[1,2]]

result = list1 * 2result[0]=result[0]+[1]

result becomes [‘*’, ‘*’, ‘*’]

result becomes [1, 2, 3, 4]

result becomes [[1,2], [1,2]] result becomes ???

Page 36: 12/9/2010 Course A201: Introduction to Programming

List: mutable

list1= [1, ‘str’, 9.08, None]Mission: change the first element of list1 to Truelist1[0] = True

>>>list1[True, ‘str’, 9.08, None]

Page 37: 12/9/2010 Course A201: Introduction to Programming

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!

Page 38: 12/9/2010 Course A201: Introduction to Programming

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!

Page 39: 12/9/2010 Course A201: Introduction to Programming

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.

Page 40: 12/9/2010 Course A201: Introduction to Programming

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]

Page 41: 12/9/2010 Course A201: Introduction to Programming

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.

Page 42: 12/9/2010 Course A201: Introduction to Programming

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

Page 43: 12/9/2010 Course A201: Introduction to Programming

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

Page 44: 12/9/2010 Course A201: Introduction to Programming

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.

Page 45: 12/9/2010 Course A201: Introduction to Programming

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.

Page 46: 12/9/2010 Course A201: Introduction to Programming

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 + widthreturn answer

List slicing returns a sublist

Use append() to add a whole list as one element

Page 47: 12/9/2010 Course A201: Introduction to Programming

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.

Page 48: 12/9/2010 Course A201: Introduction to Programming

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

Page 49: 12/9/2010 Course A201: Introduction to Programming

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]

0 1 2

3 4 5

6 7 8

matrix

row_index

coloumn_index

Page 50: 12/9/2010 Course A201: Introduction to Programming

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=0while column_index<len(row):

row[column_index]=row[column_index]+10column_index= column_index+1

row_index=row_index+1

Basic loop structure to iterate every element in a matrix