Python Virtual Training For Arcesium - Module I - Day 4

Dec 07-11, 2020 Vikrant Patil

These notes are available online at http://notes.pipal.in/2020/arcesium_finop_batch3/module1-day4.html

© Pipal Academy LLP

Day 1 | Day 2 | Day 3 | Day 4 | Day 5

We will be using jupyter hub from http://lab.pipal.in for this training. Create a notebook with name module1-day4.ipynb for today's session

Problems

  1. Net asset value, or NAV, is equal to a fund's or company's total assets less its liabilities. NAV is usually computed per share value for MF,ETF or closed ended fund. Write a function to compute NAV. Compute NAV for total assets of 25,00,00,000, liabilities of 30,00,000 and 1000 shares.
         >>> NAV(assets,liabilities,shares)
  2. In financial terms a negative balance is represented with round barackets around the number instead of - sign. Write a function numeric_value which returns actual numeric value. For example a value "(1234)" should get -1234 as numeric value. while "1234.5" will still get value as 1234.5.:
     >>> numeric_value("(35.5)")
     -35.5
     >>> numeric_value("32.5")
     32.5
  3. Compount interest is calculated using formula P (1 + r/n)nt For this formula, P is the principal amount, r is the rate of interest per annum, n denotes the number of times in a year the interest gets compounded, and t denotes the number of years. Write a function compounded_total which takes P, n, r, and t as arguments of a function and returns total value after t years.
  4. See the results of this and think about it, we will discuss it tomorrow
x = 10
def foo():
    x = x+1

foo()
print(x)

creating custom functions

In [5]:
def say_hello(greeting, name):# this function takes two arguments(python programming term) /parameter (english/mathematic)
    print(greeting, name, "!")
In [3]:
say_hello("Hello", "Vikrant")
Hello Vikrant !
In [7]:
say_hello("Welcome", "Vikrant")# when we call a function , there is new namespace comes into picture
Welcome Vikrant !
In [6]:
x
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-6fcf9dfbd479> in <module>
----> 1 x

NameError: name 'x' is not defined
In [8]:
hello
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-f572d396fae9> in <module>
----> 1 hello

NameError: name 'hello' is not defined
In [23]:
def hello(): # it takes no arguments
    print("Hello!")
In [12]:
hello # this has to be created?
Out[12]:
<function __main__.hello()>
In [14]:
hello # show me what is this object which has name hello!
Out[14]:
<function __main__.hello()>
In [25]:
hello() # this is calling the fuction with no argument... 
Hello!
In [26]:
def f(a): # the momemnt we execute this defination of function, a variable with name `f` (function name)
    return a*a+2
In [20]:
f # not calling function, this is just examining the obejct woth name f!
Out[20]:
<function __main__.f(a)>
In [21]:
print(f)
<function f at 0x7fdeefc53700>
In [22]:
f(4) ### it automatically creates a variable of name a (name of paramater)
Out[22]:
18
In [27]:
f(7)
Out[27]:
51
In [28]:
x = f(7) # i will get value returned f into x
In [29]:
def NAV(assets, liabilities, shares):
    return (assets - liabilities)/shares
In [30]:
def numeric_value(strvalue):
    v = strvalue.replace("(","-").replace(")","")
    return float(v)
In [31]:
numeric_value("(35.6)")
Out[31]:
-35.6
In [32]:
numeric_value("56")
Out[32]:
56.0
In [35]:
"(35)".replace("(","-").replace(")","") # string 
Out[35]:
'-35'
In [36]:
float("(35)".replace("(","-").replace(")",""))
Out[36]:
-35.0
In [37]:
def add(a, b):
    return a+b
In [38]:
x, y = 5, 6
In [39]:
add(x,y) # this will make x-> a , y->b inside function
Out[39]:
11
In [40]:
add(8, 10) # a and b are defined as 8, 10 ...which only in the function
Out[40]:
18
In [45]:
def foo():
    print(x) # x is not there! if it is not defined locally in function it will take the value from namespace of caller
In [43]:
x
Out[43]:
5
In [46]:
x
Out[46]:
5
In [47]:
foo()
5
In [49]:
x = 10        # global namespace x = 10

def foo():   # foo namespace does not have x
    x = 20    # foo (local to foo) namespace ... it creates a new name x in foo namespace and assignes a value of 20

