Sep 20-24, 2021 Vikrant Patil
These notes are available online at https://notes.pipal.in/2021/arcesium_finop_batch2/
© Pipal Academy LLP
Day 1 | Day 2 | Day 3 | Day 4 | Day 5
We will be using jupyter hub from https://lab2.pipal.in for this training.
login to hub and create a notebook with name module1-day4
"text".isalpha()
True
"hel" in "hello"
True
text = "Hello this is some text"
"this" in text
True
"that" in text
False
x = "is"
x in text
True
1 in [1, 1, 1, 12, 3]
True
1 in [0, 0, 3, 4]
False
1 in [(1, 0, 1),(1, 0),(0, 0)]
False
1 in (1, 0, 1)
True
1 in [[1, 1], [2, 1]]
False
[1, 1] in [[1,1], [2,1]]
True
person = {"name":"Vikrant", "language":"Marathi", "country":"India"}
person
{'name': 'Vikrant', 'language': 'Marathi', 'country': 'India'}
"name" in person # you can check if the left hand side is part of keys
True
"Vikrant" in person
False
"Vikrant" in person.values() # method from dictionary
True
"name" not in text
True
x, y = 5, 6
x == y
False
"text" == "text"
True
x < y
True
y <= y
True
x != y
True
cell = "cell"
hell = "hell"
bell = "bell"
if "hel" in cell: # the if line has to end with :
print("We are in hell!") # next line/lines should be indented by 4 spaces
elif "cel" in hell: # optional
print("We are in a cell!")
elif "del" in bell: # optional but you can start with this
print("Delete!")
else: # optional but you can start with this
print("Finally ..we are out from if else...")
Finally ..we are out from if else...
x = 2 if "hel" in hell else 3 # if very simple conditions and simple assignemt ..this one liner can be used
x
2
numbers = [45, 231, 11, 44, 1, 678, 43]
numbers[0]
45
i = 4
numbers[i]
1
i = 0
n = len(numbers)
while i < n:
print(numbers[i])
i = i + 1
# i += 1
45 231 11 44 1 678 43
def print_list(items):
i = 0
size = len(items)
while i < size: # source of bug or infinite loop!
print(items[i], end=",")
i += 1 # if you forget to change i ..
words = "if very simple conditions and simple assignemt ..this one liner can be used".split()
words
['if', 'very', 'simple', 'conditions', 'and', 'simple', 'assignemt', '..this', 'one', 'liner', 'can', 'be', 'used']
print_list(words)
if,very,simple,conditions,and,simple,assignemt,..this,one,liner,can,be,used,
print_list(numbers)
45,231,11,44,1,678,43,
print_list("some text data")
s,o,m,e, ,t,e,x,t, ,d,a,t,a,
print_list((1,2,4,3,4,54,4))
1,2,4,3,4,54,4,
### fibn = fibn-1 + fibn-2
def print_fib(n):
"""
print fibonacci numbers less than n
"""
curr, prev = 1, 1
while prev < n:
print(prev, end=",")
curr, prev = curr + prev, curr
print_fib(100)
1,1,2,3,5,8,13,21,34,55,89,
def print_list1(items):
i = 0
size = len(items)
while i < size: # source of bug or infinite loop!
print(items[i], end=",")
i += 1 # this statement is outside loop! this will result in infinite loop!
words
['if', 'very', 'simple', 'conditions', 'and', 'simple', 'assignemt', '..this', 'one', 'liner', 'can', 'be', 'used']
students = ["Akash", "Aksh", "Akanksha", "Arjun"]
for word in words:
print(word, end=",")
if,very,simple,conditions,and,simple,assignemt,..this,one,liner,can,be,used,
for char in "text is fun":
print(char, end=",")
t,e,x,t, ,i,s, ,f,u,n,
for w in words:
print(w, end=",")
if,very,simple,conditions,and,simple,assignemt,..this,one,liner,can,be,used,
for student in students:
print(student.upper(), end=" ")
AKASH AKSH AKANKSHA ARJUN
for s in students:
print(s)
Akash Aksh Akanksha Arjun
for loop can be applied to any coolection i.e. list, tuple, string, dictionary , set
point = (3, 4, 5)
for coordinate in point:
print(coordinate)
3 4 5
text = "hello this is text"
for c in text:
print(c, end="-")
h-e-l-l-o- -t-h-i-s- -i-s- -t-e-x-t-
person
{'name': 'Vikrant', 'language': 'Marathi', 'country': 'India'}
for key in person:
print(key)
name language country
for key in person:
print(key, person[key])
name Vikrant language Marathi country India
def mysum(numbers):
s = 0
for n in numbers:
s += n
return s
mysum(numbers)
1053
def mysum_(numbers):
s = 0
for n in numbers:
s += n
return s # this will return after first iteration
numbers
[45, 231, 11, 44, 1, 678, 43]
mysum_(numbers)
45
def uppercase(text_items):
"""converts every text item from text_items to upper case
and returns a new list
"""
caps_data = [] # start with empty list
for text in text_items:
caps_data.append(text.upper())
return caps_data
uppercase(words)
['IF', 'VERY', 'SIMPLE', 'CONDITIONS', 'AND', 'SIMPLE', 'ASSIGNEMT', '..THIS', 'ONE', 'LINER', 'CAN', 'BE', 'USED']
lines = """first line
second line
third line
fourth line
fifth line
""".split("\n")
lines
['first line', 'second line', 'third line', 'fourth line', 'fifth line', '']
uppercase(lines)
['FIRST LINE', 'SECOND LINE', 'THIRD LINE', 'FOURTH LINE', 'FIFTH LINE', '']
problem
product which finds product of all items form a list.
>>> product([3, 2, 4])
24
factorial to find factorial of a number. can you make use of range and product that we wrote in problem above
>>> factorial(5)
120
findlens which finds length of every item from given collection
>>> findlens(["one", "two", "three"])
[3, 3, 5]
find_words_of_len to find words of given length from given collection.
>>> words = ["one", "two", "three"]
>>> find_words_of_len(words, 3)
["one", "two"]
for i in range(5): # gives me numbers from 0 to 4
print(i)
0 1 2 3 4
for i in range(1, 11): #gives integers from 1 to 10
print(i, end=" ")
1 2 3 4 5 6 7 8 9 10
for i in range(1, 20, 3): # gives integers starting from 1 , less than 20 and every 3rd item
print(i, end=",")
1,4,7,10,13,16,19,
for word in words: # there is no need of any indexing!
print(word)
if very simple conditions and simple assignemt ..this one liner can be used
When to use for loop
When to use while loop
unique which will remove duplicate entries from a list
>>> unique([1, 1, 2, 3, 1, 2, 3, 4, 3])
[1, 2, 3, 4]
urls = ["www.abrakadabra.com/dsjhj/sdhhHHG",
"www.abrakadabra.com/jkj/dfkdjgkj",
"www.abra.com/lkji/uywe",
"www.dabra.com/oiuytw/feowu",
"www.abrakadabra.com/Asldk/kjhkKJH",
"www.abra.com/jhkjh/iuroiwue",
"www.dabra.com/yYIU/UYUY",
"www.abra.com/JHKJH",
"www.dabra.com/HJHJH,
"www.abra.com/ABCD"]
min2 which find minium from given two numbers. Also write a function min3 which find minimum from 3 numbers. DO not make use of builf min function.len
<function len(obj, /)>
len(words)
13
len = []
len
[]
len(words)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-74-a5004d9b095c> in <module> ----> 1 len(words) TypeError: 'list' object is not callable
del len
len(words)
13
def find_words_of_len(itemlist, l):
lens = findlens(itemslist)
i = 0
for length in lens:
if lenght == l:
print(itemlist[i])
i += 1
def find_words_of_len(itemlist, l):
for item in itemlist:
if len(item) == l:
print(item)
def find_words_of_len(itemlist, l):
words = []
for item in itemlist:
if len(item) == l:
words.append(item)
def product(numbers):
"""find product of all numbers from a collection!
"""
p = 1
for n in numbers:
p = p*n
return p
product(numbers)
146679021720
numbers
[45, 231, 11, 44, 1, 678, 43]
def factorial(n):
"""n! = n*(n-1)*(n-2)*(n-3).....1
range(1, n+1) -> 1, 2, 3, 4, 5...
"""
return product(range(1, n+1))
factorial(5)
120
factorial(10)
3628800
def findlens(items):
lengths = []
for item in items:
lengths.append(len(item))
return lengths
findlens(words)
[2, 4, 6, 10, 3, 6, 9, 6, 3, 5, 3, 2, 4]
words
['if', 'very', 'simple', 'conditions', 'and', 'simple', 'assignemt', '..this', 'one', 'liner', 'can', 'be', 'used']
def find_words_of_len(items, l):
words_of_len = []
for item in items:
if len(item)==l:
words_of_len.append(item)
return words_of_len
find_words_of_len(words, 3)
['and', 'one', 'can']
find_words_of_len(words, 5)
['liner']
4 in [1, 2, 3]
False
4 in [1, 2, 3, 4]
True
def unique(items):
seen = []
for item in items:
if item not in seen:
seen.append(item)
return seen
unique([1, 1, 1, 2, 2, 3, 3, 4, 1, 2, 1])
[1, 2, 3, 4]
1, 1, 1, 2, 2, 3, 3, 4, 1, 2, 1
^
unique =>
def unique(inputlist):
mycollection = []
for item inputlist:
if item not in mycollction:
mycollection.append(item)
urls = ["www.abrakadabra.com/dsjhj/sdhhHHG",
"www.abrakadabra.com/jkj/dfkdjgkj",
"www.abra.com/lkji/uywe",
"www.dabra.com/oiuytw/feowu",
"www.abrakadabra.com/Asldk/kjhkKJH",
"www.abra.com/jhkjh/iuroiwue",
"www.dabra.com/yYIU/UYUY",
"www.abra.com/JHKJH",
"www.dabra.com/HJHJH",
"www.abra.com/ABCD"]
urls[0].split("/")[0]
'www.abrakadabra.com'
def domain(url):
return url.split("/")[0]
def all_domains(urls):
domains = []
for url in urls:
domains.append(domain(url))
return domains
def unique_domains(urls):
domains = all_domains(urls)
return unique(domains)
unique_domains(urls)
['www.abrakadabra.com', 'www.abra.com', 'www.dabra.com']
x = 2==3
x
False
3 4 1 6 7 2 4 2 1 8 -3 .....
m next number
3 -
3 4
1 1
1 6
...
-3
def min2(x, y):
if x < y:
return x
else:
return y
def min3(x, y, z):
if x < y and x < z:
return x
elif y < x and y < z:
return y
else:
return z
def min3(x, y, z):
return min2(min2(x, y), z)
def min3(x, y, z):
m = min2(x, y)
return min2(m , z)
"madam"
'madam'
"12321"
'12321'
word = "hello"
#word == reverse_word(word)
word[:2] # take first 2 items
'he'
word[2:] # drom first two items
'llo'
word[::] # copy
'hello'
word[::-1] # reverse
'olleh'
def is_palindrom(item):
stritem = str(item)
return stritem == stritem[::-1]
is_palindrom("madam")
True
is_palindrom(121)
True
is_palindrom(123)
False
import os # will import built in os module
os.getcwd() # this function returns current working directory/folder
'/home/vikrant/trainings/2021/arcesium_finop_batch2'
os.listdir() # this function retuns listing from current directory/folder
['index.html', 'push', 'Untitled.html', 'index.ipynb', 'module1-day1.html', 'module1-day1.ipynb', 'module1-day2.ipynb', 'module1-day3.html', 'module1-day2.html', 'module1-day3.ipynb', 'module1-day4.html', 'Makefile', '.ipynb_checkpoints', 'module1-day4.ipynb']
os.listdir("/etc/ssh/") # if you pass path here , it will give listing from that directory
['ssh_host_ed25519_key', 'ssh_host_rsa_key.pub', 'ssh_host_ecdsa_key.pub', 'ssh_config.d', 'ssh_host_ecdsa_key', 'sshd_config', 'ssh_host_ed25519_key.pub', 'ssh_host_rsa_key', 'ssh_import_id', 'moduli', 'ssh_config', 'sshd_config.d']
os.path # this submodule inside os
<module 'posixpath' from '/home/vikrant/anaconda3/lib/python3.8/posixpath.py'>
os.path.isfile("index.html")
True
os.path.isfile(".ipynb_checkpoints")
False
os.path.isdir(".ipynb_checkpoints")
True
os.path.isdir("module1-day1.ipynb")
False
os.path.isfile("module1-day1.ipynb") # relative path, with respect current directory
True
os.path.isfile("/etc/ssh/") # this called as absolute path c:\\Program File\\Python\\
False
if you want to do any of these checks on files and folders which are not in current directory, then you will have to give absolute path (which means it should start from the drive)
os.path.exists("imaginary.txt")
False
os.path.isfile("imaginary.txt") # i might think that this is probabality a directory
False
listings = os.listdir() #this does not go recursively
for file in listings:
print(os.path.exists(file))
True True True True True True True True True True True True True True
os.path.getsize("module1-day4.ipynb") # gives size of file in bytes
48792
import os
from os import getcwd # this will import the function
getcwd()
'/home/vikrant/trainings/2021/arcesium_finop_batch2'
import os as operatingsystem
import math as m
m.sin(6.3)
0.016813900484349713
os.path.getsize("profile")
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-158-c279218e8543> in <module> ----> 1 os.path.getsize("profile") ~/anaconda3/lib/python3.8/genericpath.py 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 51 52 FileNotFoundError: [Errno 2] No such file or directory: 'profile'