Aug 17-21, 2020 Vikrant Patil
These notes are available online at http://notes.pipal.in/2020/arcesium_finop_batch2/module1-day4.html
© Pipal Academy LLP
Day 1 | Day 2 | Day 3 | Day 4 | Day 5
We will be using jupyter hub from http://lab2.pipal.in for this training. Use notebook with name module1-day4.ipynb for today's session.
True
False
"hello".endswith("")
"hel" in "helo" # check if "hel" is there in "helo"
x = "cel"
y = "Hello"
x in y
"lo" in y
x not in y
x == y # true if x and y are equal
x != y # True if x and y are not equal
2 in [1, 1, 2, 2, 2, 2, 111]
nums = [1, 2, 1, 2, 3, 1, 2]
3 in nums
4 not in nums
a, b = 10, 20
a < b
a <= b
a >= b
a > b
(a < b) and (x in y)
(a < b) or (x in y)
if "hel" in "cell":
print("Hell") # executed if condition of this block is true
elif "cel" in "hell": # optional
print("Cell") # executed if condition of this block is true
elif "del" in "bell":
print("dell!")
else:
print("ooops!") # if none of the above condition is True.
cond = True
x = 2 if cond else 3 #simple one liner for if else , for very single statements
x
So above one liner if statement if equivalent to fllwing if else statement
if cond:
x = 2
else:
x = 3
cond = False
x = 2 if cond else 3
x
write a function to check if given number is even
def even1(n):
if n%2 == 0:
return True
else:
return False
def even2(n):
return True if n%2==0 else False
even1(4)
even1(3)
even2(4)
even2(5)
n = 10
n%2 == 0
def even(n):
return n%2 == 0
even(4)
even(5)
Question: can we use lambda expression to write this simple function
even = lambda n : n%2==0
even(5)
even(4)
sumofsquares = lambda x, y: x*x + y*y
sumofsquares(2, 3)
while cond: # this clode block will be executed till the cond is True
statemente1
statemente2
.
.
.
def print_list(items):
i = 0
l = len(items)
while i < l:
print(items[i])
i += 1 ## this means increament i by one i = i + 1
numbers = [ 1, 2, 3, 4, 5,6, 7]
print_list(numbers)
def print_list(items):
i = 0
l = len(items)
while i < l:
print(items[i], end=",")
i += 1 ## this means increament i by one i = i + 1
print_list(numbers)
here is classic exmple of fibonacci numbers
def print_fib(n):
"""
Print fibonacci numbers less than
"""
curr, prev = 1, 1
while prev < n:
print(prev, end=",")
curr, prev = prev + curr, curr
print_fib(100)
print_fib(500)
numbers
numbers[0]
numbers[1]
numbers[7]
numbers[6]
The problem with using while loop to access lists/tuples is that we have keep track of index. if something goes wrong in computing index, then we will have bugs the program which will be difficult to debug. Just like in english one would say for every_student in class to iterate over all students from class, same way we can iterate over items in a collection in python
words = ["one", "two", "three", "four", "five"]
for word in words:
print(word, end=",")
xy = {"x":1, "y":2}
xy
for item in xy:
print(item)
for item in xy:
print(item, xy[item])
for char in "This is a string with some chars in it":
print(char, end=",")
classroom = ["asit", "hasneet", "aakash", "deepak", "rutul", "saurav", "shantanu"]
for student in classroom:
print("Hello" , student.capitalize())
nums = [0, 1, 2, 3, 4,5]
for i in range(5):
print(i, end=",")
for i in range(1, 6):
print(i, end=",")
for i in range(1, 21, 2):
print(i, end=",")
range(5)
list(range(5))
for i in range(4):
print(i, end=",")
def mysum(nums):
sum_ = 0
for n in nums:
sum_ += n
return sum_
mysum([1, 2, 3, 4, 4])
mysum([1, 1, 1, 1])
def squares(nums):
sqrs = []
for n in nums:
sqrs.append(n*n) # appending square of each item
return sqrs
squares(range(5))
def mysum(nums):
print("begin with nums = ", nums)
sum_ = 0
print("begining for loop")
for n in nums:
print("n =", n)
print("sum_ =", sum_)
sum_ += n
print("returning ", sum_)
return sum_
mysum([1,2,3,4])
problems
product which find product of all elements from a numeric list.
>>> product([2, 3, 4])
24
factorial which mankes use of your previous function product to compute factorial of a number. Factorial of n in multiplication of n, n-1, n-2 ....3, 2, 1.
>>> factorial(5)
120
findlens whch finds length of every string in list of of strings.
>>> findlens(["one", "two","three"])
[3, 3, 5]
person = {}
person['name'] = "vikrant"
keys = ["key1", "key2", "key3"]
values = ["v1", "v2", "v3"]
d = {}
n = len(keys)
for i in range(n):
d[keys[i]] = values[i]
d
keys = ["key1", "key2", "key3"]
values = ["v1", "v2", "v3"]
d = {}
n = len(keys)
for k, v in zip(keys, values):
d[k] = v
for key in d:
print(key)
for key in d:
print(key, d[key])
for k,v in d.items():
print(k, v)
def product(numbers): # saurav
i = 1
for h in numbers:
i = i*h
return i ## this is the bug!
def product(numbers): # saurav
p = 1
for num in numbers:
p = p*num
return p ## <<<<
def findlens(x):
for i in x:
return len(i) #<<==== this will return in first item iteself
return
findlens(["one", "two"])
def findlens(x):
lens = []
for i in x:
lens.append(len(i))
return lens
findlens("some statement with some words".split())
def add(a, b):
s = a+b
return
add(3, 4)
def add(a, b):
return a+b
add(4, 5)
def findlens(words):
lens = []
for word in words:
l = len(word)
lens.append(l)
return lens
some statement with some words
4 9 4 4 5
here is another statement
4 2 7 9
[]
[4] here
[4, 2] is
[4, 2, 7] another
[4, 2, 7, 9] statement
nums = [1, 2, 3]
nums.append(0)
nums
nums.insert(4, -1)
nums
nums.insert(-1, 10)
nums
def findlens_(words):
lens = []
for word in words:
l = len(word)
lens.insert(0, l) ##
lens.reverse()
return lens
findlens_(["one", "two", "three", "six"])
def squares(nums):
squrs = []
for n in nums:
squrs.append(n*n)
return squrs
squares([1, 3, 4, 5])
product([1, 2, 4])
product(range(1, 6))
def factorial(n):
return product(range(1, n+1))
print_list(range(5))
print_list(range(1, 5))
print_list(range(1, 6))
problems
find_words_of_len to find words of given length from given list of words
>>> words = ["one", "two", "three", "five", "six"]
>>> find_word_of_len(words, 3)
["one", "two", "six"]
Medium level problems
unique which will remove duplicates from a list keeping the order same.
>>> unique([1, 1, 2, 3, 1, 2, 3, 2, 4])
[1, 2, 3, 4]
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 minimum from given two numbers. Also write a function min3 which finds minimum form three numbers. Do not make use of builtin min function.def square(x):
return x*x
def sumofsquares(x, y):
return square(x) + square(y)
words= ["one", "two", "three", "five", "six"]
def find_words_of_len(words):
empty_list = []
for word in words:
if len(word)==3: # 3 is hardcoed! instead use parameter
empty_list.append(word)
return empty_list ## the return would return after 1st iteration of for loop
words= ["one", "two", "three", "five", "six"]
def find_words_of_len(words, n):
empty_list = []
for word in words:
if len(word)==n:
empty_list.append(word)
return empty_list
find_words_of_len(words, 3)
find_words_of_len(words, 4)
find_words_of_len(words, 2)
Generic list of when to use what bracket!
x = 2 if cond else 3
print(2) if cond else print(3)
def unique(list1): # saurav
list2 = []
for i in list1:
list2.append(i) if i not in list2 else print("")
return list2
unique([1, 2, 3, 4, 4])
def unique(words):
seen = []
for word in words:
if word not in seen:
seen.append(word)
return seen
unique([1, 1, 1, 2, 3,1, 4, 2, 4, 1, 5])
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']
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
min2(5, 6)
def min3(x, y, z):
return min2(min2(x, y), z)
print("x", "y")
print("x","y",1,2)
def min_(*args): # * is what makes it variable numbers of arguments
m = args[0]
for n in args[1:]: # drop first
m = min2(m, n)
return m
min_(1, 2, 3, 4, -1)
min_(-1)
min_(2, 3, 4, 1)
max([1, 2, 3])
max = 5
max
max([12, 3, 4])
max
del max
max([12, 4, 5])
rearrange_max to rearrange digits of an integer so as to make maximum integer from it
```rearrange_max(3524) 5432