Python Virtual Training For Arcesium - Module I - Nurturing Session¶

Jul 7, 2022 Vikrant Patil

All notes are available online at https://notes.pipal.in/2022/arcesium_finop_batch1/

Please accept the invitation that you have received in your email and login to

https://engage.pipal.in/

© Pipal Academy LLP

Where to use print and where to use return¶

In [1]:
5 * 4
Out[1]:
20
In [3]:
3 + 4
5**2
[1]*3 # jupyter's behavior
Out[3]:
[1, 1, 1]

There are two types of problems that we have in assignment

  1. You are asked to write a function
  2. You are asked to write a script/program/command
In [5]:
def add(x, y):
    print(x+y) # test will fail
    
add(4, 5)
9
In [6]:
def add(x, y):
    return x+y
In [9]:
%%file add.py
import sys

a = int(sys.argv[1])
b = int(sys.argv[2])

def add_ints(x, y):
    return x+y


add_ints(a, b) # test wil fail bebasue we are not printing the result

# if you don't give this print, test will fail
Overwriting add.py
In [10]:
!python add.py 2 3 
In [11]:
%%file add.py
import sys

a = int(sys.argv[1])
b = int(sys.argv[2])

def add_ints(x, y):
    return x+y


print(add_ints(a, b)) # if you don't give this print, test will fail
Overwriting add.py
In [12]:
!python add.py 4 5
9

when to use for loop¶

  • When you want to go over every item of a collection, list, text (str), tuple, dictionary
In [14]:
nums = [1, 2, 3, 4, 5]
text = "this is some text"
test_tuple = (1, 2, 3, 4, 5, 5, 6)
In [15]:
for n in nums:
    print(n*n)
1
4
9
16
25
In [16]:
cubes = []
for n in test_tuple:
    cubes.append(n**3)
In [17]:
cubes
Out[17]:
[1, 8, 27, 64, 125, 125, 216]
In [18]:
def mean(nums):
    """mean([1, 2, 3, 4, 5])
    3.0
    """
    
    return (nums[0] + nums[1] + nums[2] + nums[3] + nums[4])/5
In [19]:
mean([34, 45, 56])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Input In [19], in <cell line: 1>()
----> 1 mean([34, 45, 56])

Input In [18], in mean(nums)
      1 def mean(nums):
      2     """mean([1, 2, 3, 4, 5])
      3     3.0
      4     """
----> 6     return (nums[0] + nums[1] + nums[2] + nums[3] + nums[4])/5

IndexError: list index out of range
In [20]:
def mean(nums):
    """mean([1, 2, 3, 4, 5])
    3.0
    """
    s = 0
    for n in nums:
        s += n # this is same as s = s + n
    return s/len(nums)
In [21]:
mean([23, 34, 45])
Out[21]:
34.0
In [23]:
mean([])# won't work
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
Input In [23], in <cell line: 1>()
----> 1 mean([])

Input In [20], in mean(nums)
      6 for n in nums:
      7     s += n # this is same as s = s + n
----> 8 return s/len(nums)

ZeroDivisionError: division by zero
In [24]:
len([])
Out[24]:
0
In [25]:
def mean(nums):
    """mean([1, 2, 3, 4, 5])
    3.0
    """
    if len(nums) == 0:
        return 0
    
    s = 0
    for n in nums:
        s += n # this is same as s = s + n
    return s/len(nums)
In [26]:
%%file add1.py
import sys

a = int(sys.argv[1])
b = int(sys.argv[2])

def add_ints(x, y):
    return x+y # here is it allowed!


return add_ints(a, b) # for scripts only print statement is the mechanism to tell user what is output!
                      # return statements are only part of a function
Writing add1.py
In [27]:
!python add1.py 2 3
  File "/home/vikrant/trainings/2022/arcesium_finop_batch1/add1.py", line 10
    return add_ints(a, b) # for scripts only print statement is the mechanism to tell user what is output!
    ^^^^^^^^^^^^^^^^^^^^^
SyntaxError: 'return' outside function

Q: How is while loop different from for loop and whats the use case

  • Whenever you want to loop over a collection you use for loop
  • Whenever you don't have collection , but you have some condition till which code has to be executed. in that case you make use of while loop
