You are on page 1of 98

Recitation 2

Python Programming for Engineers

Tel-Aviv University / 0509-1820 / Spring 2022


Last week's highlights
• Memory and variables
• Different variable types (int, �oat, str, bool)
• Different operations for different types
• If-else statements
if expression:
statement1
else:
statement2
Agenda

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}")

# This is equivalent too (but a bit old...)


print('My name is %s and I am c-%.2f' % (name,pi))
In [ ]: i="100"
j="37"
k="137"

In [ ]: print(f"Rick is {i}+{j}==k")

Kahoot! (1): string formatting

In [ ]: print(f"Rick is {i+j==k}")


print(f"Rick is {int(i)+int(j)==int(k)}")
print(f"Rick is {int(i+j)==int(k)}")
See also https://realpython.com/python-string-formatting/ (https://realpython.com/python-string-
formatting/)
Lists
• A ordered collection of elements
• Each element in a list can be of any type

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 [ ]: print(my_str[2], my_str_list[2])

In [ ]: print(my_str[-3], my_str_list[-3])

In [ ]: print(my_str[4], my_str_list[4])


Lists
Basics
In [ ]: my_list = ['Rick','Morty', 'Beth', 'Jerry', 'Summer']

Access an element by position

In [ ]: my_list = ['Rick','Morty', 'Beth', 'Jerry', 'Summer']

In [ ]: my_list[3]
Length of a list

In [ ]: len(my_list)

Can mix di�erent element types

In [ ]: # student: name, age, height, SAT


student = ['Rick', 81, 1.83, 9000]

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 [ ]: my_list = ['Rick','Morty', 'Beth', 'Jerry', 'Summer']

In [ ]: my_list[1:5] # slicing

In [ ]: my_list[0:-1] # forward/backward indexing

In [ ]: my_list[::2] # add a step


In [ ]: # reverse
my_list[::-1]

In [ ]: # output is an empty list. This is NOT an error


my_list[1:10:2]

In [ ]: my_list = ['Rick','Morty', 'Beth', 'Jerry', 'Summer']


new_list = my_list[::2]
print(my_list)
print(new_list)
Nested lists/Matrix
In [ ]: mat = [["m", "a", "t", "R"], ["i", "c", "k", "s"]]
print(mat)

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

In [ ]: m=[[2,2], [1,3]]


n=[[4,2],[9,2]]

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

In [ ]: m=[[2,2,3], [1,3,7]]


n=[[4,2,3],[9,2,1]]

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)

*bolded does not change the list


Other list's function:
function description
len() returns the list’s length
sum() returns a sum of all list elements
min() returns the minimal element
max() returns the maximal element

in | returns True if element in list (e.g. 1 in lst)|


Examples of usage in List's methods/functions
In [ ]: students = ['Rick','Morty', 'Beth', 'Jerry', 'Summer']
print(students)

In [ ]: students.extend(['Jessica'])
print(students)

In [ ]: students.insert(1, 'Tiny Rick!')


print(students)

In [ ]: students.extend(["Rick c-134", "Rick c-135", "Rick c-136"])


print(students)

In [ ]: students[8]+=" (a.k.a evil Rick)"


print(students)
In [ ]: students[7:10]=["Rick", "Rick", "Rick"]
print(students)

In [ ]: students.remove('Morty')
print(students)
students.remove('Morty')

In [ ]: print("Morty" in students)


In [ ]: print("beth" in students)

In [ ]: print("Beth" in students)

In [ ]: print("Be" in "Beth")

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 [ ]: first_student = students.pop(0)


print(first_student)
Sorting a list
In [ ]: a = [3,7,1]
b = sorted(a)
print(a)
print(b)

In [ ]: a = [3,7,1]
b = a.sort()
print(a)
print(b)

**in-place operation vs copy**


Iterable

• Represent a sequence of some kind


▪ What kind of sequence did we see so far? Strings, Lists
Range
• Another iterable range(from, to, step) returns: from, from+step,
from+2*step,…, from+i*step until (and not including) to is reached.

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

In [ ]: list(range(1, 7, -3))

In [ ]: list(range(0, 137, 0))


While loops
Syntax
while expression: ## expression is either True or False
statement1
statement2

rest of code…
Run until the expression is False

• 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)⋅𝑛

In [ ]: # factorial implementation with "while" loop


n = 7

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?

improving our search of Rick c-137... (self-learning)


Our implementation from last week

In [ ]: # "Input" values


lowest_dimension=130
highest_dimension=150
dimension_prefix="c"

# "Secret" values (unknown to users)


dimension_real_index = 137
dimension_real_prefix="c"

if highest_dimension >= lowest_dimension:


if dimension_prefix != dimension_real_prefix:
print("Wrong dimension prefix: ", dimension_prefix)
else:
if lowest_dimension+1 == dimension_real_index:
print("We got an original Rick here!")

elif lowest_dimension+2 == dimension_real_index:


print("We got an original Rick here!")

elif lowest_dimension+3 == dimension_real_index:


print("We got an original Rick here!")

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"

# "Secret" values (unknown to users)


dimension_real_index = 137
dimension_real_prefix="c"

In [ ]: if highest_dimension >= lowest_dimension:


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!")
current_dimension+=1

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!

Let's change the current implementation:

• Drop the "too many dimensions to this implmenetation..." message


• If the dimension pre�x is corrent, print either "There are no existence of Ricks
between... " or "We got an original Rick here!"
Implementation with a while loop #2

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"

Let's go back to the implementations and see...

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!

• Use break statement!


break statement – breaking loops

• break terminates the nearest enclosing loop, skipping the code that follows the
break inside the loop.

• Used for getting out of loops when a condition occurs.


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
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}')
#######################################

• "Breaks" the loop as soon as we �nd an original Rick


For loops
Syntax
for element in iterable:
statement1
statement2

rest of code…
Run over all elements in iterable (list, string, etc.)

• Iteration 0: Assign element = iterable[0]


▪ Execute statement1, statement2, …
• Iteration 1: Assign element = iterable[1]
▪ Execute statement1, statement2, …
• …
• No more elements in the list → "jump" to the rest of the code (i.e leave the loop)

Variable element is de�ned by the loop!


Print each element separately with a descriptive text:
In [ ]: lst = ['rick', 'c', 137]
for i in range(len(lst)):
print("current element:",i, elem)
print(lst)
Iteration can also be done on a string
In [ ]: name = "Rick"
for letter in name:
print("Give me", letter)
print("What did we get?", name)
continue statement
• Stops the current iteration and jump to the next one
• Applied to both for and while loops

In [ ]: # Create a list of unique elements


lst = [1,3,3,1,7,7,7,1,3]
uniques = []
for x in lst:
if x in uniques:
break
uniques.append(x)
print(uniques)
break statements are also applied to for loops
-Reminder: break terminates the nearest enclosing loop, skipping the code that follows
the break inside the loop.

• Used for getting out of loops when a condition occurs.


break statements are also applied to for loops
-Reminder: break terminates the nearest enclosing loop, skipping the code that follows
the break inside the loop.

• Used for getting out of loops when a condition occurs.

In [ ]: lst = [4, 2, -6, 3,-9]


for elem in lst:
if elem < 0:
print("First negative number is", elem)
break
Example #1: Compute 1 + 2 + … + 100:
In [ ]: partial_sum = 0
numbers = range(1,138)
for num in numbers:
partial_sum = partial_sum + num
print("The sum is", partial_sum)

# 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"

In [ ]: # "Secret" values (unknown to users)


dimension_real_index = 137
dimension_real_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)

• No need to initialize and increment the running index variable (current_dimension)


• More intuitive
Kahoot! (5a): `for` loops

In [ ]: students = ['Morty', 'Beth', 'Jerry', 'Summer', "Rick"]

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

In [ ]: students = ['Morty', 'Beth', 'Jerry', 'Summer', "Rick"]

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)

In [ ]: 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()):
my_string+=mat[i][j]
print(my_string)

Where is the bug?


Drop capital-case letters (iterate on Strings; �xed)

In [ ]: 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()):
my_string+=mat[i][j]
print(my_string)
Drop capital-case letters: with an extra heavy process

• 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

In [ ]: in_string = "c-137"


out_string = ""
for i, c in enumerate(in_string[::-1]):
if not c.isdigit():
break
out_string += c

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

In [ ]: phone_book = [['Morty','1111'], ['Beth', '2222'], ['rick c-138', '8888'], ['rick


c-139', '9999']]
Retrieve the number for a given person
name = input("Please choose a contant name")
### Your implementation here...

if found:
print("Name:", name , "Phone:", phone)
else:
print("Cannot find", name , "in contact list.")

In [ ]: name = input("Please choose a contant name: ")


found = False
phone = ""
for contact in phone_book:
if contact[0] == name:
found = True
phone = contact[1]
break
if found:
print("Name:", name , "Phone:", phone)
else:
print("Cannot find", name , "in contact list.")
Add a contact

In [ ]: name = input("Please choose a contant name: ")


num = input("Please choose a contant number: ")
phone_book.append([name, num])
print(phone_book)
Remove a contact
name = input("Please choose a contant name: ")
found = False
for contact in phone_book:
if contact[0] == name:
### Your implementation here...

if not found:
print("Cannot find the contact {name}")

In [ ]: name = input("Please choose a contant name: ")


found = False
for contact in phone_book:
if contact[0] == name:
phone_book.remove(contact)
print(f'The contact {name} was deleted')
found = True
break

if not found:
print("Cannot find the contact {name}")
Remove a contact: implementation #2 (with for-else)

In [ ]: name = "Morty"


for contact in phone_book:
if contact[0] == name:
phone_book.remove(contact)
break
else:
print("Cannot find contact")
Search for all contacts with given pre�x.

Ignore character case (aka, case insensitive).

In [ ]: prefix = "Rick"


prefix = prefix.lower()
for contact in phone_book:
if contact[0].lower().startswith(prefix):
print("Name:", contact[0], "Phone:", contact[1])
List comprehension
• Pythonic way of creating lists.
• Combining lists and for loops.
• Syntax:
[expression for item in list]
• We can even write:
[expression for item in list if condition]
Example #1: Series of squared integers ranged between 1 to 6
In [ ]: my_list=[]
for i in range(7):
my_list.append(i*i)
print(my_list)

# 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 [ ]: [1 for i in range(7)]

In [ ]: [i for i in range(7) if (i%3==0 or i%4==0)]


In [ ]: l = ["so", "everyone’s", "supposed", "to", "sleep", "every", "single", "night", "
now?", "You", "realize", "that", "nighttime", "makes", "up", "half", "of", "all",
"time?"]

In [ ]: print([word.upper() for word in l])

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"?

In most cases it is more natural to use for


In some cases it is better to use 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)

You should avoid changing the list on which you iterate!


More "for" loop examples (from lecture)
Fibonacci series

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

for div in range(2,n):


if n % div == 0:
break
if n % div == 0:
print(n, "is not prime")
else:
print(n, "is prime")
Optimized implementation: run until the squared root of n

In [ ]: n = 9

for div in range(2,int(n**0.5)):


if n % div == 0:
break
if n % div == 0:
print(n, "is not prime")
else:
print(n, "is prime")
Fixed (optimized) implementation

In [ ]: n = 9

for div in range(2,int(n**0.5)+1):


if n % div == 0:
break
if n % div == 0:
print(n, "is not prime")
else:
print(n, "is prime")
That's all for now... �

You might also like