Professional Documents
Culture Documents
String Formatting
Lists
Ranges
Loops
• types of loops: while, for
• Other loop statements: break, continue
• Improving the search of the original Rick from last week
(self-learning)
String formatting
In [ ]: name = "Rick"
pi = 3.17159265359
# Basic printing
print("My name is", name, "and I am c-", pi)
# String formatting
print("My name is {0} and I am c-{1:.2f} ".format(name, pi))
# This is equivalent
print(f"My name is {name} and I am c-{pi:.2f}")
Recall:
H e l l o
0 1 2 3 4
-5 -4 -3 -2 -1
In [ ]: my_str="Rick"
In [ ]: my_str_list=["R","i","c","k"]
In [ ]: print(my_str[0], my_str_list[0])
In [ ]: my_list[3]
Length of a list
In [ ]: len(my_list)
print(student)
List slicing
• syntax: some_list[x:y:z]
• Returns a new list based on characters from some_list
• from position x (including) until position y (not including) with steps of size (and
direction) z
In [ ]: print(len(mat))
In [ ]: print(len(mat[1]))
Element-wise product
• For a pair of matrices, multiply each number in the �rst matrix with its
corresponding number in the second matrix
• Corresponding number = the number that lies in the same position
result=[]
result.extend([[],[]])
i=0; j=0
result[i].append(m[i][j]*n[i][j])
i=0; j=1
result[i].append(m[i][j]*n[i][j])
i=1; j=0
result[i].append(m[i][j]*n[i][j])
i=1; j=1
result[i].append(m[i][j]*n[i][j])
print(result)
Kahoot! (2): nested lists
result=[]
result.extend([[],[]])
i=0; j=0
result[i].append(m[i][j]*n[-i][-j])
i=0; j=1
result[i].append(m[i][j]*n[-i][-j])
i=1; j=0
result[-i].append(m[i][j]*n[-i][-j])
i=1; j=1
result[-i].append(m[i][j]*n[-i][-j])
print(result)
List's methods
• Method: A type of a function applied from a speci�c object (e.g. speci�c list [1,2,3])
• Applied using the dot notation: variable_name.function_name()
• Might change the original list (contrary to what we saw in Strings)
▪ Strings: Immutable
▪ Lists: Mutable
• Function that modify list are usually written with dot syntax
Partial list of methods
method description
lst.append(item) append an item to the end of the list
lst.count(val) return the number of occurrences of val
lst.extend(another_lst) extend list by appending items from another list
lst.index(val) return �rst index of val
lst.insert(index, item) insert an item before index
lst.pop(index) remove the item at location index and return it (remove last element if index is omitted)
lst.remove(val) remove �rst occurrence of a val
lst.reverse() reverse the list (in place)
lst.sort() sort the list (in place)
In [ ]: students.extend(['Jessica'])
print(students)
In [ ]: students.remove('Morty')
print(students)
students.remove('Morty')
In [ ]: print("Beth".pop(0))
Kahoot! (3): list operations
In [ ]: students=['Rick', 'Tiny Rick!', 'Beth', 'Jerry', 'Summer', 'Jessica', 'Rick', 'Ri
ck']
In [ ]: x = students.pop(-1)
if x in students[:len(students)//2] and x in students[len(students)//2:]:
students.remove(x)
students.remove(x)
if x in students[:len(students)//2] or x in students[len(students)//2:]:
students.remove(x)
print("Rick" in students)
In [ ]: a = [3,7,1]
b = a.sort()
print(a)
print(b)
In [ ]: range(7)
In [ ]: type(range(7))
In [ ]: list(range(7))
In [ ]: list(range(3,7))
In [ ]: list(range(7, 3, -1))
In [ ]: list(range(-3,7,1))
• Iteration 0:
▪ Execute statement1, statement2, …
• Iteration 1:
▪ Execute statement1, statement2, …
• …
• Expression is False → "Jump" to the rest of the code (i.e leaves the loop)
Print numbers from 1 to 7 with a descriptive text:
In [ ]: cur_number = 1
while cur_number<=7:
print("current number:", cur_number)
cur_number+=1
Factorial de�nition:
3!=1⋅2⋅3
6!=1⋅2⋅3⋅4⋅5⋅6
𝑛!=1⋅2⋅…⋅(𝑛−1)⋅𝑛
fact = 1
i = 1
while i <= n:
fact = fact * i
i = i + 1
print(f'{n}! = {fact}')
Find the smallest divisor
10 → 2
221 → 13
In [ ]: n = 141
div = 2
while n % div != 0:
div = div + 1
print("Smallest divisor of", n, "is", div)
In�nite loop
In [ ]: i = 1
while i < 137:
print(i)
Last recitation: where is the original Rick?
else:
print("too many dimensions to this implmenetation... do you have any
LOOPS around here?")
else:
print("There are no existence of Ricks between", lowest_dimension,"and", hige
st_dimesion)
Can we do better now using while loop?
Implementation with a while loop #1
In [ ]: ## For measuring the runtime. You can ignore this block... ###
import time
#######################################
# "Input" values
lowest_dimension=130
highest_dimension=1500000
dimension_prefix="c"
else:
print("There are no existence of Ricks between", lowest_dimension,"and", hige
st_dimesion)
In the implementation w/o loops we couldn't be sure if the original rick exists between lowest and
highest dimension
• Now we can!
In [ ]: dimension_prefix="c"
In [ ]: ## For measuring the runtime. You can ignore this block... ###
start=time.time()
#######################################
if dimension_prefix != dimension_real_prefix:
print("Wrong dimension prefix: ", dimension_prefix)
else:
current_dimension=lowest_dimension
got_original_rick=False
while current_dimension <= highest_dimension:
if current_dimension==dimension_real_index:
print("We got an original Rick here!")
got_original_rick=True
current_dimension+=1
if not got_original_rick:
print("There are no existence of Ricks between", lowest_dimension,"and",
highest_dimension)
## For measuring the runtime. You can ignore this block... ###
end=time.time()
print(f'Runtime: {end-start}')
#######################################
Kahoot! (4a): For implementation #2, the runtimes of non-real dimension pre�xes (e.g., "d") are
di�erent than those of the real dimension ("c")
In [ ]: dimension_prefix="d"
Implementation with a while loop #3
In [ ]: dimension_prefix="c"
In [ ]: ## For measuring the runtime. You can ignore this block... ###
start=time.time()
#######################################
current_dimension=lowest_dimension
got_original_rick=False
while current_dimension <= highest_dimension:
if current_dimension==dimension_real_index:
print("We got an original Rick here!")
got_original_rick=True
current_dimension+=1
if not got_original_rick :
if dimension_prefix != dimension_real_prefix:
print("Wrong dimension prefix: ", dimension_prefix)
else:
print("There are no existence of Ricks between", lowest_dimension,"and",
highest_dimension)
## For measuring the runtime. You can ignore this block... ###
end=time.time()
print(f'Runtime: {end-start}')
#######################################
Kahoot! (4b): For implementation #3, the runtimes of non-real dimension pre�xes (e.g., "d") are
shorter than those of the real dimension ("c")
In [ ]: dimension_prefix="d"
Implementation #2
Implementation #3
for-else (??)
• If a loop (either for or while) is terminated w/o error, it goes to the else clause
• The else clause is optional
Implementation with while loop #4
In [ ]: ## For measuring the runtime. You can ignore this block... ###
start=time.time()
#######################################
if dimension_prefix != dimension_real_prefix:
print("Wrong dimension prefix: ", dimension_prefix)
else:
current_dimension=lowest_dimension
while current_dimension <= highest_dimension:
if current_dimension==dimension_real_index:
print("We got an original Rick here!")
break
current_dimension+=1
else:
print("There are no existence of Ricks between", lowest_dimension,"and",
highest_dimension)
## For measuring the runtime. You can ignore this block... ###
end=time.time()
print(f'Runtime: {end-start}')
#######################################
Runtime is still always long for real dimension pre�x
• Can we do better?
• If an original rick was found, no need to pass on the rest of the interval!
• break terminates the nearest enclosing loop, skipping the code that follows the
break inside the loop.
In [ ]: ## For measuring the runtime. You can ignore this block... ###
start=time.time()
#######################################
if dimension_prefix != dimension_real_prefix:
print("Wrong dimension prefix: ", dimension_prefix)
else:
current_dimension=lowest_dimension
got_original_rick=False
while current_dimension <= highest_dimension:
if current_dimension==dimension_real_index:
print("We got an original Rick here!")
got_original_rick=True
break # Note this break here!
current_dimension+=1
if not got_original_rick:
print("There are no existence of Ricks between", lowest_dimension,"and",
highest_dimension)
## For measuring the runtime. You can ignore this block... ###
end=time.time()
print(f'Runtime: {end-start}')
#######################################
# This is equivalent:
print("The sum is", sum(range(1,138)))
Example #2: Factorial implementation with "for" loop
In [ ]: n = 7
fact = 1
for i in range(2, n+1):
fact = fact * i
print(f'{n}! = {fact}')
# This is equivalent:
n = 7
fact = 1
for i in range(2, n+1):
fact *= i
print(f'{n}! = {fact}')
Example #3: concatenate all characters in a matrix into a single string
In [ ]: mat = [["m", "a", "t", "R"], ["i", "c", "k", "s"]]
my_string=""
num_rows = len(mat)
num_columns = len(mat[0])
for i in range(num_rows):
for j in range(num_columns):
my_string+=mat[i][j]
print(my_string)
Example #4: multiplication chart
In [ ]: for i in range(1,11):
for j in range(1,11):
print(i*j, end ="\t")
print()
Find Rick using "for" loop
In [ ]: dimension_prefix="c"
if dimension_prefix != dimension_real_prefix:
print("Wrong dimension prefix: ", dimension_prefix)
else:
for current_dimension in range(lowest_dimension, highest_dimension+1):
if current_dimension==dimension_real_index:
print("We got an original Rick here!")
break
else:
print("There are no existence of Ricks between", lowest_dimension,"and",
highest_dimension)
for i in range(len(students)):
if students[i-1] <students[i] or students[i] <students[i+1]:
last=students[i]
print(last)
Kahoot! (5b): `for` loops
for i in range(len(students)):
if students[i-1] <students[i] and students[i] <students[i+1]:
last=students[i]
print(last)
Drop capital-case letters (self-learning)
In [ ]: mat = [["M", "A", "T", "r", "i"], ["c", "k", "S", "!", "!"]]
my_string=""
num_rows = len(mat)
num_columns = len(mat[0])
for i in range(num_rows):
for j in range(num_columns):
if mat[i][j]!=mat[i][j].upper():
my_string+=mat[i][j]
print(my_string)
Drop capital-case letters: second attempt (�xed)
In [ ]: mat = [["M", "A", "T", "r", "i"], ["c", "k", "Z", "!", "!"]]
my_string=""
num_rows = len(mat)
num_columns = len(mat[0])
for i in range(num_rows):
for j in range(num_columns):
if mat[i][j]!=mat[i][j].upper() or mat[i][j].upper()==mat[i][j].lower():
my_string+=mat[i][j]
print(my_string)
Drop capital-case letters: third attemp attempt (a bit nicer)
In [ ]: mat = [["M", "A", "T", "r", "i"], ["c", "k", "Z", "!", "!"]]
my_string=""
num_rows = len(mat)
num_columns = len(mat[0])
for i in range(num_rows):
for j in range(num_columns):
if mat[i][j]!=mat[i][j].upper() or not (mat[i][j].isalpha()):
my_string+=mat[i][j]
print(my_string)
Drop capital-case letters (iterate on Strings)
• Assume that for each lower case letter we encounter has an extra heavy processing
step
▪ we will mock this process using time.sleep(0.5) (i.e., the process
takes 0.5 seconds)
Same code as before (only timing was added)
In [ ]: ## For measuring the runtime. You can ignore this block... ###
import time
start=time.time()
#######################################
mat = ["MATri","ckZ!!"]
my_string=""
num_rows = len(mat)
num_columns = len(mat[0])
for i in range(num_rows):
for j in range(num_columns):
if mat[i][j]!=mat[i][j].upper() or not (mat[i][j].isalpha()):
time.sleep(0.5) # extra heavy process
my_string+=mat[i][j]
print(my_string)
## For measuring the runtime. You can ignore this block... ###
end=time.time()
print(f'Runtime: {end-start}')
#######################################
Drop capital-case letters (Using the continue statement)
In [ ]: ## For measuring the runtime. You can ignore this block... ###
start=time.time()
#######################################
mat = ["MATri","ckZ!!"]
my_string=""
num_rows = len(mat)
num_columns = len(mat[0])
for i in range(num_rows):
for j in range(num_columns):
if not mat[i][j].isalpha():
continue
if mat[i][j]!=mat[i][j].upper():
time.sleep(0.5)
my_string+=mat[i][j]
print(my_string)
## For measuring the runtime. You can ignore this block... ###
end=time.time()
print(f'Runtime: {end-start}')
#######################################
Kahoot! (6): `for` loops with Strings
print(out_string[::-1], len(in_string)-i)
The phone book of Rick
• We want to develop an application for managing the Contacts of Ricks
• 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 pre�x
• Add contact
• Remove contact
if found:
print("Name:", name , "Phone:", phone)
else:
print("Cannot find", name , "in contact list.")
if not found:
print("Cannot find the contact {name}")
if not found:
print("Cannot find the contact {name}")
Remove a contact: implementation #2 (with for-else)
# This is equivalent:
my_list = [i**2 for i in range(7)]
print(my_list)
More examples
In [ ]: [2**i for i in range(7)]
In [ ]: print([word for word in l if len(word) < 6 and len(word) > 3])
Kahoot! (7a): list comprehension
In [ ]: print([b.upper() if b > 'w' else b for a in ["Spaceship", "Says:", "Keep", "Summe
r", "Safe!"] for b in a if b.lower()>'t'])
Kahoot! (7b): list comprehension
In [ ]: print([b.upper() if b > 'w' else b for a in ["Spaceship", "Says:", "Keep", "Summe
r", "Safe!"] for b in a if b >'q'])
Loops - "for" or "while"?
• for:
▪ Prede�ned number of iterations
▪ No need to initialize or advance the loop variable
• while:
▪ Unknown number of iterations
▪ Can specify a stop condition
Bonus: in�nite "for" loop
In [ ]: x=[1]
for a in x:
x.append(1)
print(x)
De�nition
�b(1) = 1
�b(2) = 1
�b(n) = �b(n-1) + �b(n-2)
Example
1, 1, 2, 3, 5, 8, 13, 21, 34...
Task
Write a program that for any integer n > 0, prints the nth Fibonacci number.
In [ ]: n = 7
prev = 1
curr = 1
for i in range(n-2):
new = prev + curr
prev = curr
curr = new
print("The", n, "Fibonacci number is", curr)
Find the smallest divisor using "for" loop and "break"
In [ ]: n = 141
for div in range(2, n+1):
if n % div == 0:
break
print(div)
Check if a number is prime
Naive implementation
In [ ]: n = 9
In [ ]: n = 9
In [ ]: n = 9