foo()      
# the moment foo call is over, namespace foo ... is gone!
print(x) # global name space x => 10
10
In [52]:
x = 10

def foo(x): 
    x = 20 # the assignment operator ... whatever is left hand side it create a name for that in current name space
    return x

s = foo(x)
print(x)
10
In [55]:
def appendzero(x):
    x.append(0) # method does the modfication of the object
    
nums = [1, 1, 1]

appendzero(nums)
In [54]:
nums
Out[54]:
[1, 1, 1, 0]
In [56]:
x = 10
In [57]:
l = [1, 2, 3, 4]
In [58]:
#l = [1, 2, 3, 4, 0] # this will create new list
In [59]:
l.append(0)
In [61]:
3*4 # repr
Out[61]:
12
In [62]:
add(3, 4) # repr
Out[62]:
7
In [63]:
x = add(3, 4)
In [64]:
hello = "hello"
In [65]:
hello.upper()
Out[65]:
'HELLO'

Functions as Argumnets

In [66]:
def square(x):
    return x*x
In [67]:
square
Out[67]:
<function __main__.square(x)>
In [68]:
x = 10
In [70]:
y = x # aliasing
In [71]:
y
Out[71]:
10
In [72]:
x
Out[72]:
10
In [73]:
sqr  = square
In [74]:
sqr
Out[74]:
<function __main__.square(x)>
In [75]:
square
Out[75]:
<function __main__.square(x)>
In [76]:
square(5)
Out[76]:
25
In [77]:
sqr(5)
Out[77]:
25
In [79]:
add(x, y)
Out[79]:
20
In [81]:
def square(x):
    return x*x

def cube(x):
    return x*x*x

def sumofsquares(x, y):
    return square(x) + square(y)


def sumofcubes(x, y):
    return cube(x) + cube(y)

def sumof(x, y, func):
    return func(x) + func(y)
In [82]:
sumof(9 , 18, square)
Out[82]:
405
In [83]:
sumofsquares(9, 18)
Out[83]:
405
In [84]:
sumof(9, 18, cube)
Out[84]:
6561
In [85]:
abs(-5)
Out[85]:
5
In [86]:
sumof(-5, 10, abs)
Out[86]:
15
In [87]:
words = ["one", "two", "three", "four", "five", "six"]
In [88]:
max([1, 2, 45, 2, 5])
Out[88]:
45
In [89]:
max(words) # finding max by dictionary position, it tries to arrange alphabeticaly
Out[89]:
'two'
In [91]:
max(words, key=len)
Out[91]:
'three'
In [92]:
sorted(words)
Out[92]:
['five', 'four', 'one', 'six', 'three', 'two']
In [93]:
sorted(words, key=len)
Out[93]:
['one', 'two', 'six', 'four', 'five', 'three']
In [94]:
max(["hello", "text", "random", "words"]) #arrange it alphabetical (ASCII) order and return last one
Out[94]:
'words'
In [95]:
max(["hello", "text", "random", "words"], key=len) #len("string")
Out[95]:
'random'
In [96]:
records = [
    ("TATA", 200.0, 5.5),
    ("REL",2000.5, -5),
    ("INF", 1550.3, 3.0),
    ("HCL",1200, 70.5)
]
In [97]:
records[0]
Out[97]:
('TATA', 200.0, 5.5)
In [98]:
max(records)
Out[98]:
('TATA', 200.0, 5.5)
In [111]:
x =  ("TATA", 200.0, 5.5)
In [112]:
x[1]
Out[112]:
200.0
In [113]:
x[0]
Out[113]:
'TATA'
In [114]:
x[2]
Out[114]:
5.5
In [99]:
def get_value(r):
    return r[1]

def get_name(r):
    return r[0]

def get_gain(r):
    return r[2]
In [100]:
max(records, key=get_value)
Out[100]:
('REL', 2000.5, -5)
In [101]:
max(records, key=get_gain)
Out[101]:
('HCL', 1200, 70.5)
In [102]:
min(records, key=get_value)
Out[102]:
('TATA', 200.0, 5.5)
In [103]:
min(records, key=get_gain)
Out[103]:
('REL', 2000.5, -5)
In [104]:
sorted(records, key=get_name)
Out[104]:
[('HCL', 1200, 70.5),
 ('INF', 1550.3, 3.0),
 ('REL', 2000.5, -5),
 ('TATA', 200.0, 5.5)]