In [29]:
nums = [34, 454 , 343, 3, 5]

find sum of first 1000 numbers

  • Either You make a list/range of first 1000 numbers and call sum on it or use for loop to sum it
  • make use of condition n < 1000 to find sum
In [30]:
sum1000 = 0
count = 1

while count <= 1000:
    sum1000 += count
    count += 1
    
print(sum1000)
500500
  • every problem of for loop can be solved with while loop. But if the condition is wrong , you might end up in infinite loop or you might not go over all the desired cases
  • for loop will avoid above problem, because it doe not have condition! There is no question of going it wrong
In [31]:
s = 0 
for i in range(1, 1001):
    s += i
print(s)
500500
In [32]:
stocks = {"IBM": 123,
         "APPLE": 150,
         "AGILENT": 300,
         "AT&T": 200}
In [33]:
stocks['IBM'] # access by key
Out[33]:
123
In [34]:
for item in stocks: # this will loop over keys
    print(item)
IBM
APPLE
AGILENT
AT&T
In [35]:
for key, value in stocks.items():# loop over key and value
    print(key, value)
IBM 123
APPLE 150
AGILENT 300
AT&T 200
In [36]:
for value in stocks.values():# loop over values
    print( value)
123
150
300
200
In [37]:
x, y = 3, 4
In [38]:
x, y = [5, 6]
In [39]:
a, b = (3, 4)
In [40]:
a
Out[40]:
3
In [41]:
b
Out[41]:
4
In [44]:
# name, value and volume
records = [("name1", 34, 678),
           ("name2", 45, 343),
           ("name3", 100, 50)]
In [46]:
for record in records:
    print(record)
('name1', 34, 678)
('name2', 45, 343)
('name3', 100, 50)
In [50]:
for name, value, volume in records: # you have to know before hand that it has 3 items
    if value > 50:
        print("This has value greater than 50")
        print(name, volume)
This has value greater than 50
name3 50
In [51]:
import os
In [52]:
def longlistdir(folder):
    files_dirs = os.listdir(folder)
    
    for filename in files_dirs:
        if os.path.isfile(filename):
            print("f", filename)
        else:
            print("d", filename)
In [54]:
longlistdir("..")
d data.txt
d arcesium_finop_batch1
In [55]:
os.path.isfile("sadjkjshfkjds hf")
Out[55]:
False
In [56]:
def longlistdir(folder):
    files_dirs = os.listdir(folder)
    
    for filename in files_dirs:
        filepath = os.path.join(folder, filename)
        if os.path.isfile(filepath):
            print("f", filename)
        else:
            print("d", filename)
In [57]:
longlistdir("..")
f data.txt
d arcesium_finop_batch1
In [58]:
longlistdir(".")
f index.html
f mystas.py
f nurturing-session.ipynb
f module1-day5.html
f arguments.py
f day2.txt
f push
f hello.py
f sqaure.py
f module1-day5.ipynb
f nurturing1.org
d __pycache__
f index.ipynb
f module1-day1.html
f module1-day1.ipynb
f module1-day2.ipynb
f add.py
f module1-day3.html
f module1-day2.html
f day3.txt
f day1.txt
f nurturing-session.html
f module1-day3.ipynb
f module1-day4.html
f Makefile
d .ipynb_checkpoints
f nurturing1.org~
f add1.py
f module1-day4.ipynb
In [59]:
def longlistdir_deep(folder):
    files_dirs = os.listdir(folder)
    
    for filename in files_dirs:
        filepath = os.path.join(folder, filename)
        if os.path.isfile(filepath):
            print("f", filename)
        else:
            print("d", filename)
            longlistdir_deep(filepath)
