Aug 10-14, 2020 Vikrant Patil
These notes are available online at http://notes.pipal.in/2020/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 http://lab1.pipal.in for this training.
make use of notebook module1-day4.ipynb for today's session.
True
False
"hello".startswith("hel")
"hel" in "hello"
"hel" not in "hello"
first = "hel"
second = "hello world!"
first in second
"python" in second
"python" not in second
x = 2
y = 4
x == y
x == 2 #checks if both sides of operator have same values
x, y = 5, 4
x < y # comparison operator
x > y
x >= y
x <= y
x != y # checks if both sides are not equal
2 != 2
2 != 3
if "hel" in "cell": # this ends with :
print("hell") # 4 space indentation shoube given
print("another print statement")
elif "cel" in "hell":
print("cell")
elif "del" in "bell":
print("dell")
else:
print("Finally, if none of above conditons matched!")
if the conditions have only two possiblities and simple satetments, then it is also possible to write if-else statement in one line
cond = True
x = 2 if cond else 3
print(x)
cond = False
x = 2 if cond else 3
print(x)
def print_list(items):
i = 0
while i < len(items):
print(items[i])
i += 1 ## is equivalent i = i +1
print_list([1, 2, 3, 4, 2, 4])
def print_list(items):
i = 0
n = len(items)
print("i =", i, "n =", n, "i< n" , i <n)
while i < n:
print(items[i])
i += 1 ## is equivalent i = i +1​
print("i =", i, "n =", n, "i< n" , i <n)
print_list([12, 1, 2, 3])
4 < 4
And here is classic fibonacci
def print_fib(n):
"""
This function prints fibonacci numbers less than n
"""
curr, prev = 1, 1
while prev < n:
print(prev, end=",")
curr, prev = curr+prev, curr
print_fib(100)
a function that calls itself is called as recursive function.
def foo():
foo() # this is infinite resursion
foo()
def fib(n):
if n == 1 or n == 0:
return 1
else:
return fib(n-1) + fib(n-2)
fib(1)
fib(2)
fib(5)
fib(10)
def print_fib1(n):
i = 0
f = fib(i)
while f < n:
print(f, end=",")
i = i +1
f = fib(i)
print_fib1(100)
fib(15)
fib(30)
#fib(50) # don;t execute this on your notebook, it take very long time
def print_list(items):
i = 0
while i < len(items):
print(items[i])
i += 1 ## is equivalent i = i +1
Using while loop to iterate over items from a list has a problem that , we have to do correct book keeping of index. if that goes wrong, we might
end up in infinite loop or might access out of index. Python gives alternative for this through for loop. Just like we sya in plain
english, for every_student in class. Just similar statement is supported in python as programming construct.
words = ["one", "two", "three", "four", "five", "six"]
for word in words: # it ends with :
print(word, end=",") # next line starts with 4 spaces indentation
for w in words:
print(w, end=",")
for i in word:
print(i, end=",")
for word in words: # it ends with :
print(word, end=",") # next line starts with 4 spaces indentation
for c in "this string":
print(c, end=",")
for t in (0 , 1, 2, 3):
print(t, end=",")
for item in {"x":1, "y":2}:
print(item)
stock = {"name":"IBM",
"open":123.5,
"high":125.3,
"low":122.3,
"close":124.2
}
for paramater in stock:
print(paramater)
for paramater in stock:
print(paramater, stock[paramater])
stock
stock['name']
stock['low']
stock['name']
stock['name'] = "MICROSOFT"
stock
stock['name'] = "IBM"
stock
Problems
product which finds product of all elements from a list. >>> product([3, 2, 4])
24
factorial which computes factorial of a number. >>> factorial(5)
120
findlens which will find length of every string from given list of strings. >>> findlens(["one", "two", "three"])
[3, 3, 5]
find_words_of_len to find words of given length from given list. >>> ["one", "two", "three", "four", "five", "six"]
>>> find_words_of_len(words, 3)
['one', 'two', 'six']
Example function which will find sum of items from a list
def sumlist(numbers):
s = 0
for n in numbers:
s = s + n
return s
sumlist([1, 2, 3, 1, 2])
i++
i = 0
i += 1
# i++ , i-- is not there in python
i = 0
i -= 1
nums = [1, 2, 3, 4, 5]
range(5) # created a sequ of numbers starting from 0 till less than , 4
for i in range(5):
print(i, end=",")
for i in range(1,6):
print(i, end=",")
for i in range(1, 20, 2): ## start, end , step
print(i, end=",")
Solutions 1
def product(numbers):
p = 1
for num in numbers:
p = p *num
return p
product([1,2,4,2])
product(range(1, 6)) # product of 1, 2, 3, 4, 5
def factorial(n):
return product(range(1, n+1))
factorial(5)
factorial(4)
for i in range(5): # end with :, for _ in __: this is structure of for loop
print(i, end=",") # indentation of 4 spaces
i = 0
n = 5
for i < n: # incorrect
print(i, end=",")
i = 0
n = 5
while i < n:
print(i, end=",")
i += 1
def findlens(words):
lens = []
for w in words:
lens.append(len(w))
return lens
findlens(["helllo", "these", "are", "some", "words"])
def fancy_print(words):
for w in words:
print("lenghth of", w, "=", len(w))
fancy_print(["helllo", "these", "are", "some", "words"])
def find_words_of_len(words, l):
filtered = []
for word in words:
if len(word) == l:
filtered.append(word)
return filtered
words = "How do I make words from this sentence?".split()
find_words_of_len(words, 2)
find_words_of_len(words, 4)
More problems
>>> unique([1, 1, 2, 2, 3, 1, 2, 3, 1]
[1, 2, 3]
urls = ['www.abrakadabra.com/dccEcB/EGdd',
'www.abrakadabra.com/gADFeD/bcAF',
'www.abra.com/AGadbb/eagE',
'www.dabra.com/cffdfD/FCAD',
'www.abra.com/GFGaBE/dcfc',
'www.abra.com/gaFegG/Bdaf',
'www.abrakadabra.com/aGabaf/EEfa',
'www.dabra.com/ceEgFD/bGgc',
'www.dabra.com/bDEffC/bcEA']
min2 which finds minumum from given two numbers. Then write another function min3 which finds minimum number from given 3 numbers. Do not make use of built in min function. >>> min2(5, 4.5)
4.5
>>> min3(1, 2, 4)
1
rearrange_max to rearrange digits of an integer to form a maximum number. >>> rearrange_max(1321)
3211
"hel" in "hello"
1 in [1, 2, 3, 4] # check if given item is in list or not
nums = [1, 2, 3, 4,4, 3, 42]
42 in nums
43 in nums
def unique(items): # a function defination has () brackets not [] brackets.
uniq = []
for item in items:
if item not in uniq:
uniq.append(item)
return uniq
unique([1, 1, 2, 3, 1, 3, 4, 1, 3, 2, 2])
nums = [3, 4, 1, 1, 2, 3, 1, 3, 4, 1, 3, 2, 2]
s = set(nums) # set is unique but order is not garanteed!
s
sorted(s)
nums = [42, 1, 43, 42, 1, 3, 3, 2, 2, 1, 1, 1, 5, 5]
unique(nums)
sorted(set(nums), reverse=True)
** rohit's code
def unique(num1):
num1.sort()
x = []
n = 1
for i in num1:
print(n)
if num1[n] != num1[n-1]:
x.append(num1[n]) # there is a bug here! find out! it will skip first number
n += 1
else:
n += 1
return x
len(nums)
nums[14]
nums[13]
unique(nums)
def unique(num1):
num1.sort()
x = []
n = 1
for i in num1[1:]: # drop first item
print(n)
if num1[n-1] != num1[n]:
x.append(num1[n])
n += 1
else:
n += 1
return x
unique(nums)
* * * * * *
- -
- -
- -
- -
- -
def unique(num1):
num1.sort()
x = []
n = 1
for i in range(len(num1)-1): # THis is not using i!
if num1[n-1] != num1[n]: # check with next number if it is same
x.append(num1[n-1])
n += 1
else:
n += 1
return x
unique(nums)
def unique(items): # a function defination has () brackets not [] brackets.
uniq = []
for item in items:
if item not in uniq:
uniq.append(item)
return uniq
not True
urls = ['www.abrakadabra.com/dccEcB/EGdd',
'www.abrakadabra.com/gADFeD/bcAF',
'www.abra.com/AGadbb/eagE',
'www.dabra.com/cffdfD/FCAD',
'www.abra.com/GFGaBE/dcfc',
'www.abra.com/gaFegG/Bdaf',
'www.abrakadabra.com/aGabaf/EEfa',
'www.dabra.com/ceEgFD/bGgc',
'www.dabra.com/bDEffC/bcEA']
urls
def domain(url):
return url.split("/")[0]
def unique_domains(urls):
domains = []
for url in urls:
domains.append(domain(url))
return unique(domains)
unique_domains(urls)
def min2(x, y):
if x < y:
return x
else:
return y
def min3(x, y, z):
return min2(min2(x, y), z)
min3(1, 1, 1)
min3(1, 2, 3)
min3(2, 1, 3)
min3(3, 2, 1)
def my_min(*args):
m = args[0]
for n in args[1:]:
m = min2(m, n)
return m
my_min(3, 4, 5, 6, 1, 4, 3)
str(12344)
d = []
for c in str(12344):
d.append(c)
d
sorted(d, reverse=True)
"".join(sorted(d, reverse=True))
list(12123)
list((1, 2, 3))
list("sladlsad")
list(str(12123))
str(12)
def rearrange_max(number):
digits = list(str(number))
digits_ = sorted(digits, reverse=True)
return int("".join(digits_))
rearrange_max(345454)
import math
math.sqrt(45)
math.pi
import math as m
m.pi
from math import sin
sin(m.pi)
import os
current = os.getcwd() # get me present working directory/folder
#c:\\Program files\\Python3.7
os.listdir(current) # list of files and folders from given folder
os.listdir() # if you don't give any parameter, it will take current folder
os.path.exists("day3.html")
os.path.exists("/home/vikrant/Documents/prayas")
current
os.path.sep # this is platform dependent
#os.path.sep on windows will be `\\`
os.path.sep.join([current, "day3.html"])
os.path.join(current, "day3.html")
day3 = os.path.join(current , "day3.html")
day3
os.path.exists(day3)
file = '/home/vikrant/trainings/2020/arcesium_finop_batch1_module1/module1-day1.ipynb'
os.path.exists(file)
os.path.getsize(day3) # this gives size correctly for files , not for directory
Example
Find biggest file in current directory
files = os.listdir()
max(files, key=os.path.getsize)