In [105]:
sorted(records, key=get_value)
Out[105]:
[('TATA', 200.0, 5.5),
 ('HCL', 1200, 70.5),
 ('INF', 1550.3, 3.0),
 ('REL', 2000.5, -5)]
In [106]:
sorted(records, key=get_gain)
Out[106]:
[('REL', 2000.5, -5),
 ('INF', 1550.3, 3.0),
 ('TATA', 200.0, 5.5),
 ('HCL', 1200, 70.5)]
In [119]:
x = 10
def foo():
    x = x+1 # the assignment operator delinks my name x from global, it create a local
            # you can't do modificaton of global like this

foo()
print(x)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-119-740b485f526e> in <module>
      4             # you can't do modificaton of global like this
      5 
----> 6 foo()
      7 print(x)

<ipython-input-119-740b485f526e> in foo()
      1 x = 10
      2 def foo():
----> 3     x = x+1 # the assignment operator delinks my name x from global, it create a local
      4             # you can't do modificaton of global like this
      5 

UnboundLocalError: local variable 'x' referenced before assignment
In [116]:
x = 10
def foo():
    print(x) # take from global context on for reading

foo()
print(x)
10
10
In [117]:
doom
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-117-19c75a2ef253> in <module>
----> 1 doom

NameError: name 'doom' is not defined
In [118]:
doom = doom + 4
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-118-3d9b9f683cac> in <module>
----> 1 doom = doom + 4

NameError: name 'doom' is not defined
In [120]:
x = 10
def foo():
    y = x+1 

foo()
print(x)
10

Introduction to programming constructs

condtions

In [121]:
True
Out[121]:
True
In [122]:
False
Out[122]:
False
In [125]:
"Vikrant".startswith("V") # boolean value
Out[125]:
True
In [126]:
"hel" in "Hello"
Out[126]:
False
In [127]:
"hel" in "hello"
Out[127]:
True
In [128]:
"hello"  in "Worlds"
Out[128]:
False
In [132]:
x = "hello"
y = "hello"
In [134]:
x == y # check if x and y are same
Out[134]:
True
In [135]:
x in y # check if x in y
Out[135]:
True
In [136]:
"one" in ["one", "two", "three", "four"]
Out[136]:
True
In [137]:
"name" in {"name":"Alice", "age":20}  # check if 'name' is in keys of dictionary
Out[137]:
True
In [138]:
#x in collection # check if x is there in collection
In [139]:
x, y = 5, 4
In [140]:
x > y
Out[140]:
True
In [141]:
x<y
Out[141]:
False
In [142]:
x <= y
Out[142]:
False
In [143]:
y >= x
Out[143]:
False
In [144]:
x != y # results in True if x and y are not equal 
Out[144]:
True
In [145]:
if "hel" in "cell":
    x = 30
    y = x+45
    print("hell!") # exeute this if condition if this block is True
In [146]:
if "hel" in "cell":
    x = 30
    y = x+45
    print("hell!") # exeute this if condition if this block is True
elif "cel" in "hell":
    print("cell!")
elif "del" in "bell":
    print("dell!")
else:
    print("None of the conditons were True!")
None of the conditons were True!
In [153]:
cond = True
if cond:
    x = 2
else:
    x = 3
In [148]:
x
Out[148]:
2
In [150]:
def get_value_x(cond):
    if cond:
        return 2
    else:
        return 3
In [151]:
get_value_x(True)
Out[151]:
2
In [154]:
min
Out[154]:
<function min>
In [155]:
max
Out[155]:
<function max>
In [156]:
def min_(x, y):
    if x < y:
        return x
    else:
        return y
In [157]:
min_(45, 23)
Out[157]:
23

While loop

In [1]:
def print_list(items):
    i = 0
    while i < len(items):# till this condition is True, execute following block 
        print(items[i])# prints one line at a time
        i = i +1 
In [2]:
numbers = [3, 2, 1, 3, 6]
In [3]:
print_list(numbers)
3
2
1
3
6
In [4]:
numbers[0] # numbers[i] i = 0
Out[4]:
3
In [5]:
numbers[1]# numbers[i] i = 1
Out[5]:
2
In [6]:
numbers[2]# numbers[i] i = 2
Out[6]:
1
In [12]:
numbers[3]# numbers[i] i = 3
Out[12]:
3
In [13]:
numbers[4]# # numbers[i] i = 4
Out[13]:
6
In [15]:
numbers[5]# # numbers[i] i = 5 # this cond has to be avoided
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-15-cdb148220ebf> in <module>
----> 1 numbers[5]# # numbers[i] i = 5 # this cond has to be avoided

IndexError: list index out of range
In [17]:
i == 5 # this is to be avoided
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-17-98f0dcdd9270> in <module>
----> 1 i == 5 # this is to be avoided

NameError: name 'i' is not defined
In [18]:
i < 5 # is allowed
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-18-e014bed90376> in <module>
----> 1 i < 5 # is allowed

NameError: name 'i' is not defined
In [38]:
def print_list(items):
    i = 0
    while i < len(items):# till this condition is True, execute following block 
        print(items[i])# prints one line at a time
        i = i +1
In [20]:
i = 0 
In [21]:
i < len(numbers)
Out[21]:
True
In [23]:
#print(numbers[i])# prints one line at a time
i = i +1 
3
In [24]:
i
Out[24]:
1
In [25]:
i < len(numbers)
Out[25]:
True
In [26]:
#print(numbers[i])# prints one line at a time
i = i +1 
In [27]:
i
Out[27]:
2
In [28]:
i < len(numbers)
Out[28]:
True
In [29]:
#print(numbers[i])# prints one line at a time
i = i +1 
In [30]:
i < len(numbers)
Out[30]:
True
In [31]:
i
Out[31]:
3
In [32]:
#print(numbers[i])# prints one line at a time
i = i +1 
In [33]:
i
Out[33]:
4
In [34]:
i < len(numbers)
Out[34]:
True
In [35]:
#print(numbers[i])# prints one line at a time
i = i +1 
In [36]:
i
Out[36]:
5
In [37]:
i < len(numbers)
Out[37]:
False
In [39]:
print_list(numbers)
3
2
1
3
6
In [40]:
def print_list(items):
    i = 0
    while i < len(items):# till this condition is True, execute following block
        i = i + 1 
        print(items[i])# prints one line at a time
        
In [41]:
print_list(numbers)
2
1
3
6
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-41-32f7e5f44d3d> in <module>
----> 1 print_list(numbers)

<ipython-input-40-e37d5e1b3f7d> in print_list(items)
      3     while i < len(items):# till this condition is True, execute following block
      4         i = i + 1
----> 5         print(items[i])# prints one line at a time
      6 

IndexError: list index out of range
In [42]:
numbers
Out[42]:
[3, 2, 1, 3, 6]
In [43]:
def print_list(items):
    i = 0
    while i < len(items):# till this condition is True, execute following block
        
        print(items[i])# prints one line at a
        
        i = i + 1 # do this at end of loop 
In [44]:
print_list(numbers)
3
2
1
3
6
In [47]:
def print_list1(items):# not recommanded
    i = -1
    while i < (len(items)-1):# till this condition is True, execute following block
        i = i + 1
        print(items[i])# prints one line at a
        
         
In [46]:
print_list1(numbers)
3
2
1
3
6
In [50]:
def print_list(items):
    i = 0
    while i < len(items):# till this condition is True, execute following block
        x = items(i)#<--------
        print(x)# prints one line at a
        i = i + 1 # do this at end of loop 
In [51]:
print_list(numbers)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-51-32f7e5f44d3d> in <module>
----> 1 print_list(numbers)

<ipython-input-50-f83a38ce5ecd> in print_list(items)
      2     i = 0
      3     while i < len(items):# till this condition is True, execute following block
----> 4         x = items(i)#<--------
      5         print(x)# prints one line at a
      6         i = i + 1 # do this at end of loop

TypeError: 'list' object is not callable
In [53]:
name = "Vikrant"
In [54]:
name(0)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-54-127db450e689> in <module>
----> 1 name(0)

