Sep 20-24, 2021 Vikrant Patil
These notes are available online at https://notes.pipal.in/2021/arcesium_finop_batch1/
© Pipal Academy LLP
We will be using jupyter hub from https://lab.pipal.in for this training.
create a notebook with name module2-day1
def squares(numbers):
sqr = []
for n in numbers:
sqr.append(n*n)
return sqr
squares([1, 2, 3, 4])
[1, 4, 9, 16]
squares('[1, 2, 3, 4, 5]') # this is not a list which we are passing as an argument
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-3-2a34ce5e7bfd> in <module> ----> 1 squares('[1, 2, 3, 4, 5]') # this is not a list which we are passing as an argument <ipython-input-1-96f3c59bfb8e> in squares(numbers) 3 4 for n in numbers: ----> 5 sqr.append(n*n) 6 7 return sqr TypeError: can't multiply sequence by non-int of type 'str'
x = input("Enter a list")
print(x)
[1, 2, 3, 4, 5, 6]
x
'[1, 2, 3, 4, 5, 6]'
for item in x:
print(item, end="-")
[-1-,- -2-,- -3-,- -4-,- -5-,- -6-]-
def extract_int_list(text_input):
text_input = text_input.strip() # this will remove trainling spaces
text_input = text_input.replace("[","").replace("]","") # this is method chaining...
# next method is applied on output of first
nums = []
for item in text_input.split(","):
strn = item.strip()
nums.append(int(strn))
return nums
extract_int_list(x)
[1, 2, 3, 4, 5, 6]
extract_int_list(input("Enter some list of ints:"))
[12, 23, 34, 1, 2, 3]
squares([1, 2, 3, 4])
[1, 4, 9, 16]
int("4f")
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-14-bf727f49db3a> in <module> ----> 1 int("4f") ValueError: invalid literal for int() with base 10: '4f'
numbers = [45, 34, 23, 45, 7, 2, ,5]
File "<ipython-input-15-fc1d0b1b54c9>", line 1 numbers = [45, 34, 23, 45, 7, 2, ,5] ^ SyntaxError: invalid syntax
numbers = [45, 34, 23, 46, 7, 2,5]
max(numbers)
46
2**100
1267650600228229401496703205376
len(656767) # interanally python does not know these digits, it is binary number
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-21-7a33a2562928> in <module> ----> 1 len(656767) TypeError: object of type 'int' has no len()
for i in 87658763:
print(i)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-22-6322e915bff5> in <module> ----> 1 for i in 87658763: 2 print(i) TypeError: 'int' object is not iterable
for c in str(374636):
print(c, end=",")
3,7,4,6,3,6,
def count_digits(n):
return len(str(n))
count_digits(435435)
6
numbers = [451, 34111112, 2311, 4621, 7121, 21, 5]
max(numbers, key=count_digits)
34111112
volume = ["6B","5M","3M","1.5B"]
def convert(strn):
if strn.endswith("B"):
n = float(strn[:-1])
return n*10**9
elif strn.endswith("M"):
n = float(strn[:-1])
return n*10**6
else:
return float(strn)
max(volume, key=convert)
'6B'
sorted(volume, key=convert)
['3M', '5M', '1.5B', '6B']
sorted(volume, key=convert, reverse=True)
['6B', '1.5B', '5M', '3M']
import os
%%file mymathmodule.py
def add(x, y):
return x+y
def square(x):
s = x*x
return s
Writing mymathmodule.py
import mymathmodule
mymathmodule.add(3, 4)
7
%%file square.py
def square(x):
return x*x
print(square(5))
Overwriting square.py
!python3 square.py
25
%%file square.py
import sys
def square(x):
return x*x
print(sys.argv)
#print(square())
Overwriting square.py
!python3 square.py
['square.py']
!python3 square.py 5 some args more words
['square.py', '5', 'some', 'args', 'more', 'words']
%%file square.py
import sys
def square(x):
return x*x
print(square(sys.argv[1]))
Overwriting square.py
!python3 square.py 5
Traceback (most recent call last):
File "square.py", line 6, in <module>
print(square(sys.argv[1]))
File "square.py", line 4, in square
return x*x
TypeError: can't multiply sequence by non-int of type 'str'
%%file square.py
import sys
def square(x):
return x*x
arg = sys.argv[1]
n = int(arg)
print(square(n))
Overwriting square.py
!python3 square.py 5
25
!python3 square.py 56
3136
!python3 square.py 95874398736895745 # this ! symbols makes sure that whatever is command it goes to operating system
9191900333161276424288358999105025
import square # this run inside interpreter or inside another module
# what sys.argv when i import a module?
%%file just_another.py
import sys
print(sys.argv)
Overwriting just_another.py
%%file capitalize.py
import sys
print(sys.argv)
Writing capitalize.py
!python3 capitalize.py python programming from scratch
['capitalize.py', 'python', 'programming', 'from', 'scratch']
%%file capitalize.py
import sys
print(sys.argv)
print(" ".join(sys.argv[1:]))
Overwriting capitalize.py
!python3 capitalize.py the tile of book is this
['capitalize.py', 'the', 'tile', 'of', 'book', 'is', 'this'] the tile of book is this
!python3 capitalize.py "the tile of book is this"
['capitalize.py', 'the tile of book is this'] the tile of book is this
numbers = [1, 2, 3, 4, 5]
for n in numbers:
print(n, end=",")
1,2,3,4,5,
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""" #this is multiline text
poem
'Beautiful is better than ugly\nExplicit is better than implicit\nsimple is better than complex\ncomplex is better than complicated\nflat is better than nested\nsparse is better than dense'
lines = poem.split("\n")
for line in lines:
print(line)
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
for item in reversed(numbers):
print(item, end=",") #instead of new line put a commo after every print
5,4,3,2,1,
for line in reversed(lines):
print(line) # if no end is given it means go to next line after very print
sparse is better than dense flat is better than nested complex is better than complicated simple is better than complex Explicit is better than implicit Beautiful is better than ugly
size = len(numbers)
for i in range(len(numbers)):
print(numbers[size-i])
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-79-996e6cbb4815> in <module> 1 size = len(numbers) 2 for i in range(len(numbers)): ----> 3 print(numbers[size-i]) IndexError: list index out of range
size = len(numbers)
for i in range(len(numbers)):
print(numbers[size-i-1]) # indexing always has possiblity of errors as you can see above
5 4 3 2 1
numbers[0]
1
numbers[2]
3
numbers[5-1]
5
for n in reversed(numbers):
print(n) # there is no chance of any logical error
5 4 3 2 1
lines
['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']
for i, line in enumerate(lines):
print(i, line)
0 Beautiful is better than ugly 1 Explicit is better than implicit 2 simple is better than complex 3 complex is better than complicated 4 flat is better than nested 5 sparse is better than dense
for i, line in enumerate(lines, start=1):
print(i, line)
1 Beautiful is better than ugly 2 Explicit is better than implicit 3 simple is better than complex 4 complex is better than complicated 5 flat is better than nested 6 sparse is better than dense
multiline = "one\ntwo\nthree\nfour"
print(multiline)
one two three four
multiline="""one
two
three
four"""
reversed # allows access in reverse fashion
enumerate #index, item
enumerate
first = ["Alice", "Alex", "Elsa", ""]
for ind, line in enumerate(lines, start=1):
print(ind, line) # these names ind, line are programmers choice..but first is always index and second item in always item from collection
1 Beautiful is better than ugly 2 Explicit is better than implicit 3 simple is better than complex 4 complex is better than complicated 5 flat is better than nested 6 sparse is better than dense
def add(x, y):
return x+y
add(x=4, y=10)
14
add(4, 10)
14
add(4, y=10) # give all non named arguments first and then keyword
14
add(x=4, 10) # positional (arguments without names has to be given first)
File "<ipython-input-107-80ed357f93dd>", line 1 add(x=4, 10) # positional (arguments without names has to be given first) ^ SyntaxError: positional argument follows keyword argument
max(numbers, key=count_digits)
1
max(key=count_digits, numbers)
File "<ipython-input-109-07ae39a62dcb>", line 1 max(key=count_digits, numbers) ^ SyntaxError: positional argument follows keyword argument
for i, line in enumerate(lines, start=1):
print(i, line)
1 Beautiful is better than ugly 2 Explicit is better than implicit 3 simple is better than complex 4 complex is better than complicated 5 flat is better than nested 6 sparse is better than dense
help(max)
Help on built-in function max in module builtins:
max(...)
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
max(arg1=4, arg2=5)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-113-248bd354ac2a> in <module> ----> 1 max(arg1=4, arg2=5) TypeError: max expected 1 argument, got 0
add(3, 4)
7
max(numbers, count_digits)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-115-acc63a40ad5b> in <module> ----> 1 max(numbers, count_digits) TypeError: '>' not supported between instances of 'function' and 'list'
max(numbers, key=count_digits)
1
first = ["Alice", "Alex", "Elsa", "Elisa"]
lastname = ["Wondergirl", "Lion", "Frozen", "Hacker"]
for name, surname in zip(first, lastname):
print(name, surname)
Alice Wondergirl Alex Lion Elsa Frozen Elisa Hacker
i = 0
n = len(first)
for i in range(n):
print(first[i], lastname[i]) # again prone errors!
Alice Wondergirl Alex Lion Elsa Frozen Elisa Hacker
for i,j in zip([1, 2, 3, 4], [1, 1, 1, 1]):
print(i,j)
1 1 2 1 3 1 4 1
xs = ['x1', 'x2', 'x3', 'x4']
ys = ['y1', 'y2', 'y3', 'y3']
zs = ['z1', 'z2', 'z3', 'z4']
for x,y,z in zip(xs,ys,zs):
print(x, y, z)
x1 y1 z1 x2 y2 z2 x3 y3 z3 x4 y3 z4
max(1, 2, 3, 4)
4
xs = ['x1', 'x2', 'x3', 'x4']
ys = ['y1', 'y2', 'y3', 'y3']
zs = ['z1', 'z2', 'z3']
for x,y,z in zip(xs,ys,zs): # whatever is the shortest list that will be taken as reference for deciding the result size
print(x, y, z)
x1 y1 z1 x2 y2 z2 x3 y3 z3
xs = ['x1', 'x2', 'x3', 'x4']
ys = ['y1', 'y2', 'y3', 'y3']
zs = ['z1', 'z2', 'z3', ""]
for x,y,z in zip(xs, ys, zs):
print(x, y, z)
x1 y1 z1 x2 y2 z2 x3 y3 z3 x4 y3
r = reversed(numbers) # this is for one time use only ...iterator ...it is consumable..once consumed it is no use!
for i in r:
print(i)
5 4 3 2 1
for i in r:
print(i)
rl = list(reversed(numbers)) # list function will consume it and return me a list
for i in rl:
print(i, end=",")
5,4,3,2,1,
for i in rl:
print(i, end=",")
5,4,3,2,1,
for i in enumerate(lines): # but using in for loop makes sure that if run the loop again ... it recreates the iterator at start of loop
print(i, end=",")
(0, 'Beautiful is better than ugly'),(1, 'Explicit is better than implicit'),(2, 'simple is better than complex'),(3, 'complex is better than complicated'),(4, 'flat is better than nested'),(5, 'sparse is better than dense'),
r = reversed(numbers) # this iterator
r1 = reversed(r) #
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-146-fd553d1f8c5d> in <module> ----> 1 r1 = reversed(r) # TypeError: 'list_reverseiterator' object is not reversible
len(reversed(numbers))
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-148-918cb389e4c0> in <module> ----> 1 len(reversed(numbers)) TypeError: object of type 'list_reverseiterator' has no len()
rlist = list(reversed(numbers)) # this is a list
len(rlist)
5
x, y = 3, 4
x, y = (3, 4)
x, y = [2, 3]
list(enumerate(lines))
[(0, 'Beautiful is better than ugly'), (1, 'Explicit is better than implicit'), (2, 'simple is better than complex'), (3, 'complex is better than complicated'), (4, 'flat is better than nested'), (5, 'sparse is better than dense')]
i, line = (0, 'Beautiful is better than ugly')
i
0
line
'Beautiful is better than ugly'
i = (0, 'Beautiful is better than ugly')
i
(0, 'Beautiful is better than ugly')
for i in enumerate(lines):
print(i)
(0, 'Beautiful is better than ugly') (1, 'Explicit is better than implicit') (2, 'simple is better than complex') (3, 'complex is better than complicated') (4, 'flat is better than nested') (5, 'sparse is better than dense')
for i, line in enumerate(lines):
print(i)
0 1 2 3 4 5
for i, line in enumerate(lines):
print(i, line)
0 Beautiful is better than ugly 1 Explicit is better than implicit 2 simple is better than complex 3 complex is better than complicated 4 flat is better than nested 5 sparse is better than dense
enumerate # gives tuple
zip # tuple
reversed # give tuple
reversed
numbers.reverse() # this will reverse the list parmanently
numbers
[5, 4, 3, 2, 1]
reversed(numbers) # this will not change original list
<list_reverseiterator at 0x7f8a86c85df0>
a = [1, 2, 3]
b = ['a','b','c']
merged = []
for i, j in zip(a, b):
merged.append(i)
merged.append(j)
merged
[1, 'a', 2, 'b', 3, 'c']
def merge(list1, list2):
merged = []
for item1, item2 in zip(list1, list2):
merged.extend([item1, item2])
return merged
merge(a, b)
[1, 'a', 2, 'b', 3, 'c']
numbers = [34 , 545, 232, 12, 231, 2, 1]
def squares(nums):
"""
[n1, n2, n3...] -> [n1**2, n2**2, n3**2...]
mapped one list to another list by performing some operation
in this function the operation is square
"""
sqr = []
for n in nums:
sqr.append(n*n)
return sqr
def findlens(text_items):
lens = []
for word in text_items:
lens.append(len(word))
return lens
newlist = []
for item in oldlist:
x = do_operation(item) # do_operation is some function
newlist.append(x)
newlist = [do_operation(item) for item in oldlist]
1 1
2 4
3 9
4 16
def square(x):
return x*x
[square(item) for item in numbers]
[1156, 297025, 53824, 144, 53361, 4, 1]
[count_digits(n) for n in numbers]
[2, 3, 3, 2, 3, 1, 1]
[len(line) for line in lines]
[29, 32, 29, 34, 26, 27]
lines
['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']
list(range(5))
[0, 1, 2, 3, 4]
[len(line) for word in lines] # line is some global variable...forgot to make use of word
[27, 27, 27, 27, 27, 27]
[len(word) for word in lines]
[29, 32, 29, 34, 26, 27]
line
'sparse is better than dense'
def evens(numbers):
e = []
for n in numbers:
if n%2==0:
e.append(n)
return e
evens(numbers)
[34, 232, 12, 2]
[n for n in numbers if n%2==0]
[34, 232, 12, 2]
numbers
[34, 545, 232, 12, 231, 2, 1]