Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
Reminder: String SlicingThink of string indexes as pointers to characters.>>> a = 'Hello'>>> a[1:3]'el'>>> a[1:]'ello'>>> a[1:5:2]'el'>>> a[-4:-2]'el'>>> a[-2:-4:-1]'ll'>>> a[:-3]'He'>>> a[-3:]'llo'>>> 'hello'[1:5:2]'el'
olleH
0 1 2 3 4
-5 -4 -3 -2 -1
3
Strings
>>> s = "While My Guitar Gently Weeps"
# Lowercase representation of a string>>> s.lower()
# find the index of the first occurrence of ‘e’>>> s.find("e")
# What does first contain?>>> n_pos = s.find("e") + 1>>> first = s[:n_pos]>>> first
4
'while my guitar gently weeps'
'While'
4
ListsA list is an ordered collection of elements (of any type). To create a list with specific elements, enclose them in square brackets:
>>> my_list = [2,3,5,7,11]
>>> print(my_list)
[2, 3, 5, 7, 11]
>>> empty_list = []
>>> mixed_types = [2, "hi",3.4]
To initialize a list of n elements set to zero do:>>> a = [0] * n # what about +?
(you may replace 0, with any other number)
5
int str float
Indexing
� Indexing and Slicing works the same as for Strings.
>>> my_list = ["George", "Paul", "John", "Ringo"]
>>> my_list[0]
>>> my_list[2]
>>> my_list[4]
6
0 1 2 3
"George"
"John"
Traceback (most recent call last):File "<pyshell#7>", line 1, in <module>my list[4]
IndexError: list index out of range
Slicing>>> my_list = ['a','b','c','d','e','f','g','h','i','j']
>>> my_list[1:5] # Slicing
['b', 'c', 'd', 'e']
# Slicing does NOT change original list
>>> my_list
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
# Slicing an arithmetic progression
>>> my_list[0:9:2]
['a', 'c', 'e', 'g', 'i']
7
0 1 2 3 4 5 6 7 8 9
start stop step
Adding Elements>>> my_list = [6, 2]
# Insert at position
>>> my_list.insert(0, 'begin')
>>> my_list.insert(1, 'here')
>>> my_list
# Append (insertion at end)
>>> my_list.append('at last')
>>> my_list
8
['begin', 'here', 6, 2]
['begin', 'here', 6, 2 , 'at last']
Adding Elements – cont’my_list = ['begin', 'here', 6, 2 , 'at last' ]# Extend (concatenate another list to the end)
>>> my_list.extend([15, 16])
>>> my_list
� What would happen if we used append instead of extend?
>>> my_list.append([15, 16])
>>> my_list
['begin', 'here', 6, 2, 'at last', 15, 16, [15, 16]]
9
['begin', 'here', 6, 2, 'at last', 15, 16]
Changing Elements>>> my_list = ["aa", "bb", 1, 2]
# Change an element inside a list
>>> my_list[0] = my_list[1] + "b"
>>> my_list[2] = my_list[2] + 5
>>> my_list
# Replace elements
>>> my_list[0:2] = [1, 12]
>>> my_list
10
[1, 12, 6, 2]
['bbb', 'bb', 6, 2]
Removing Elements>>> my_list = [2, 3, "in", 4]
# Remove by value (first occurrence only)>>> my_list.remove("in")>>> my_list
# Remove by position (slice)>>> my_list[0:2] = []>>> my_list[4]
� What if we try my_list.remove(1) ?
11
[2, 3, 4]
In
Use in to check for the existence of an element inside a collection:>>> my_list = [2, 3, "in", 4]
# Element exists
>>> 2 in my_list
>>> "in" in my_list
# Element does not exist
>>> 5 in my_list
12
True
False
True
LengthUse len to get the number of elements in a collection:
>>> len([1,2,3,4,5])
>>> len([])
>>> len("abc")
13
5
0
3
Rangerange(a, b) creates an iterator with ordered integers. All k values satisfying a ≤ k < b
# Examples:>>> list(range(6,10))[6, 7, 8, 9]>>> list(range(5)) # same as range(0,5)[0, 1, 2, 3, 4]>>> list(range(4,2))[]>>> type(range(3))<class 'range’>
range(a, b, d) - all integers from a (including) to b (not including) taking a “step” of d in between >>> list(range(10, 0, -2))
[10, 8, 6, 4, 2]14
Range – Cont.How can we create an Arithmetic progression of n elements:
𝒂𝒊 = 𝒂𝟎 + 𝒅 ∗ 𝒊# Examples:
>>> a_0 = 4
>>> d = 2
>>> n = 6
>>> list(range(a_0, a_0 + d * n, d))
15
[4, 6, 8, 10, 12, 14]
What if we try n=0? n=1? n=10?
Other useful functions
16
� Reversing list:>>> l = list(range(10))
>>> l.reverse() #What’s the difference from l[::-1]?
>>> print(l)
� Sorting list:>>> l = list(range(10, 0,-1))
>>> l.sort() #What’s the difference from sorted(l)?
>>> print(l)
For other useful functions: list - useful functions
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Nested ListsList may contain other lists:
>>> nested_list = [['a', 12], ['b', 16]]
>>> nested_list[0]
>>> nested_list[0][0] #slicing one by one'a'
� What is the length of “nested_list"?>>> len(nested_list)
17
2
['a', 12]
The str function
• Use str to convert any value of built-in types into a string
>>> str(1)'1'
>>> str("hello")'hello'
>>> str(range(3))'range(0, 3)'
18
For LoopSaywewanttoprinteachelementofourlist:
lst =[3,1.24,"gorilla"]print (lst[0])print(lst[1])print(lst[2])print(lst[3])
Thisisveryrepetitiveandreliesonusknowingthenumberofelementsinthelist.
19
Error
For Loopfor element in iterable:
statement1statement2
lst=[3, 1.24, "gorilla"]
for elem in lst:
print(elem)
20
Indentation determines the scope of the iteration.
25
For LoopsLet'sgooverastringandcountthenumberofoccurrencesoftheletterP:
seq = 'MALWMRLLPLLALLALWGPDPA'
count = 0for letter in seq:
if letter == 'P':count += 1 # count = count + 1
same as: seq.count('P')
For Loops with range� Example: print the even numbers between 0-20
(each in a new line)l = range(0,21,2)
for num in _____________:print(_________)
024…20
26
numlrange(0,21,2)
For Loops with range� Example: display the multiplication chart (לוח הכפל)
for i in ____________:for j in ____________:
print(___________)print("")
27
range(1, 11)
range(1, 11)i*j,end=""
'end=“”' is used to accumulate output in the
same line
forces the output to be in separate lines
For Loops with rangeFor a given string, lets print each two subsequent letters:ACGT −> AC CG GT
seq ='ATGATTCCAACGCGA'
for letterin seq:print(letter….) and the next letter(?!)
seq='ATGATTCCAACGCGA'
n=len(seq)for i in range(n):print(seq[i])
But we want to printsubsequent letters
For Loops with rangeFor a given string, lets print each two subsequent letters:ACGT −> AC CG GT
0123451014
seq='ATGATTCCAACGCGA'
n=len(seq)for i in range(n):print(seq[i]+seq[i+1])
What will happen when i==14?
IndexError!
For Loops with rangeFor a given string, lets print each two subsequent letters:ACGT −> AC CG GT
0123451014
seq='ATGATTCCAACGCGA'
n=len(seq)
for i in range(n-1):print(seq[i]+seq[i+1])
For Loops with rangeFor a given string, lets print each two subsequent letters:ACGT −> AC CG GT
0123451014
32
lst =[3,1.24,"gorilla"]
for elem in lst:
print(elem)
Sameresultinthiscase!Butsometimeswemustusetheindices(previousslideforexample)
Usewisely,andaccordingtoneed
For Loops with / without range
for i in range(len(lst)):
print(lst[i])
Matrix representation using lists
33
� A matrix (plural matrices) is a rectangular array of numbers, symbols, or expressions, arranged in rows and columns (From wiki). An 𝑀×𝑁 matrix, denotes an array of 𝑀 rows and 𝑁columns.
� An example of a 4×2 matrix is:
2 5823
190
� The (i,j) element refers to the j’th element of the i’th row� What does (3,2) equals to (in 1-based indexing)? 9
34
� An𝑀×𝑁 matrix,canberepresentedbynestedlists.The(i,j)elementofthematrixisstoredasthe(j-1)’th elementofthe(i-1)’th list.
� Thematrixinourexampleisrepresentedby:A=[[2,5],[8,1],[2,9],[3,0]]� Toobtainthe(i,j)element:A[i-1][j-1]� Forexample,toobtain(3,1),wewrite:A[2][0]
Matrix representation using lists
35
� Wearegivenamatrixofintegers,wewouldliketocollectallevennumbersintoanewlist.
� Anyideas?� Initializeavariable,toholdthenewlist(initializewithwhatvalue?)
�Goovereachelementinthematrix:� Ifthecurrentelementiseven,updatethenewlist
� printthelist
Matrix representation using lists
36
A = [[2, 4], [3, 5], [4, 1], [3, 2]]
new_list = ______________
num_rows = len(______________)
num_columns = len(______________)
for i in range(num_rows):
for j in range(num_columns):
if ____________________:
__________________________
print("The even numbers are:", new_list)
[]
AA[0]
A[i][j] % 2 == 0
new_list.append(A[i][j])
Assumptions:1. A contains at least a single row (otherwise?)2. All rows A[0], A[1],…, are lists of the same length
Matrix representation using lists
While Loopwhile expression:
statement1statement2…
rest of code
Example:count = 0 while count < 3:
print("The count is:", count)count += 1 # count = count + 1
print("Goodbye!")
expr
statement(s)
true
false
37
The count is: 0 The count is: 1 The count is: 2 Goodbye!
Break
break - terminates the nearest enclosing loop# Write a code which prints True if all digits in a given number are smaller or equal to 5
n = 129231330
print("Number:", n)
while n > 0:
cur_dig = n % 10
if _______________:
________________
________________
____________
if _______________:
____________38
cur_dig > 5
print(False)
break
n = n // 10
n == 0
print(True)
Continue
39
continue - starts the next cycle of the nearest enclosing loop
# Example: counting spacesin_string = "Ground control to Major Tom"spaces = 0for c in in_string:
if c != " ":continue
spaces += 1 print("Number of spaces:", spaces)
While Loop – Example 1
secret = int(input("Choose a number: "))
while True:guess = int(input("Enter guess: "))if _______________:
breakelif ______________:
print("Try a higher number")else:
print("Try a lower number")
print("Right!")
40
guess == secret
guess < secret
Hint (sample output)
Choose a number: 34Enter guess: 100Try a lower numberEnter guess: 50Try a lower numberEnter guess: 25Try a higher numberEnter guess: 35Try a lower numberEnter guess: 34Right!
Player 1
Player 2
Phone Book
41
� We want to develop an application for managing contacts
� It will contain a database� A list of contacts� Each contact is a list in the format [name, phone]
� Functionality� Find contact(s) by full name or prefix� Add contact� Remove contact
found = Falsephone = ""for contact in phone_book:
if contact[0] == name:found = Truephone = contact[1]break
if found:print "Name:", name , "Phone:", phone
else:print "Cannot find", name , "in contact list."
phone_book = [['nir','7886'],
['cohen','0123456758']]
# Retrieve the number for a given personname = "Moshe"
42
Hint (sample output)
For name == "nir" the result will be:Name: nir Phone: 7886
For name == "assaf" the result will beCannot find assaf in contact list.
Phone book
Phone book
43
found = Falsephone = ""for contact in phone_book:
if contact[0] == name:found = Truephone = contact[1]break
if found:print("Name:", name , "Phone:", phone)
else:print("Cannot find", name , "in contact list.")
phone_book = [['nir','7886'],
['cohen','0123456758']]
# Retrieve the number for a given personname = "Moshe"
# Remove a contact
name = "Moshe"
found = False
for contact in ___________:
if __________________:
__________________________
____________
break
if not found:
print("Cannot find contact")
phone_book.remove(contact)
45
phone_book
contact[0] == name
found = True
Phone book
# Search for all contacts with given prefix.
# Ignore character case (aka, case insensitive).
prefix = "ni"
prefix = prefix.lower()
for contact in phone_book:
if contact[0].lower().startswith(prefix):
print("Name:", contact[0], "Phone:", contact[1])
46
Note that we don’t break (otherwise we will only find the first contact)
Phone book
One more break# Example: find the hidden number in a string# (a hidden number is a number which begins at the first character of the string and continues until some letter appears, e.g., 23fkd => 23)
in_string = "2346897ewrwqer"out_string = ""for c in in_string:if not c.isdigit():
breakout_string += c
print("The number is:", out_string)
47