TypeError: 'str' object is not callable
In [56]:
name[0]# any access of items from collection is using square backet
Out[56]:
'V'
In [59]:
def print_list_single_line(items):
    i = 0 
    while i < len(items):
        print(items[i], end=",") # tell print not to end every print with \n
        i = i + 1
In [60]:
print_list_single_line(numbers)
3,2,1,3,6,
In [61]:
def print_list_single_line(items, sep):
    i = 0 
    while i < len(items):
        print(items[i], end=sep) # tell print not to end every print with \n
        i = i + 1
In [62]:
print_list_single_line(numbers, " ")
3 2 1 3 6 
In [63]:
print_list_single_line(numbers, ",")
3,2,1,3,6,
In [64]:
print_list_single_line(numbers, "")
32136
In [65]:
print_list_single_line(numbers, "\n")
3
2
1
3
6
In [66]:
def print_list_single_line(items, sep=","): # default argument
    i = 0 
    while i < len(items):
        print(items[i], end=sep) # tell print not to end every print with \n
        i = i + 1
In [67]:
print_list_single_line(numbers) # sep is taken as default value
3,2,1,3,6,
In [68]:
print_list_single_line(numbers, ":")
3:2:1:3:6:
In [69]:
def addone(a, b=1):
    return a+b
In [70]:
addone(3)
Out[70]:
4
In [71]:
addone(3, 5)
Out[71]:
8
In [72]:
def addone_(a, b):
    return a + b
In [73]:
addone_(5)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-73-87b93c8e01fc> in <module>
----> 1 addone_(5)

TypeError: addone_() missing 1 required positional argument: 'b'
In [74]:
def addone(b=1, a):
    return a+b
  File "<ipython-input-74-136f5cef0cb5>", line 1
    def addone(b=1, a):
               ^
SyntaxError: non-default argument follows default argument
In [75]:
def addone(a, b=1):
    return a +b

For loop

In [76]:
words = ["one", "two", "three", "four"]
In [77]:
for word in words:
    print(word, end=",")
one,two,three,four,
In [78]:
def printlist(items):
    for item in items:
        print(item)
In [79]:
printlist(numbers)
3
2
1
3
6
In [80]:
students = ["A","B","C","D","E"]
In [82]:
for student in students:
    print(student, end=",")
A,B,C,D,E,
In [83]:
def sumlist(items):
    s = 0
    for n in items:
        s = s + n
    return s
In [84]:
sumlist(numbers)
Out[84]:
15
In [86]:
sumlist(words)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-86-0ec078326588> in <module>
----> 1 sumlist(words)

<ipython-input-83-a50cd175e038> in sumlist(items)
      2     s = 0
      3     for n in items:
----> 4         s = s + n
      5     return s

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [87]:
def sumlist(items, start=0):
    s = start
    for n in items:
        s = s + n
    return s
In [88]:
sumlist(numbers)
Out[88]:
15
In [89]:
sumlist(words, "")
Out[89]:
'onetwothreefour'
In [90]:
for c in "string":
    print(c, end=",")
s,t,r,i,n,g,
In [91]:
for key in {"x":1,"y":2}:
    print(key)
x
y
In [92]:
for s in (1, 2, 3,4, 5):
    print(s, end=",")
1,2,3,4,5,

Simple Problems

  1. Write a function product which finds product of all elements from a list.
        >>> product([3, 2, 4])
        24
  1. Write a function factorial to find factorial of a number.
    >>> factorial(5)
    120
  1. Write a function findlens which finds lengths of every word from a given list of words.
        >>> findlens(["one", "two", "three"])
        [3, 3, 5]
  1. Write a function find_words_of_len to find words of given length from given list.:
    >>> find_words_of_len(words, 3)
    ['one', 'two', 'six']

Medium level Problems

  1. Write a function unique which will remove duplicates from a list.:
    >>> unique([1, 1, 2, 3, 1, 2, 3, 2, 4])
    [1, 2, 3, 4]
  1. List of urls is given. Some urls are from same domain, some are from different. Find unique domain names used in the 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']
  1. Write a function min2 which find minimum from given two numbers. Also write a function min3 which can find minimum number from given 3 numbers. Do not make use of bulit in min function.

  2. Write a function rearramge_max to rearrange digits of an integer so as to make maximum integer from it.

        >>> rearramge_max(1312)
        3211
In [ ]: