Jun 20-24, 2022 Vikrant Patil
All notes are available online at https://notes.pipal.in/2022/arcesium_finop_batch1/
Please accept the invitation that you have received in your email and login to
© Pipal Academy LLP
def foo(): # defination
pass
foo # referrering function as varaible...referring name foo
<function __main__.foo()>
x = 10
def func(variable):
print(variable)
func(x)
10
func(foo)
<function foo at 0x7f9ae5b0e560>
def sumof(x, y, func): # third argument is neither defination of function nor it is calling the function!
return func(x) + func(y)
def square(x):
return x*x
def cube(x):
return x**3
square # this is just referring name square
<function __main__.square(x)>
def add(a, b):
## assumption that user will pass a and b such that they can be added
return a + b
def testfunc(x, y, z): #
#z.split() # if developer assumes that it is a string
#z ** 2 # if he assumes that it is an integer!
#z(x) # there is assumption that z is a function so I am using it!
return z(x) + z(y)
sumof(3, 4, square)
25
sumof(3, 4, cube)
91
max([1, 3, 43, 2, 4, 5, 45]) # by default it assumes that if list has numeric data then order by value
# if it has text data then order by dictionary order
45
1, 2, 3, 4, 5, 43, 45 # first you will order it in ascending manner..then take last item
nums = [232, 34545, 54, 45646456, 434, 454546, -4545454545454]
I am looking for a number with maximum digits!
def digits(num):
strnum = str(abs(num))
print("processing", num, "->", type(strnum), strnum)
return len(strnum)
digits(34343434)
processing 34343434 -> <class 'str'> 34343434
8
max(nums, key=digits)
processing 232 -> <class 'str'> 232 processing 34545 -> <class 'str'> 34545 processing 54 -> <class 'str'> 54 processing 45646456 -> <class 'str'> 45646456 processing 434 -> <class 'str'> 434 processing 454546 -> <class 'str'> 454546 processing -4545454545454 -> <class 'str'> 4545454545454
-4545454545454
"hello"
'hello'
print("hello")
hello
34
34
print("34")
34
def mymax(items, key):
m = items[0]
for item in items:
if key(item) > key(m):
m = item
return m
mymax(nums, key=digits)
processing 232 -> <class 'str'> 232 processing 232 -> <class 'str'> 232 processing 34545 -> <class 'str'> 34545 processing 232 -> <class 'str'> 232 processing 54 -> <class 'str'> 54 processing 34545 -> <class 'str'> 34545 processing 45646456 -> <class 'str'> 45646456 processing 34545 -> <class 'str'> 34545 processing 434 -> <class 'str'> 434 processing 45646456 -> <class 'str'> 45646456 processing 454546 -> <class 'str'> 454546 processing 45646456 -> <class 'str'> 45646456 processing -4545454545454 -> <class 'str'> 4545454545454 processing 45646456 -> <class 'str'> 45646456
-4545454545454
5 > None
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [43], in <cell line: 1>() ----> 1 5 > None TypeError: '>' not supported between instances of 'int' and 'NoneType'
def mymax(items, key=None):
m = items[0]
for item in items:
if key !=None:
if key(item) > key(m):
m = item
else:
if item > m:
m = item
return m
mymax([23,234324, 56, 6, 7,2])
234324
max([5, 5, 3, 2, -6, 3, 5, 3, 2, 1])
5
5 > -6
True
max([5, 5, 3, 2, -6, 3, 5, 3, 2, 1], key=abs)
-6
def key(x):
return abs(x)
square
<function __main__.square(x)>
aliassqr = square
square(5)
25
aliassqr(5)
25
def fib(n):
if n==0 or n ==1:
return n # because there is return here ..function will not go ahead
#else: if there would not have been return in if block then else would be needed
curr, prev = 1, 0
count = 1
while count < n: # this has to be carefully
curr, prev = prev+curr, curr
# tmp = prev
# prev = curr
# curr = curr + tmp
count += 1 # count = count + 1
return curr
fib(10)
55
for i in range(11):
print(fib(i))
0 1 1 2 3 5 8 13 21 34 55
def fibr(n):
if n in [0, 1]:
return n
else:
return fibr(n-1) + fibr(n-2)
fibr(5)
5
for i in range(11):
print(fibr(i))
0 1 1 2 3 5 8 13 21 34 55
def unique(items):
seen = []
for item in items:
if item not in seen:
seen.append(item)
return seen
unique([1, 2, 2, 3, 1, 2, 3, 2, 4, 1])
[1, 2, 3, 4]
["1K","2K","3K"]
['1K', '2K', '3K']
def numeric(value):
return int(value.replace("K","000"))
def numeric(value):
if value.endswith("K"):
return int(value.replace("K","000"))
elif value[-1] == "M":
return int(value.replace("M","000000"))
elif value[-1] == "B":
return int(value.replace("B","000000000"))
else:
return int(value)
def numeric(value):
return int(value.replace("K","000").replace("M", "000000").replace("B", "000000000"))
max(["1K","2K","3K"], key=numeric)
'3K'
words = ["one", "two", "three", "four", "five", "six", "seven"]
max(words, key=len)
'three'
def find_word_with_len(words, length):
words_ = []
for word in words:
if len(word) == length:
words_.append(word)
return words_
find_word_with_len(words, 5)
['three', 'seven']
len(max(words, key=len))
5
find_word_with_len(words, len(max(words, key=len)))
['three', 'seven']
import os ## os is built in module in python ..and we are importing it here
os.getcwd() # this is function inside os module...returns current working
'/home/vikrant/trainings/2022/arcesium_finop_batch1'
"/home/username"
os.path # is submodule inside os module
<module 'posixpath' from '/home/vikrant/usr/local/python3.10/lib/python3.10/posixpath.py'>
filename = "hello.txt"
"/".join(["","dsfdf", "sds","asasd"]) # this code will not work on windows because path sepearator is different on windows
'/dsfdf/sds/asasd'
os.path.join("xys", "sdsd", "sds", "dsfdsf")
'xys/sdsd/sds/dsfdsf'
filepath = os.path.join(os.getcwd(), filename)
print(filepath)
/home/vikrant/trainings/2022/arcesium_finop_batch1/hello.txt
"day1.txt" ## this is relative path ..path with respect to current working directory
'day1.txt'
!ls # this is unix/mac/linux command to list files in current directory
day1.txt index.ipynb module1-day2.html module1-day4.html push day2.txt Makefile module1-day2.ipynb module1-day4.ipynb day3.txt module1-day1.html module1-day3.html module1-day5.html index.html module1-day1.ipynb module1-day3.ipynb module1-day5.ipynb
filepath = "module1-day1.ipynb" # relative path
os.path.getsize(filepath) # gives size in bytes
67735
!ls .. # you can see data.txt is in parent folder
arcesium_finop_batch1 data.txt
os.path.getsize("data.txt") #with relative path this will fail
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) Input In [104], in <cell line: 1>() ----> 1 os.path.getsize("data.txt") File ~/usr/local/python3.10/lib/python3.10/genericpath.py:50, in getsize(filename) 48 def getsize(filename): 49 """Return the size of a file, reported by os.stat().""" ---> 50 return os.stat(filename).st_size FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'
os.path.getsize(os.path.join("..", "data.txt")) # correct relative path
0
absoutepath = os.path.join(os.getcwd(), "module1-day1.ipynb")
absoutepath
'/home/vikrant/trainings/2022/arcesium_finop_batch1/module1-day1.ipynb'
os.path.getsize(absoutepath)
67735
os.path.isfile(absoutepath)
True
cwd = os.getcwd()
parent = os.path.join(cwd, "..")
os.path.getsize(os.path.join(parent, "data.txt"))
0
os.path.join(parent, "data.txt")
'/home/vikrant/trainings/2022/arcesium_finop_batch1/../data.txt'
os.path.abspath(os.path.join(parent, "data.txt"))
'/home/vikrant/trainings/2022/data.txt'
filepath = "/home/vikrant/Downloads/000000001.pdf"
os.path.getsize(filepath)
28370500
os.listdir() # lists all the files in current working directory
['index.html', 'module1-day5.html', 'day2.txt', 'push', 'module1-day5.ipynb', 'index.ipynb', 'module1-day1.html', 'module1-day1.ipynb', 'module1-day2.ipynb', 'module1-day3.html', 'module1-day2.html', 'day3.txt', 'day1.txt', 'module1-day3.ipynb', 'module1-day4.html', 'Makefile', '.ipynb_checkpoints', 'module1-day4.ipynb']
def print_listdir():
for file in os.listdir():
print(file)
print_listdir()
index.html module1-day5.html day2.txt push module1-day5.ipynb index.ipynb module1-day1.html module1-day1.ipynb module1-day2.ipynb module1-day3.html module1-day2.html day3.txt day1.txt module1-day3.ipynb module1-day4.html Makefile .ipynb_checkpoints module1-day4.ipynb
def print_listdir():
for file in os.listdir():
if os.path.isfile(file):
print("f", file) # print f for file
else:
print("d", file) # print d for directory
print_listdir()
f index.html f module1-day5.html f day2.txt f push f module1-day5.ipynb f index.ipynb f module1-day1.html f module1-day1.ipynb f module1-day2.ipynb f module1-day3.html f module1-day2.html f day3.txt f day1.txt f module1-day3.ipynb f module1-day4.html f Makefile d .ipynb_checkpoints f module1-day4.ipynb
def print_listdir():
for file in os.listdir():
if os.path.isfile(file):
print("f", file, os.path.getsize(file)) # print f for file
else:
print("d", file, os.path.getsize(file)) # print d for directory
print_listdir()
f index.html 577223 f module1-day5.html 684080 f day2.txt 1602 f push 0 f module1-day5.ipynb 37517 f index.ipynb 2231 f module1-day1.html 756305 f module1-day1.ipynb 67735 f module1-day2.ipynb 56791 f module1-day3.html 733409 f module1-day2.html 737138 f day3.txt 1424 f day1.txt 1690 f module1-day3.ipynb 57634 f module1-day4.html 825133 f Makefile 627 d .ipynb_checkpoints 4096 f module1-day4.ipynb 87198
def print_listdir():
for file in os.listdir():
if os.path.isfile(file):
print("f", file.ljust(20), os.path.getsize(file)) # print f for file
else:
print("d", file.ljust(20), os.path.getsize(file)) # print d for directory
print_listdir()
f index.html 577223 f module1-day5.html 684080 f day2.txt 1602 f push 0 f module1-day5.ipynb 37517 f index.ipynb 2231 f module1-day1.html 756305 f module1-day1.ipynb 67735 f module1-day2.ipynb 56791 f module1-day3.html 733409 f module1-day2.html 737138 f day3.txt 1424 f day1.txt 1690 f module1-day3.ipynb 57634 f module1-day4.html 825133 f Makefile 627 d .ipynb_checkpoints 4096 f module1-day4.ipynb 87198
"helo".ljust(20)
'helo '
files = os.listdir()
max(files)
'push'
files
['index.html', 'module1-day5.html', 'day2.txt', 'push', 'module1-day5.ipynb', 'index.ipynb', 'module1-day1.html', 'module1-day1.ipynb', 'module1-day2.ipynb', 'module1-day3.html', 'module1-day2.html', 'day3.txt', 'day1.txt', 'module1-day3.ipynb', 'module1-day4.html', 'Makefile', '.ipynb_checkpoints', 'module1-day4.ipynb']
max(files, key=os.path.getsize)
'module1-day4.html'
os.listdir("/home/vikrant/trainings/") # files and folder inside directory /home/vikrant/trainings/
['2018', 'nakul', 'day5.org', '2022', 'hello.py', 'day5.org~', '2020', 'trainingvenv', '2021', '2019', '2017', 'indexdata.xlsx']
def print_listdir(folder=""):
if folder:
files = os.listdir(folder)
else:
files = os.listdir()
for file in files:
path = os.path.join(folder, file)
if os.path.isfile(path):
print("f", file.ljust(20), os.path.getsize(path)) # print f for file
else:
print("d", file.ljust(20), os.path.getsize(path)) # print d for directory
print_listdir()
f index.html 577223 f module1-day5.html 705642 f day2.txt 1602 f push 0 f module1-day5.ipynb 47203 f index.ipynb 2231 f module1-day1.html 756305 f module1-day1.ipynb 67735 f module1-day2.ipynb 56791 f module1-day3.html 733409 f module1-day2.html 737138 f day3.txt 1424 f day1.txt 1690 f module1-day3.ipynb 57634 f module1-day4.html 825133 f Makefile 627 d .ipynb_checkpoints 4096 f module1-day4.ipynb 87198
print_listdir("/home/vikrant/trainings/")
d 2018 4096 d nakul 4096 f day5.org 243 d 2022 4096 f hello.py 0 f day5.org~ 216 d 2020 4096 d trainingvenv 4096 d 2021 4096 d 2019 4096 d 2017 4096 f indexdata.xlsx 6301
"" , [], {}, these result in False in if condition
if []:
pass
else:
print("here")
here
if [1, 2]:
print("hello")
else:
print("here")
hello
if "":
print("hello")
else:
print("here") #<
here
if "":
print("hello")
else:
print("here") #<
here
import math
import random
random.random() # random number between 0, 1
0.5896644221780958
random.choice(words)
'two'
%%file mystas.py
import math
def mean(nums):
return sum(nums)/len(nums)
def std(nums):
m = mean(nums)
s = 0
for n in nums:
s += (n-m)**2
return math.sqrt(s/(len(nums)-1))
Overwriting mystas.py
import mystas
mystas.mean([12, 3, 34, 5, 4, 56])
19.0
mystas.std([12, 3, 34, 5, 4, 56])
21.540659228538015
%%file hello.py
import sys
def say_hello(name):
print("Hello", name.title())
print(sys.argv) # list of arguments that we will pass to our script
say_hello(sys.argv[1])
Writing hello.py
!python hello.py vikrant
['hello.py', 'vikrant'] Hello Vikrant
!python hello.py vikrant patil sadjsa kjhsdkjsa askhdkjsa
['hello.py', 'vikrant', 'patil', 'sadjsa', 'kjhsdkjsa', 'askhdkjsa'] Hello Vikrant
%%file sqaure.py
import sys
print(float(sys.argv[1])**2) # there is no return inside python script ..but we print
Overwriting sqaure.py
!python sqaure.py 5
25.0
!python sqaure.py 56
3136.0
problem
add.py which takes two numbers from commandline and prints addition of thoseinput("Enter a number")
'656'
def sqaure(x):
return x*x # return is a statement ..it is not a function
def sqaure(x):
return(x*x)# this is not needed!
%%file arguments.py
import sys
print(sys.argv) # sys.argv is a list ... you handle it like a like
Overwriting arguments.py
!python arguments.py 1 2 3 4 4 5
['arguments.py', '1', '2', '3', '4', '4', '5']