In [60]:
longlistdir_deep("..")
f data.txt
d arcesium_finop_batch1
f index.html
f mystas.py
f nurturing-session.ipynb
f module1-day5.html
f arguments.py
f day2.txt
f push
f hello.py
f sqaure.py
f module1-day5.ipynb
f nurturing1.org
d __pycache__
f mystas.cpython-310.pyc
f index.ipynb
f module1-day1.html
f module1-day1.ipynb
f module1-day2.ipynb
f add.py
f module1-day3.html
f module1-day2.html
f day3.txt
f day1.txt
f nurturing-session.html
f module1-day3.ipynb
f module1-day4.html
f Makefile
d .ipynb_checkpoints
f nurturing-session-checkpoint.ipynb
f module1-day4-checkpoint.ipynb
f index-checkpoint.ipynb
f module1-day2-checkpoint.ipynb
f index-checkpoint.html
f module1-day3-checkpoint.ipynb
f module1-day5-checkpoint.ipynb
f module1-day1-checkpoint.ipynb
f nurturing1.org~
f add1.py
f module1-day4.ipynb
In [66]:
def longlistdir_deep(folder, prefix=""):
    files_dirs = os.listdir(folder)
    
    for filename in files_dirs:
        filepath = os.path.join(folder, filename)
        if os.path.isfile(filepath):
            print(prefix, "f", filename)
        else:
            print(prefix, "d", filename)
            longlistdir_deep(filepath, prefix + "    ")
In [67]:
longlistdir_deep("..")
 f data.txt
 d arcesium_finop_batch1
     f index.html
     f mystas.py
     f nurturing-session.ipynb
     f module1-day5.html
     f arguments.py
     f day2.txt
     f push
     f hello.py
     f sqaure.py
     f module1-day5.ipynb
     f nurturing1.org
     d __pycache__
         f mystas.cpython-310.pyc
     f index.ipynb
     f module1-day1.html
     f module1-day1.ipynb
     f module1-day2.ipynb
     f add.py
     f module1-day3.html
     f module1-day2.html
     f day3.txt
     f day1.txt
     f nurturing-session.html
     f module1-day3.ipynb
     f module1-day4.html
     f Makefile
     d .ipynb_checkpoints
         f nurturing-session-checkpoint.ipynb
         f module1-day4-checkpoint.ipynb
         f index-checkpoint.ipynb
         f module1-day2-checkpoint.ipynb
         f index-checkpoint.html
         f module1-day3-checkpoint.ipynb
         f module1-day5-checkpoint.ipynb
         f module1-day1-checkpoint.ipynb
     f nurturing1.org~
     f add1.py
     f module1-day4.ipynb
In [68]:
def fib(n):
    """nth fibonacci is sum of (n-1)th fibonacci and (n-2)th fibonacci
    """
    
    if n == 0 or n == 1:
        return n
    
    else:
        return fib(n-1) + fib(n-2)
    

``` just to show how this will work def dirsize(folder): files = #listfiles size = 0 for f in files: if f is file: size += sizeof(f) else: size += dirsize(folder/f)

return size

```

In [70]:
def hello():
    print("hello")

SUMIFs¶

Implement excel function SUMIFS as a function in python. SUMIFS(sum_list, criteria_list, condition). Here first argument is the list on which sum will be performed. Second argument is the list on which condition is checked, and third argument is condition as a string , as in excel.

possible values of condition are

  • "<" --------- less than
  • "<="--------- less than or equal to
  • ">" --------- greater than
  • ">="--------- greater than or equal to
  • "<>"--------- not equal to

Sample run is shown below. For simplicity assume that all the data consists of integers.

  >>> d = [1,2,3,4,5,4,4,5]
  >>> a = [10,20,30,40,50,40,40,50]
  >>> SUMIFS(d, a, "<40")
  6
  >>> SUMIFS(d, a, ">=40")
  22
  >>> SUMIFS(d, a, "40")
  12
  >>> SUMIFS(d, a, "<>40")
  16
In [74]:
def lessthaneq(sumlist, criterio_list, condition):
    num = int(condition[2:])
    s = 0
    for i in range(len(sumlist)):
        if criterio_list[i] <= num:
            s += sumlist[i]
            
    return s
    
    
def SUMIFS(sum_list, criterio_list, condition):
    s = 0
    if "<>" in condition:
        pass
    elif "<=" in condition:
        return lessthaneq(sum_list, criterio_list, condition)
    elif "<" in condition:
        pass
    elif ">=" in condition:
        pass
    elif ">" in condition:
        pass
    else:
        # case for equal
        pass
    
In [72]:
d = [1,2,3,4,5,4,4,5]
a = [10,20,30,40,50,40,40,50]
In [73]:
SUMIFS(d, a, "<=50")
Out[73]:
28
In [ ]: