Python Virtual Training For Arcesium - Module I - Day 4¶

Jan 16-20, 2023 Vikrant Patil

All notes are available online at https://notes.pipal.in/2023/arcesium_finop_jan/

Please login to https://engage.pipal.in/ and launch jupyter lab

For today create a notebook with name module1-day4

notebook names are case sensitive. Make sure you give correct name

© Pipal Academy LLP

Concept of Function¶

In [ ]:
index = 0
numeric, text = complex_list[0][index], complex_list[1][index]
print(numeric, text)

index = 1
numeric, text = complex_list[0][index], complex_list[1][index]
print(numeric, text)

index = 2
numeric, text = complex_list[0][index], complex_list[1][index]
print(numeric, text)

# code snippet from submissions

def digit_count(nums1,els1):
    num = str(nums1)
    els = str(els1)
    return num.count(els) #

nums1 = ("1231")
els1 = ("1")
print(nums1.count("1"))

def digit_count(nums2,els2):
    num = str(nums2)
    els = str(els2)
    return num.count(els2)

nums2 = ("1231") # not required ()
els2 = ("3")
print(nums1.count("3"))

def digit_count(nums3,els3):
    num = str(nums3)
    els = str(els3)
    return num.count(els3)

nums3 = ("1231")
els3 = ("9")
print(nums1.count("9"))

### Write a function digit_count that takes a number and a digit as argument and returns the number of 
### times the digit is present in that number.


2*(3+4)

(1, 2, 3)
"this" # ("this")
num2 = 1231
els2 = 3
In [1]:
def digit_count(nums1,els1):
    num = str(nums1)
    els = str(els1)
    return num.count(els)
In [2]:
digit_count(1231, 1)
Out[2]:
2
In [3]:
digit_count(1231, 3)
Out[3]:
1
In [4]:
digit_count(1231, 9)
Out[4]:
0
In [5]:
def digit_count(number,digit):
    numbertoString=str(number)
    digittoString=str(digit)
    return int((numbertoString.count(digittoString)))
In [6]:
digit_count(1231, 1) # 2
digit_count(1231, 3) # 1 
digit_count(1231, 9) # 0
Out[6]:
0
In [7]:
2 + 3
5**5
1**32 # interpreter will respond only for last line
Out[7]:
1
In [8]:
digit_count(1231, 1)
Out[8]:
2
In [9]:
x = digit_count(1231, 1) # this will happen only if our function returns value

problem

Write a function reverse_digits which will reverse digits of multi digit number and return new formed integer.

>>> reverse_digits(1234)
4321
In [10]:
num = 1234566
str_digits = str(num)
str_digits[::-1]
Out[10]:
'6654321'
In [11]:
num = 1234566
str_digits = str(num)
int(str_digits[::-1])
Out[11]:
6654321
In [12]:
def reverse_digits(num):
    str_digits = str(num)
    return int(str_digits[::-1])
In [13]:
reverse_digits(1232432)
Out[13]:
2342321
In [14]:
reverse_digits(6785)
Out[14]:
5876
In [15]:
def reverse_digits(num):
    digits = list(str(num))
    digits.reverse()
    return int("".join(digits))
In [16]:
def numeric_value(strnum):
    """>>> numeric_value("(121323)")
    -121323
    >>> numeric_value("232")
    232
    """
    new_chars = strnum.replace("(", "-").replace(")", "")
    return int(new_chars)
In [17]:
numeric_value("(123)")
Out[17]:
-123
In [18]:
numeric_value("345454")
Out[18]:
345454
In [20]:
"(2323)".replace("(", "-").strip(")")
Out[20]:
'-2323'

Conditions¶

In [22]:
"text".endswith("t") # this one way of checking
Out[22]:
True
In [23]:
strnum = "(121232)"
In [24]:
"(" in strnum
Out[24]:
True
In [25]:
"-" in strnum
Out[25]:
False
In [26]:
evens = list(range(2, 20, 2))
In [27]:
evens
Out[27]:
[2, 4, 6, 8, 10, 12, 14, 16, 18]
In [28]:
1 in evens
Out[28]:
False
In [30]:
4 in evens
Out[30]:
True
In [31]:
3 not in evens
Out[31]:
True
In [32]:
4 not in evens
Out[32]:
False
In [33]:
check = ")" in strnum
In [34]:
check
Out[34]:
True
In [35]:
x = 5
y = 4
In [36]:
x > 5
Out[36]:
False
In [37]:
x < 5
Out[37]:
False
In [38]:
x  >= 5
Out[38]:
True
In [39]:
x != y
Out[39]:
True
In [40]:
x == y #check if x and y are equal
Out[40]:
False
In [41]:
"hello" == strnum
Out[41]:
False
In [43]:
s = {1, 1, 2, 2, 3, 4}
In [44]:
2 in s
Out[44]:
True
In [45]:
x = 10
y = 10
In [46]:
x == y
Out[46]:
True
In [47]:
x = 10
y = 10
In [48]:
x == y
Out[48]:
True
In [50]:
x==y
Out[50]:
True
In [51]:
if "hel" in "cell": # line start with if...this makes it block statement .. it should end with :
    print("hell!")
    print("Hello!")
elif "cel" in "hell": # block
    print("cell!")
elif "del" in "bell": # block
    print("delll")
else:                 #block
    print("oops!")
oops!
  • you start with if block

  • you can have as many elif s as you want with a condition

  • finally at end you can have else

  • you can have only if, no need to have else, elif

  • you can have if and else , no need to have elif

  • you can also have if and elif , no need to have else

  • only one block will be executed.

  • if multiple conditions in block are True, then that occures first will be executed

In [52]:
if True:
    pass
elif True:
    pass
In [53]:
def even(n):
    if n%2 == 0:
        return True
    else:
        return False
In [54]:
even(5)
Out[54]:
False
In [55]:
even(2)
Out[55]:
True
In [57]:
def even(n):
    return n%2 == 0
In [58]:
even(4)
Out[58]:
True
In [59]:
even(5)
Out[59]:
False
In [60]:
def is_palindrom(text):
    return text == text[::-1]
In [61]:
is_palindrom("madam")
Out[61]:
True
In [62]:
is_palindrom(121)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[62], line 1
----> 1 is_palindrom(121)

Cell In[60], line 2, in is_palindrom(text)
      1 def is_palindrom(text):
----> 2     return text == text[::-1]

TypeError: 'int' object is not subscriptable
In [63]:
is_palindrom(str(121))
Out[63]:
True

Question: What is subscriptable?

  • anything after which we can put a square bracket and access by indexing
  • string/list/dict/tuple these are subscriptable
In [69]:
def mymax1(a, b):
    if a > b:
        return a
    else:
        return b
    
def mymax2(a, b):
    if a > b:
        return a # this will be executed only if condition after if is True
    return b
  
In [70]:
mymax1(5, 6)
Out[70]:
6
In [71]:
mymax2(5, 6)
Out[71]:
6
In [72]:
mymax1(20, 4)
Out[72]:
20
In [73]:
mymax2(20, 4)
Out[73]:
20

both codes are same ..because the way return works

  • Whereever we reach return statement, function execution ends there!
  • if there are multiple return statements, which ever return comes first in the flow thats where function ends
In [66]:
def add1(x, addfive): # this func will add either 5 or 7
    if addfive: 
        x = x + 5
    else:
        x = x + 7
    
    return x
    
def add2(x, addfive): # this func will always add 7 , but add 5 is optional
    if addfive:
        x = x + 5
    
    x = x + 7
    return x
    
    
In [74]:
add1(5, True)
Out[74]:
10
In [75]:
add2(5, True)
Out[75]:
17
In [76]:
if 5:
    print(" I am 5")
 I am 5

What all results True if you don't give condition , but give some object directly

  • nonzero integer
  • nonempty string
  • nonempty list
  • nonempty dict
  • non empty tuple

What results into False

  • zero
  • empty string
  • empty list
  • empty dict
  • empty tuple
  • None

for loops¶

Iteartions in python are different from other languanges.

Anything that is iterable (iterable is any collection that we saw till today) we can put for loop on it.

In [78]:
words = "one two three four five six".split()
In [79]:
words
Out[79]:
['one', 'two', 'three', 'four', 'five', 'six']

plain english

for every word in words , capitalize the word

In [80]:
for word in words:
    print(word.capitalize())
One
Two
Three
Four
Five
Six
In [81]:
words
Out[81]:
['one', 'two', 'three', 'four', 'five', 'six']
In [82]:
caps_words = []
for word in words:
    W = word.capitalize()
    caps_words.append(W)
In [83]:
caps_words
Out[83]:
['One', 'Two', 'Three', 'Four', 'Five', 'Six']
In [84]:
evens
Out[84]:
[2, 4, 6, 8, 10, 12, 14, 16, 18]

for every number in evens, square the number

In [85]:
for number in evens:
    print(number**2)
4
16
36
64
100
144
196
256
324
In [86]:
sqr_evens = []
for e in evens:
    s = e**2
    sqr_evens.append(s)
In [87]:
sqr_evens
Out[87]:
[4, 16, 36, 64, 100, 144, 196, 256, 324]
In [88]:
text = "Some text with some data in it"

for every char in text, print char and space

In [91]:
for char in text:
    print(char, " ", sep="", end="") # if you skip sep then it will add its own space
                                     # if you skil end, then it will add its one \n
S o m e   t e x t   w i t h   s o m e   d a t a   i n   i t 
In [92]:
for char in text:
    print(char," ")
S  
o  
m  
e  
   
t  
e  
x  
t  
   
w  
i  
t  
h  
   
s  
o  
m  
e  
   
d  
a  
t  
a  
   
i  
n  
   
i  
t  
In [93]:
for e in evens:
    print(e) # this add newline
2
4
6
8
10
12
14
16
18
In [94]:
for e in evens:
    print(e, end=",")
2,4,6,8,10,12,14,16,18,
In [95]:
print(2, 3, 4, 5)
2 3 4 5
In [97]:
print(2) # sep will come into picture only when I give multiple items to print
2
In [98]:
print(2, 5)
2 5
In [ ]:
print(2, " ")
In [96]:
print(2, 3, 4, 5, sep="_")
2_3_4_5
In [ ]:
digits = {"one" : 1,
            "two" : 2,
           "three" : 3,
           "four": 4}
In [101]:
for w in words:
    print(w,end="_")
one_two_three_four_five_six_
In [102]:
digits = {"one" : 1,
            "two" : 2,
           "three" : 3,
           "four": 4}
In [103]:
for key in digits:
    print(key)
one
two
three
four
In [104]:
for key in digits:
    print(key, digits[key])
one 1
two 2
three 3
four 4
In [105]:
for key, value in digits.items():
    print(key, value)
one 1
two 2
three 3
four 4

Example¶

we want to implement mysum exactly like built in sum

In [106]:
sum(evens)
Out[106]:
90
In [107]:
s = 0
for n in evens:
    s =  s + n
In [108]:
s
Out[108]:
90
In [116]:
s = 10
def mysum(nums):
    s = 0
    for num in nums:
        s = s + num
    
    return s
In [110]:
mysum(range(10))
Out[110]:
45
In [111]:
mysum(range(100))
Out[111]:
4950
In [115]:
def mysum_(nums):
    s = 0
    for num in nums:
        s = s + num
    
        return s # this statement sould be outside for loop
In [113]:
mysum(evens)
Out[113]:
2
In [117]:
s = 10
def mysum_(nums):
    for num in nums:
        s = s + num
    
    return s
In [118]:
mysum_(evens)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
Cell In[118], line 1
----> 1 mysum_(evens)

Cell In[117], line 4, in mysum_(nums)
      2 def mysum_(nums):
      3     for num in nums:
----> 4         s = s + num
      6     return s

UnboundLocalError: local variable 's' referenced before assignment
In [119]:
def mysum_(nums, s):
    for num in nums:
        s = s + num
    
    return s
In [120]:
mysum_(evens, 0)
Out[120]:
90

problems

  • Write a function product which finds product of all elements from a list.
>>> product([3, 2, 4])
24
  • Write a function factorial to find factorial of a number.
>>> factorial(5)
120
  • Write a function findlens which finds lengths of every word from a given list of words.
>>> findlens(["one", "two", "three"])
[3, 3, 5]
  • 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']
In [121]:
def product(nums):
    pr = 1
    for n in nums:
        pr = pr * n
    return pr
In [122]:
def factorial(n):
    return product(range(1, n +1))
In [123]:
factorial(6)
Out[123]:
720
In [124]:
factorial(5)
Out[124]:
120
In [125]:
range(5)
Out[125]:
range(0, 5)
In [126]:
range("5")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[126], line 1
----> 1 range("5")

TypeError: 'str' object cannot be interpreted as an integer
In [128]:
list(range(1, 5))
Out[128]:
[1, 2, 3, 4]
In [130]:
list(range(5, 4))
Out[130]:
[]
In [131]:
n = 5
list(range(1, n+1))
Out[131]:
[1, 2, 3, 4, 5]
In [132]:
def product(nums):
    p = 1
    for num in nums:
        p = p * num
    return p

def factorial(n):
    return product(range(1, n+1))

def findlens(words):
    lens = []
    for word in words:
        lens.append(len(word))
        
    return lens


def find_words_of_len(words, length):
    words_of_length = []
    
    for word in words:
        if len(word) == length:
            words_of_length.append(word)
            
    return words_of_length
    
In [135]:
words
findlens(words)
Out[135]:
[3, 3, 5, 4, 4, 3]
In [136]:
words
Out[136]:
['one', 'two', 'three', 'four', 'five', 'six']
In [137]:
find_words_of_len(words, 5)
Out[137]:
['three']
In [138]:
find_words_of_len(words, 4)
Out[138]:
['four', 'five']

functions are like any other variable¶

In [142]:
def square(x):
    return x*x

def cube(x):
    return x**3

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

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


def sumof(x, y, func): # functions can be passed as aarguments ..just like any other variable
    return func(x) + func(y)
In [140]:
sumof(5, 6, square)
Out[140]:
61
In [141]:
sumofsqures(5, 6)
Out[141]:
61
In [143]:
max(evens)
Out[143]:
18
In [144]:
evens
Out[144]:
[2, 4, 6, 8, 10, 12, 14, 16, 18]
In [145]:
words
Out[145]:
['one', 'two', 'three', 'four', 'five', 'six']
In [146]:
max(words) # you want word with maximum lenght
Out[146]:
'two'
In [149]:
def mymaxwords(words):
    word_of_max_len = words[0]
    
    for word in words:
        if len(word) > len(word_of_max_len):
            word_of_max_len = word
            
    return word_of_max_len
In [150]:
mymaxwords(words)
Out[150]:
'three'
In [151]:
def mymaxnums(nums):
    maxnum = nums[0]
    
    for num in nums:
        if num > maxnum:
            maxnum = num
            
    return maxnum
In [153]:
def comparewords(word1, word2):
    return len(word1) > len(word2)
    
def mymaxwords(words):
    word_of_max_len = words[0]
    
    for word in words:
        if comparewords(word, word_of_max_len):
            word_of_max_len = word
            
    return word_of_max_len
In [154]:
mymaxwords(words)
Out[154]:
'three'
In [155]:
def comparenums(num1, num2):
    return num1>num2

def mymaxnums(nums):
    maxnum = nums[0]
    
    for num in nums:
        if comparenums(num, maxnum):
            maxnum = num
            
    return maxnum
In [156]:
mymaxnums(evens)
Out[156]:
18
In [157]:
def mymax(items, comparator=comparenums):
    maxitem = items[0]
    
    for item in items:
        if comparator(item, maxitem):
            maxitem = item
            
    return maxitem
In [158]:
mymax(words, comparator=comparewords)
Out[158]:
'three'
In [159]:
mymax(evens)
Out[159]:
18
In [160]:
max(evens)
Out[160]:
18
In [161]:
max(words, key=len)
Out[161]:
'three'
In [162]:
mymax(evens, comparator=comparenums)
Out[162]:
18
In [163]:
help(max)
Help on built-in function max in module builtins:

max(...)
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.

In [165]:
max(words, len) # this will not work
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[165], line 1
----> 1 max(words, len) # this will not work

TypeError: '>' not supported between instances of 'builtin_function_or_method' and 'list'
In [166]:
max(words, key=len)
Out[166]:
'three'
In [167]:
records = [
  ("TATA", 200.0, 5.5),
  ("INFY", 2000.0, -5),
  ("RELIANCE", 1505.5, 50.0),
  ("HCL", 1200, 70.5)
]
In [168]:
max(records) # by default first column, then second....
Out[168]:
('TATA', 200.0, 5.5)
In [169]:
def get_value(record):
    return record[1]


def get_gain(record):
    return record[2]
In [171]:
max(records, key=get_value)
Out[171]:
('INFY', 2000.0, -5)
In [172]:
max(records, key=get_gain)
Out[172]:
('HCL', 1200, 70.5)
In [173]:
def mylen(w):
    print("Finding len of ", w)
    return len(w)
In [174]:
max(words, key=mylen)
Finding len of  one
Finding len of  two
Finding len of  three
Finding len of  four
Finding len of  five
Finding len of  six
Out[174]:
'three'
In [175]:
words[0]
Out[175]:
'one'
In [176]:
records[0]
Out[176]:
('TATA', 200.0, 5.5)
In [ ]: