Dec 17-23, 2020 Vikrant Patil
These notes are available online at http://notes.pipal.in/2020/arcesium_finop_batch3/module2-day1.html
© Pipal Academy LLP
Day 1 | Day 2 | Day 3 | Day 4 | Day 5
We will be using jupyter hub from http://lab.pipal.in for this training. Create a notebook with name module2-day1.ipynb for today's session.
collection = ["Hello", "world", 1, 2, 3, 4]
for item in collection:
print(item, end=",")
for c in "on text data":
print(c,end=",")
person = {"name":"Alice", "email":"alice@wonder.land"}
for key in person:
print(key, person[key])
nums = {1, 2, 3, 4, 5, 5, 6, 6} # unique
for item in nums:# set
print(item)
def unique(items):
return set(items) # this will return set (which is uniqe), but order is not gauranteed!
unique([1, 1, 1, 2, 3, 1, 2])
nums = range(5) # this will have nmbers from 0 to 4
for i in nums:
print(i)
for i in range(5):
print(i, end=",")
for i in range(4, -1, -1):
print(i, end=',')
words = ["one", "two", "three", "four", "five"]
for w in words: # for loop syntax
print(w, end=",")
for w in reversed(words): # will allow us to go through the collection in reversed fashion
print(w, end=",")
reversedlist = reversed(words) # should not be done
for w in reversedlist:# puting for loop in reversed iterator only once is possible
print(w, end=",")
for w in reversedlist:
print(w, end=",") # it will not print anything!
for w in reversed(words):
print(w, end=",")
i = 0
for x in [1, 2, 3, 4, 5]:
print("iteration", i)
print("value of x", x)
i = i +1
for w in ["one", "two", "three", "four"]:
print(w)
words = ["one", "two", "three", "four"]
for word in words:
print(word)
for i in reversed(range(5)):
print(i, end=",")
poem = """Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
"""
for line in poem.split("\n"):
print(line)
for line in poem.split("."):
print(line)
for line in reversed(poem.split("\n")):
print(line)
for i in range(5):
print(i, end=",")
for i in reversed(range(5)):
print(i, end=",")
lines = poem.strip().split("\n")
lines
for line in lines:
print(line)
for line in reversed(lines):
print(line)
for index, value in enumerate(lines):
print(index, value)
words = ["one", "two", "three", "four", "five"] # stored by location .. by index
for word in words: # allows going over items directly accesing index!
print(word, end=",")
print()
for index, word in enumerate(words):
print(index, word)
for word in words:
print(words.index(word), word) # this time consuming O(N^2)
def printwith_linenums(poem):
lines = poem.strip().split("\n")
for i, line in enumerate(lines, start=1):
print(i, line)
printwith_linenums(poem)
firstname = ["Alice", "Elsa", "Alex", "Elisa"]
lastname = ["Wondegirl", "Frozen", "Lion", "Hacker"]
for i, name in enumerate(firstname):
print(i, name, lastname[i])
for name, last in zip(firstname, lastname):
print(name, last)
xs = ["x1", "x2", "x3", "x4"]
ys = ["y1", "y2", "y3", "y4"]
zs = ["z1", "z2", "z3", "z5"]
for x, y, z in zip(xs, ys, zs): # zip can take multiple list as argument
print(x, y, z)
print(1, 2, 3, 4, 5)
xs = ["one", "two", "three"]
nums = (1, 2, 3, 4, 5)
for n, x in zip(nums, xs):
print(n, x)
xs = ["one", "two", "three"]
nums = (1, 2, 3)
for n, x in reversed(zip(nums, xs)):
print(n, x)
xs = ["one", "two", "three"]
nums = (1, 2, 3)
for n, x in zip(reversed(nums), reversed(xs)):
print(n, x)
for i, values in enumerate(zip(nums, xs)):
print(i, values)
for i, values in reversed(zip(nums, xs)):
print(i, values)
for i, n, x in enumerate(zip(nums, xs)):
print(i, n, x)
list(zip(nums, xs))
nums
xs
list(zip(nums, xs))
zipped = zip(nums, xs)
for item in zipped: # it also an iterator
print(item)
for item in zipped:
print(item)
nums = [1, 2, 3, 4]
niter = iter(nums) # for loop internally works on iterators
next(niter)
next(niter)
next(niter)
next(niter)
next(niter)
for n in nums:
print(n)
enums = enumerate(nums)
enums
next(enums)
next(enums)
next(enums)
next(enums)
next(enums)
printwith_linenums(poem)
printwith_linenums(poem)
for i in reversed(nums):
print(i)
r = reversed(nums) #here iterartor got created
for i in r: #
print(i) # it got consumed
for i in r:
print(i)#??? nothing , its already consumed
for i in reversed(nums): # cretaed
print(i) # consumed
r = reversed(nums) # never store it like this!!! use it directly in for loop
def print_items(items):
print("started")
for i in items:
print(i)
print("ended")
print_items(r)
print_items(r)
for i in reversed(nums):
print(i)
x = 10 # it is not an iterator
Problems
vector_add which does vector addition of two vectors taken as a list>>> vector_add([1, 1, 1], [3 , 4, 5])
[4, 5, 6]
>>> m = [[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]]
>>> is_unit_matrix(m)
True
>>> is_unit_matrix([[1,2],[2,1]])
False
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
Write a functio merge whcih will merge the lists into a single list such that alternatively one item from first list and one item from second list is taken.
>>> merge(a, b)
[1, 'a', 2, 'b', 3, 'c']
def vector_add(vector1, vector2):
result = []
for v1, v2 in zip(vector1, vector2):
result.append(v1+v2)
return result
vector_add([1, 1, 1], [3, 4, 5])
vector_add([2, 3, 4], [2, 2, 2])
m = [[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]]
#for row in m:
# print(row)
def is_unit_matrix(mat):
for i, row in enumerate(mat):
if row[i]!=1 or sum(row)!=1:
return False
return True
is_unit_matrix(m)
m1 = [[1, 1, 1],
[0, 1, 1],
[0, 0, 1]]
is_unit_matrix(m1)
m2 = [[1, -2, 2],
[0, 1, 0],
[0 , 0, 1]]
is_unit_matrix(m2)
def zeros_except_diagonal(row, rowindex):
for i, item in enumerate(row):
if i!=rowindex and item!=0:
return False
return True
def is_unit_matrix(mat):
for i, row in enumerate(mat):
if row[i]!=1 or not zeros_except_diagonal(row,i):
return False
return True
is_unit_matrix(m2)
is_unit_matrix(m1)
is_unit_matrix(m)
2*3
2*3
5*6
2*4
5*3
5**5 # only repr of last line will be shown
def findlens(words):
"""
compute length of every word
word1 -> len(word1)
word2 -> len(word2)
word3 -> len(word3)
"""
lens = []
for word in words:
lens.append(len(word))
return lens
def squares(nums):
"""
compute square of every item
n1 -> n1*n1
n2 -> n2*n2
n3 -> n3*n3
n4 -> n4*n4
"""
sqrs = []
for n in nums:
sqrs.append(n*n)
return sqrs
words= "Hello make some words out of this text".split()
words
findlens(words)
nums = [2, 3, 1, 4, 5]
squares(nums)
these are some examples of mappings!
List1 result
|| ||
item1 -> do_operation(item1)
item2 -> do_operation(item2)
item3 -> do_operation(item3)
item4 -> do_operation(item4)
[len(word) for word in words]
[x*x for x in nums]
[x*x*x for x in nums]
def findlens(words):
return [len(w) for w in words]
def squares(numbers):
return [n*n for n in numbers]
def cubes(nums):
return [x*x*x for x in nums]
def evens(nums):
e = []
for n in nums:
if n%2==0:
e.append(n)
return e
evens([1, 2, 12, 12, 2, 3, 4, 5, 6, 7, 5, 7, 5])
def find_words_of_len(words, l):
words_of_len = []
for w in words:
if len(w)==l:
words_of_len.append(w)
return words_of_len
find_words_of_len(words, 4)
[n for n in nums if n%2==0] # filtering
[w for w in words if len(w)==4] # filtering operation
[n*n for n in nums if n%2==0] # filtering and mapping
def even(x):
return x%2==0
even(3)
even(2)
[n for n in nums if even(n)]
[n*n for n in nums if even(n)]
Problems
>>> listpy(os.getcwd())
add.py
add1.py
add2.py
hello.py
records = [("2018-11-11 24:04","11803","16602"),
("2018-11-11 24:09","11782","16568"),
("2018-11-11 24:14","11741","16524"),
("2018-11-11 24:19","11756","16543"),
("2018-11-11 24:24","11741","16538"),
("2018-11-11 24:28","11722","16558"),
("2018-11-11 24:34","11716","16457"),
("2018-11-11 24:39","11724","16430"),
("2018-11-11 24:44","11723","16572"),
("2018-11-11 24:49","11739","16611"),
("2018-11-11 24:54","11740","16501"),
("2018-11-11 24:58","11743","16568"),
("2018-11-12 01:04","11754","16626")]
The timestamp given above has been misprinted, instead of 11th Nov 24:04 , it should be 12 Nov 00:04! Write a function to correct the record. use list comprehension to do this.
Bonus Problem
"<" --------- less than
"<="--------- less than or equal to
">" --------- greater than
">="--------- greater than or equal to
"<>"--------- not equal to
Sample run is shown below:
>>> a = [10,20,30,40,50,40,40,50]
>>> COUNTIFS(a, "<40")
3
>>> COUNTIFS(a, ">=40")
5
>>> COUNTIFS(a, "40")
>>> COUNTIFS(a, "<>40")
5