Python Virtual Training For Arcesium - Module I - Day 4

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.

Introduction to programming constructs

Conditions

In [1]:
True
Out[1]:
True
In [2]:
False
Out[2]:
False
In [3]:
"hello".endswith("")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-7d42924490f6> in <module>
----> 1 "hello".endswith()

TypeError: endswith() takes at least 1 argument (0 given)
In [5]:
"hel" in "helo" # check if "hel" is there in "helo"
Out[5]:
True
In [6]:
x = "cel"
In [7]:
y = "Hello"
In [8]:
x in y
Out[8]:
False
In [9]:
"lo" in y
Out[9]:
True
In [11]:
x not in y
Out[11]:
True
In [14]:
x == y # true if x and y are equal
Out[14]:
False
In [15]:
x != y # True if x and y are not equal
Out[15]:
True
In [16]:
2 in [1, 1, 2, 2, 2, 2, 111]
Out[16]:
True
In [17]:
nums = [1, 2, 1, 2, 3, 1, 2]
In [18]:
3 in nums
Out[18]:
True
In [19]:
4 not in nums
Out[19]:
True
In [20]:
a, b = 10, 20
In [21]:
a < b
Out[21]:
True
In [22]:
a <= b
Out[22]:
True
In [23]:
a >= b
Out[23]:
False
In [24]:
a > b
Out[24]:
False
In [25]:
(a < b) and (x in y)
Out[25]:
False
In [26]:
(a < b) or (x in y)
Out[26]:
True

if elif else blocks

In [27]:
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.
ooops!
In [28]:
cond = True
In [35]:
x = 2 if cond else 3   #simple one liner for if else , for very single statements
In [30]:
x
Out[30]:
2

So above one liner if statement if equivalent to fllwing if else statement

In [36]:
if cond: 
    x = 2
else:
    x = 3
In [31]:
cond = False
In [32]:
x = 2 if cond else 3
In [33]:
x
Out[33]:
3

write a function to check if given number is even

In [39]:
def even1(n):
    if n%2 == 0:
        return True
    else:
        return False
In [40]:
def even2(n):
    return True if n%2==0 else False
In [41]:
even1(4)
Out[41]:
True
In [42]:
even1(3)
Out[42]:
False
In [43]:
even2(4)
Out[43]:
True
In [44]:
even2(5)
Out[44]:
False
In [45]:
n = 10
In [46]:
n%2 == 0
Out[46]:
True
In [48]:
def even(n):
    return n%2 == 0
In [49]:
even(4)
Out[49]:
True
In [50]:
even(5)
Out[50]:
False

Question: can we use lambda expression to write this simple function

In [51]:
even = lambda n : n%2==0
In [52]:
even(5)
Out[52]:
False
In [53]:
even(4)
Out[53]:
True
In [54]:
sumofsquares = lambda x, y: x*x + y*y
In [55]:
sumofsquares(2, 3)
Out[55]:
13

While loop

while cond: # this clode block will be executed till the cond is True
   statemente1
   statemente2
   .
   .
   .
In [56]:
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
        
In [58]:
numbers = [ 1, 2, 3, 4, 5,6, 7]
print_list(numbers)
1
2
3
4
5
6
7
In [59]:
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
        
In [60]:
print_list(numbers)
1,2,3,4,5,6,7,

here is classic exmple of fibonacci numbers

In [61]:
def print_fib(n):
    """
    Print fibonacci numbers less than
    """
    
    curr, prev = 1, 1
    
    while prev < n:
        print(prev, end=",")
        curr, prev  = prev + curr, curr
In [62]:
print_fib(100)
1,1,2,3,5,8,13,21,34,55,89,
In [63]:
print_fib(500)
1,1,2,3,5,8,13,21,34,55,89,144,233,377,

For loop

In [64]:
numbers
Out[64]:
[1, 2, 3, 4, 5, 6, 7]
In [65]:
numbers[0]
Out[65]:
1
In [66]:
numbers[1]
Out[66]:
2
In [67]:
numbers[7]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-67-99ddd0b0f865> in <module>
----> 1 numbers[7]

IndexError: list index out of range
In [68]:
numbers[6]
Out[68]:
7

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

In [69]:
words = ["one", "two", "three", "four", "five"]
In [70]:
for word in words:
    print(word, end=",")
