Sep 13-17, 2021 Vikrant Patil
These notes are available online at https://notes.pipal.in/2021/arcesium_finop_batch1/module1-day4.html
© Pipal Academy LLP
Day 1 | Day 2 | Day 3 | Day 4 | Day 5
We will be using jupyter hub from https://lab.pipal.in for this training.
login to hub and create a notebook with name module1-day4
items = [[1, 2, 3, 4],
[1, 1, 1],
[1, 2, 3, 4, 5, 6, 7],
[2]
[1, 2, 3, 4, 5]]
courses = {
"practical python": ["Python practice book", "Python for finance", "Python cookbook"],
"elegant programming": ["SICP", "Python programming", "Art of Programming"],
"python primer": ["Python practice book", "Python from scratch"],
"extreme programming": ["Async Python", "Web and Python", "Optimizing python code", "Advanced Python"]
}
def sumof(x, y, func):
return func(x) + func(y)
items = [[1, 2, 3, 4],
[1, 1, 1],
[1, 2, 3, 4, 5, 6, 7],
[2],
[1, 2, 3, 4, 5]]
len("hello")
5
len([1, 2, 3, 4])
4
max(items, key=len)
[1, 2, 3, 4, 5, 6, 7]
courses = {
"practical python": ["Python practice book", "Python for finance", "Python cookbook"],
"elegant programming": ["SICP", "Python programming", "Art of Programming"],
"python primer": ["Python practice book", "Python from scratch"],
"extreme programming": ["Async Python", "Web and Python", "Optimizing python code", "Advanced Python"]
}
def number_of_books(coursename):
num_books = len(courses[coursename])
print("Coursename:", coursename, "num_books", num_books)
return num_books
min(courses, key=number_of_books)
Coursename: practical python num_books 3 Coursename: elegant programming num_books 3 Coursename: python primer num_books 2 Coursename: extreme programming num_books 4
'python primer'
courses.keys()
dict_keys(['practical python', 'elegant programming', 'python primer', 'extreme programming'])
courses.values()
dict_values([['Python practice book', 'Python for finance', 'Python cookbook'], ['SICP', 'Python programming', 'Art of Programming'], ['Python practice book', 'Python from scratch'], ['Async Python', 'Web and Python', 'Optimizing python code', 'Advanced Python']])
courses.items()
dict_items([('practical python', ['Python practice book', 'Python for finance', 'Python cookbook']), ('elegant programming', ['SICP', 'Python programming', 'Art of Programming']), ('python primer', ['Python practice book', 'Python from scratch']), ('extreme programming', ['Async Python', 'Web and Python', 'Optimizing python code', 'Advanced Python'])])
len(courses)
4
courses['python primer']
['Python practice book', 'Python from scratch']
len(courses['python primer'])
2
def longest_book_name(coursename):
books = courses[coursename]
return len(max(books, key=len))
min(courses, key=longest_book_name)
'elegant programming'
courses
{'practical python': ['Python practice book',
'Python for finance',
'Python cookbook'],
'elegant programming': ['SICP', 'Python programming', 'Art of Programming'],
'python primer': ['Python practice book', 'Python from scratch'],
'extreme programming': ['Async Python',
'Web and Python',
'Optimizing python code',
'Advanced Python']}
def get_books(key_value):
print(key_value)
return len(key_value[1])
max(courses.items(), key=get_books)
('practical python', ['Python practice book', 'Python for finance', 'Python cookbook'])
('elegant programming', ['SICP', 'Python programming', 'Art of Programming'])
('python primer', ['Python practice book', 'Python from scratch'])
('extreme programming', ['Async Python', 'Web and Python', 'Optimizing python code', 'Advanced Python'])
('extreme programming',
['Async Python',
'Web and Python',
'Optimizing python code',
'Advanced Python'])
min(courses.items(), key=get_books)
('practical python', ['Python practice book', 'Python for finance', 'Python cookbook'])
('elegant programming', ['SICP', 'Python programming', 'Art of Programming'])
('python primer', ['Python practice book', 'Python from scratch'])
('extreme programming', ['Async Python', 'Web and Python', 'Optimizing python code', 'Advanced Python'])
('python primer', ['Python practice book', 'Python from scratch'])
t = ('python primer', ['Python practice book', 'Python from scratch'])
t[0]
'python primer'
t[1]
['Python practice book', 'Python from scratch']
t[1][0]
'Python practice book'
def make_adder(x):
def adder(y):
return x+y
return adder # it is returning a function
adder5 = make_adder(5) # x is given here as parameter
adder5
<function __main__.make_adder.<locals>.adder(y)>
adder5(7)
12
adder5(9)
14
f = lambda x,y: x+y
f(3,4)
7
sqr = lambda x: x*x
sqr(5)
25
def foo():
print("hello")
def make_adder(x):
def adder(y):
return x+y
return adder(7) # this is not returning a function
make_adder(5)
12
make_adder(8)
15
def make_logger(type_):
def print_message(message):
return print(type_.upper() + ":", message)
return print_message
warning = make_logger("warn") ##
info = make_logger("info")
error = make_logger("error")
warning("Your input contains floats! I expect integers")
WARN: Your input contains floats! I expect integers
info("Your input look of, I am processing")
INFO: Your input look of, I am processing
error("Something went wrong, division by zero!")
ERROR: Something went wrong, division by zero!
Conditions
True
True
False
False
"hello".endswith("o")
True
"hel" in "Hello"
False
"Hel" in "Hello"
True
1 in [1, 2, 3, 4]
True
courses
{'practical python': ['Python practice book',
'Python for finance',
'Python cookbook'],
'elegant programming': ['SICP', 'Python programming', 'Art of Programming'],
'python primer': ['Python practice book', 'Python from scratch'],
'extreme programming': ['Async Python',
'Web and Python',
'Optimizing python code',
'Advanced Python']}
"python primer" in courses # it will check in keys only
True
x = 10
y = 15
x == y
False
x == 5
False
x == 10
True
1 not in [2, 3, 4, 5, 6]
True
1 not in [1, 2, 3, 4]
False
x, y = 2, 4
x
2
y
4
x, y = [4, 5]
x
4
y
5
x, y = (5, 6)
x
5
y
6
x > y
False
x >= y
False
x < y
True
x <= y
True
x != y
True
print(x, y)
5 6
cond = True
if cond:
print("hello")
hello
if "hel" in "cell":
x = 10
y = 20
z = x+y
print("hell!")
elif "cel" in "hell":
print("cell")
elif "del" in "bell":
print("dell")
else:
print("oops!")
oops!
[1, 2] in [1, 2, 3, 4]
False
[1, 2] in [[1,2],[2,3],[3,4]]
True
i = 0
while i < 5:
print(i)
i = i + 1
0 1 2 3 4
words = "This is some sentence for testing while loop".split()
print(words)
i = 0
while i<len(words):#possibility of having wrong condition..might result in infite loop
print(words[i]) # if indexing goes wrong possibility of going out of index
i = i +1
['This', 'is', 'some', 'sentence', 'for', 'testing', 'while', 'loop'] This is some sentence for testing while loop
def print_fib(n):
"""print fibonacci numbers lees than n
"""
curr, prev = 1, 1
while prev<n:
print(prev, end=",")#after every print put a comma insted new line
curr , prev = prev+curr, curr
print_fib(1000)
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
words
['This', 'is', 'some', 'sentence', 'for', 'testing', 'while', 'loop']
for word in words:
print(word)
This is some sentence for testing while loop
for c in "hello":
print(c)
h e l l o
for coursename in courses: #loop over keys
print(coursename)
practical python elegant programming python primer extreme programming
for books in courses.values():
print (books)
['Python practice book', 'Python for finance', 'Python cookbook'] ['SICP', 'Python programming', 'Art of Programming'] ['Python practice book', 'Python from scratch'] ['Async Python', 'Web and Python', 'Optimizing python code', 'Advanced Python']
for key, value in courses.items():
print(key, value)
practical python ['Python practice book', 'Python for finance', 'Python cookbook'] elegant programming ['SICP', 'Python programming', 'Art of Programming'] python primer ['Python practice book', 'Python from scratch'] extreme programming ['Async Python', 'Web and Python', 'Optimizing python code', 'Advanced Python']
def mysum(numbers):
s = 0
for n in numbers:
s = s + n
return s
mysum([1,2, 3, 4, 5, 6, 8])
29
list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list(range(5, 100, 5))
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
for i in range(5):
print(i)
0 1 2 3 4
mysum((1, 2, 3, 4, 5))
15
problems
product which finds product of all elements from a list/coolection.
>>> product([3, 2, 4])
24
factorial which computes factorial of a number.
>>> factorial(5)
120
findlens which will find length of every word from a list of words
>>> findlens(["one", "two", "three"])
[3, 3, 5]
>>> words = ["one", "two", "three", "four", "five", "six"]
>>> find_words_of_len(words, 3)
["one", "two", "six"]
bonus
unique which will remove duplicates from a list:
>>> unique([1, 1, 1, 2, 2, 3, , 4, 4, 5])
[1, 2, 3, 4, 5]
if x == y:
print("equal")
else:
print("unequal")
unequal
del i
def func():
#i = 0
while i < 5:
i = i +1
print(i)
func()
--------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) <ipython-input-114-bd1982955a12> in <module> ----> 1 func() <ipython-input-113-86ce4d620c3a> in func() 1 def func(): 2 #i = 0 ----> 3 while i < 5: 4 i = i +1 5 print(i) UnboundLocalError: local variable 'i' referenced before assignment
#product(1, 2, 3) # three argument!
#product([1, 2, 3]) # signle argment, which is a list
--------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) <ipython-input-116-bd1982955a12> in <module> ----> 1 func() <ipython-input-113-86ce4d620c3a> in func() 1 def func(): 2 #i = 0 ----> 3 while i < 5: 4 i = i +1 5 print(i) UnboundLocalError: local variable 'i' referenced before assignment
mysum([1, 2, 3, 4])
10
mysum([1, 2, 3, 4])
10
for i in 4:
print(i)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-120-d5ac0dd5fd2d> in <module> ----> 1 for i in 4: 2 print(i) 3 TypeError: 'int' object is not iterable
for i in range(4):
print(i)
0 1 2 3
for i in range(1, 5):
print(i)
1 2 3 4
### n in num
#item in collection (list, tuple, string, dictionary)
4 in 54
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-125-511254e4adcd> in <module> ----> 1 4 in 54 TypeError: argument of type 'int' is not iterable
"4" in "54"
True
4 in [4, 5, 54]
True
def factorial(num):
mult = 1
n = 1
while n <= num:
mult = mult*n
n = n+1
return mult
factorial(5)
120
def findlens(words):
lens = [] # empty list
for word in words:
length = len(word)
lens.append(length)
return lens
findlens(words)
[4, 2, 4, 8, 3, 7, 5, 4]
words
['This', 'is', 'some', 'sentence', 'for', 'testing', 'while', 'loop']
def make_upper(words):
upper_words = []
for word in words:
upper = word.upper()
upper_words.append(upper)
return upper_words
make_upper(words)
['THIS', 'IS', 'SOME', 'SENTENCE', 'FOR', 'TESTING', 'WHILE', 'LOOP']
def make_squares(numbers):
sqrs = []
for num in numbers:
s = num**2
sqrs.append(s) # adding next value
return sqrs
make_squares([2, 3, 4, 5, 2, 3, 5])
[4, 9, 16, 25, 4, 9, 25]
",".join(words)
'This,is,some,sentence,for,testing,while,loop'
":".join(words)
'This:is:some:sentence:for:testing:while:loop'
" ".join(words)
'This is some sentence for testing while loop'
def func_with_two_values(x):
return x, x+5
func_with_two_values(7)
(7, 12)
a, b = func_with_two_values (7)
def product(numbers):
p = 1
for num in numbers:
p = p * num
return p
product([2, 3, 4, 5])
120
product([1, 6, 7])
42
def factorial(n):
return product(range(1, n+1))
factorial(5)
120
factorial(-1)
1
factorial(0)
1
list(range(1, 5))
[1, 2, 3, 4]
list(range(5))
[0, 1, 2, 3, 4]
list(range(5, 50, 5)) # start, end, step
[5, 10, 15, 20, 25, 30, 35, 40, 45]
def find_words_of_len(words, l):
"""find all words of length l from given words
"""
newwords = []
for word in words:
length = len(word)
if length == l:
newwords.append(word)
return newwords
find_words_of_len(words, 2)
['is']
find_words_of_len(words, 4)
['This', 'some', 'loop']
def unique(items):
my_collection = []
for item in items:
if item not in my_collection:
my_collection.append(item)
return my_collection
[1, 1, 2, 3, 4, 5, 5, 6, 6, 6]
unique items
[1, 2, 3, 4, 5, 6]
unique([1, 1, 1, 2, 3, 2, 4, 5,5, 5, 5, 6, 2, 3, 1, 6, 6])
[1, 2, 3, 4, 5, 6]
tips for looping
for i in range(5,20, 3):
print(i)
5 8 11 14 17
i = 5
while i < 20:#possible error
print(i)
i = i + 3 #possible error
5 8 11 14 17