one,two,three,four,five,
In [71]:
xy = {"x":1, "y":2}
In [72]:
xy
Out[72]:
{'x': 1, 'y': 2}
In [73]:
for item in xy:
    print(item)
x
y
In [74]:
for item in xy:
    print(item, xy[item])
x 1
y 2
In [75]:
for char in "This is a string with some chars in it":
    print(char, end=",")
T,h,i,s, ,i,s, ,a, ,s,t,r,i,n,g, ,w,i,t,h, ,s,o,m,e, ,c,h,a,r,s, ,i,n, ,i,t,
In [76]:
classroom = ["asit", "hasneet", "aakash", "deepak", "rutul", "saurav", "shantanu"]
In [78]:
for student in classroom:
    print("Hello" , student.capitalize())
Hello Asit
Hello Hasneet
Hello Aakash
Hello Deepak
Hello Rutul
Hello Saurav
Hello Shantanu
In [79]:
nums = [0, 1, 2, 3, 4,5]
In [80]:
for i in range(5):
    print(i, end=",")
0,1,2,3,4,
In [81]:
for i in range(1, 6):
    print(i, end=",")
1,2,3,4,5,
In [82]:
for i in range(1, 21, 2):
    print(i, end=",")
1,3,5,7,9,11,13,15,17,19,
In [83]:
range(5)
Out[83]:
range(0, 5)
In [84]:
list(range(5))
Out[84]:
[0, 1, 2, 3, 4]
In [85]:
for i in range(4):
    print(i, end=",")
0,1,2,3,
In [86]:
def mysum(nums):
    sum_ = 0
    for n in nums:
        sum_ += n
    return sum_
In [87]:
mysum([1, 2, 3, 4, 4])
Out[87]:
14
In [88]:
mysum([1, 1, 1, 1])
Out[88]:
4
In [93]:
def squares(nums):
    sqrs = []
    
    for n in nums:
        sqrs.append(n*n) # appending square of each item
        
    return sqrs
In [94]:
squares(range(5))
Out[94]:
[0, 1, 4, 9, 16]
In [95]:
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_
In [92]:
mysum([1,2,3,4])
begin with nums =  [1, 2, 3, 4]
begining for loop
n = 1
sum_ = 0
n = 2
sum_ = 1
n = 3
sum_ = 3
n = 4
sum_ = 6
returning  10
Out[92]:
10

problems

  1. Write a function product which find product of all elements from a numeric list.
     >>> product([2, 3, 4])
     24
  2. Write a function 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
  3. Write a function findlens whch finds length of every string in list of of strings.
     >>> findlens(["one", "two","three"])
     [3, 3, 5]
In [96]:
person = {}
In [97]:
person['name'] = "vikrant"
In [98]:
keys = ["key1", "key2", "key3"]
values = ["v1", "v2", "v3"]
d = {}

n = len(keys)
for i in range(n):
    d[keys[i]] = values[i]
In [99]:
d
Out[99]:
{'key1': 'v1', 'key2': 'v2', 'key3': 'v3'}
In [101]:
keys = ["key1", "key2", "key3"]
values = ["v1", "v2", "v3"]
d = {}

n = len(keys)
for k, v in zip(keys, values):
    d[k] = v
In [102]:
for key in d:
    print(key)
key1
key2
key3
In [103]:
for key in d:
    print(key, d[key])
key1 v1
key2 v2
key3 v3
In [104]:
for k,v in d.items():
    print(k, v)
key1 v1
key2 v2
key3 v3
In [105]:
def product(numbers): # saurav
     
    i = 1
    
    for h in numbers:
        i = i*h
        return i ## this is the bug!
    
In [106]:
def product(numbers): # saurav
     
    p = 1
    
    for num in numbers:
        p = p*num
    
    return p ## <<<<
    
In [109]:
def findlens(x):
    for i in x:
        return len(i) #<<==== this will return in first item iteself
    return
In [108]:
findlens(["one", "two"])
Out[108]:
3
In [110]:
def findlens(x):
    lens = []
    for i in x:
        lens.append(len(i))  
    return lens
In [111]:
findlens("some statement with some words".split())
Out[111]:
[4, 9, 4, 4, 5]
In [112]:
def add(a, b):
    s = a+b
    return
In [113]:
add(3, 4)
In [114]:
def add(a, b):
    return a+b
In [115]:
add(4, 5)
Out[115]:
9
In [116]:
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
In [117]:
nums = [1, 2, 3]
In [118]:
nums.append(0)
In [119]:
nums
Out[119]:
[1, 2, 3, 0]
In [120]:
nums.insert(4, -1)
In [121]:
nums
Out[121]:
[1, 2, 3, 0, -1]
In [122]:
nums.insert(-1, 10)
In [123]:
nums
Out[123]:
[1, 2, 3, 0, 10, -1]
In [126]:
def findlens_(words):
    lens = []
    for word in words:
        l = len(word)
        lens.insert(0, l)  ## 
    lens.reverse()
    return lens
In [127]:
findlens_(["one", "two", "three", "six"])
Out[127]:
[3, 3, 5, 3]
In [128]:
def squares(nums):
    squrs = []
    for n in nums:
        squrs.append(n*n)
    
    return squrs
In [129]:
squares([1, 3, 4, 5])
Out[129]:
[1, 9, 16, 25]
In [130]:
product([1, 2, 4])
Out[130]:
8
In [131]:
product(range(1, 6))
Out[131]:
120
In [132]:
def factorial(n):
    return product(range(1, n+1))
In [134]:
print_list(range(5))
0,1,2,3,4,
In [135]:
print_list(range(1, 5))
1,2,3,4,
In [136]:
print_list(range(1, 6))
1,2,3,4,5,

problems

  1. Write a function 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

  1. Write a function 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]
  2. List of urls is given. Some urls are from same domains, some are from different. Find unique domain names used in urls
    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']
  3. write function 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.
In [137]:
def square(x):
    return x*x

def sumofsquares(x, y):
    return square(x) + square(y)
In [143]:
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
In [144]:
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
In [145]:
find_words_of_len(words, 3)
Out[145]:
['one', 'two', 'six']
In [146]:
find_words_of_len(words, 4)
Out[146]:
['five']
In [147]:
find_words_of_len(words, 2)
Out[147]:
[]

Generic list of when to use what bracket!

  • () -> calling a function or creating a tuple or changing priority of mathemactical expression.
  • [] -> for accessing elements form list, dictionary , tuple or string
  • {} -> for creating dictionary
  • productOfList -> classes/methods use camel case naming style
  • product_of_list -> style preferred for simple functions and varaibles
In [148]:
x = 2 if cond else 3
In [150]:
print(2) if cond else print(3)
3
In [152]:
def unique(list1): # saurav
    
    list2 = []
    for i in list1:
        list2.append(i) if i not in list2 else print("")
    
    return list2
In [153]:
unique([1, 2, 3, 4, 4])

Out[153]:
[1, 2, 3, 4]
In [154]:
def unique(words):
    seen = []
    for word in words:
        if word not in seen:
            seen.append(word)
            
    return seen
In [155]:
unique([1, 1, 1, 2, 3,1, 4, 2, 4, 1, 5])
Out[155]:
[1, 2, 3, 4, 5]
In [156]:
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']
In [157]:
def domain(url):
    return url.split("/")[0]

def unique_domains(urls):
    domains = []
    for url in urls:
        domains.append(domain(url))
        
    return unique(domains)
In [158]:
unique_domains(urls)
Out[158]:
['www.abrakadabra.com', 'www.abra.com', 'www.dabra.com']
In [159]:
def min2(x, y):
    if x < y:
        return x
    else:
        return y
In [160]:
min2(5, 6)
Out[160]:
5
In [161]:
def min3(x, y, z):
    return min2(min2(x, y), z)
In [162]:
print("x", "y")
x y
In [163]:
print("x","y",1,2)
x y 1 2
In [175]:
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
In [165]:
min_(1, 2, 3, 4, -1)
Out[165]:
-1
In [166]:
min_(-1)
Out[166]:
-1
In [167]:
min_(2, 3, 4, 1)
Out[167]:
1
In [168]:
max([1, 2, 3])
Out[168]:
3
In [169]:
max = 5
In [170]:
max
Out[170]:
5
In [171]:
max([12, 3, 4])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-171-5b22428a1ffa> in <module>
----> 1 max([12, 3, 4])

TypeError: 'int' object is not callable
In [172]:
max
Out[172]:
5
In [173]:
del max
In [174]:
max([12, 4, 5])
Out[174]:
12

Homework

  1. Write a function rearrange_max to rearrange digits of an integer so as to make maximum integer from it ```

    rearrange_max(3524) 5432

In [ ]: