Jun 20-24, 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
© Pipal Academy LLP
#"(3465324.54)" -> -13465324.54
def numeric_value(text_num):
x = text_num.replace("(", "-").replace(")", "")
return float(x)
numeric_value("(2323.6")
-2323.6
numeric_value("5656.6") #
5656.6
text = "hello this is what it is!"
text.replace("how", "where")
'hello this is what it is!'
def reverse_digits(integer):
reversed_ = str(integer)[::-1]
return int(reversed_)
reverse_digits(3435435)
pass # this is empty statement
def reverse_digits(integer):
reversed_ = str(integer)[::-1]
return int(reversed_)
print(reverse_digits(3435435))
5345343
'3435435'[::-1]
'5345343'
int('5345343')
5345343
num = 34343
list(3434)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [13], in <cell line: 1>() ----> 1 list(3434) TypeError: 'int' object is not iterable
list('34343')
['3', '4', '3', '4', '3']
num
34343
num[::-1] # slicing is only for collections like list, str, tuple
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [17], in <cell line: 1>() ----> 1 num[::-1] TypeError: 'int' object is not subscriptable
def digit_count(number, digit):
return str(number).count(str(digit))
def digit_count(number, digit):
strnum = str(number)
strdigit = str(digit)
return strnum.count(strdigit)
def test_reverse_digits():
assert reverse_digits(1234) == 4321
assert reverse_digits(1) == 1
assert reverse_digits(0) == 0
test_reverse_digits() # everything passed!
def test_reverse_digits1():
assert reverse_digits1(1234) == 4321
def reverse_digits1(num):
return str(num)[::-1]
reverse_digits1(1234)
'4321'
test_reverse_digits1()
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Input In [29], in <cell line: 1>() ----> 1 test_reverse_digits1() Input In [22], in test_reverse_digits1() 1 def test_reverse_digits1(): ----> 2 assert reverse_digits1(1234) == 4321 AssertionError:
#def mean(nums):
# return sum(nums)/len(nums)
def mean(nums):
return (nums[0]+nums[1]+nums[2]+nums[3]+nums[4])/5
def test_mean():
assert mean([1,2,3,4,5]) == 3.0
assert mean([1,2]) == 1.5
assert mean(range(1,10)) == 5.5
test_mean()
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Input In [39], in <cell line: 1>() ----> 1 test_mean() Input In [38], in test_mean() 8 def test_mean(): 9 assert mean([1,2,3,4,5]) == 3.0 ---> 10 assert mean([1,2]) == 1.5 11 assert mean(range(1,10)) == 5.5 Input In [38], in mean(nums) 5 def mean(nums): ----> 6 return (nums[0]+nums[1]+nums[2]+nums[3]+nums[4])/5 IndexError: list index out of range
1 == 2
False
2 == 1
False
1 == 1
True
two = [1,2]
two[2]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Input In [44], in <cell line: 1>() ----> 1 two[2] IndexError: list index out of range
nums = [1, 2, 3, 4, 5]
nums[2]
3
num = 2232
num[2]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [50], in <cell line: 1>() ----> 1 num[2] TypeError: 'int' object is not subscriptable
def twice(x):
print(2*x)
fourtimes5 = twice(twice(5)) # this will fail
10
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [52], in <cell line: 1>() ----> 1 fourtimes5 = twice(twice(5)) Input In [51], in twice(x) 1 def twice(x): ----> 2 print(2*x) TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
def twice(x):
return 2*x
twice(twice(5)) # this jupyter interpreter. this automatically shows me output of last like in this code cell
20
twice(twice(5)) # this executed but no results are shown because this is last line in this cell
pass # empty statement
twice(twice(twice(5)))
40
a, b = 1, 2
def add_():
return a+b # this not recommeded way of writing code!
def add(x, y):
return x+y
add(3, 5)
8
add(1000, 454609)
455609
add_() # just computes a+b!
3
n = 3
def power(x):
return x**n # not a good way!
def cube(x):
return x**3
def power(base, exponent):
return base**exponent
ones = [1, 1, 1, 1]
ones.append(2)
[1, 2, 3, 4] + [0]
[1, 2, 3, 4, 0]
xlist = [1, 1, 1]
def appendzero(ylist):
ylist = ylist + [0] # this creates a local variable!
appendzero(xlist) # here xlist is linked with ylist...they point to same object
print(xlist)
[1, 1, 1]
xlist = [1, 1, 1]
def appendzero(ylist):
ylist.append(0) # list method
appendzero(xlist)
print(xlist)
[1, 1, 1, 0]
zlist = [1, 2, 3, 4,5]
appendzero(zlist)
print(zlist)
[1, 2, 3, 4, 5, 0]
def cylinder_volume(radius, height):
return 3.14*radius**2*height
cylinder_volume(1, 2) # positinal arguments... order is important
6.28
cylinder_volume(2, 1) # by mistake I changed order of arguments, so you get wrong results
12.56
cylinder_volume(height=2, radius=1) # if i give named arguments..then order does not matter
6.28
def foo(a, b, c, d):
return ((a**b)*c)+d
foo(1, 2, 3, 4)
7
foo(2, 1, 3, 4)
10
foo(1, c=3, d=4, b=2) # you can give first few arguments without name..but in correct order
7
foo(c=3, d=4, 1, 2) # this is not allowed... positional argument can not follow named argument
Input In [89] foo(c=3, d=4, 1, 2) # this is not allowed... positional argument can not follow named argument ^ SyntaxError: positional argument follows keyword argument
foo(1, 2, 3, d=4) # named arguments can follow positional argument
7
def say_hello(name, greeting):
print(name, greeting)
def say_hello(name, greeting="hello"): # default argument!
print(name, greeting)
say_hello("vikrant") # if you don't give greeting argument.. it will take default value
vikrant hello
say_hello("vikrant", "welcome")
vikrant welcome
say_hello(name="vikrant", greeting="welcome")
vikrant welcome
def say_hello(name):
print(name,"hello")
def say_welcome(name):
print(name,"welcome")
def greetings(name, greetingtype="Hello"):
print(greetingtype, name)
greetings("vikrant")
Hello vikrant
greetings("vikrant", "Welcome")
Welcome vikrant
def foobar():
print("foobar")
foobar
<function __main__.foobar()>
print(foobar)
<function foobar at 0x7f50f6cee170>
print(3)
3
print(foobar)
<function foobar at 0x7f50f6cee170>
def sqaure(x):
return x*x
def sumofsquares(x, y):
return sqaure(x) + sqaure(y) # in your new functions you call all your old functions or you can anyway call built in functions
def cube(x):
return x**3
def sumofcubes(x, y):
return cube(x) + cube(y)
sumofsquares(2, 3)
13
sumofcubes(4, 5)
189
def sumof(x, y, func):
return func(x) + func(y)
sumof(4, 5, cube)
189
sumof(2, 3, sqaure)
13
max([3, 232, 434, 56])
434
def foosum(x, y, funcx, funcy):
return funcx(x), funcy(y)
foosum(5, 7, sqaure, cube)
(25, 343)
def foosum(x,funcx, y, funcy):
return funcx(x)+ funcy(y)
foosum(5, cube, 10, sqaure)
225
abs(-1)
1
foosum(-5, abs, 4, sqaure)
21
max([324, 3434, 455, 65])
3434
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.
words = ["one", "two", "three", "four", "five", "six", "seven"]
max(words) # take alphabetical order.. dictinary order and return last item
'two'
max(words, key=len)
'three'
def mylen(word):
print("processing", word, ", it has length:", len(word))
return len(word)
mylen("xyz")
processing xyz , it has length: 3
3
words
['one', 'two', 'three', 'four', 'five', 'six', 'seven']
max(words, key=mylen)
processing one , it has length: 3 processing two , it has length: 3 processing three , it has length: 5 processing four , it has length: 4 processing five , it has length: 4 processing six , it has length: 3 processing seven , it has length: 5
'three'
words_ = ['one', 'seven', 'two', 'three', 'four', 'five', 'six']
max(words_, key=mylen)
processing one , it has length: 3 processing seven , it has length: 5 processing two , it has length: 3 processing three , it has length: 5 processing four , it has length: 4 processing five , it has length: 4 processing six , it has length: 3
'seven'
def fixed_value(x):
return 3
max(words, key=fixed_value)
'one'
words_ = ['one', 'seven', 'two', 'three', 'four', 'five', 'six']
max(words_, key=mylen) # max can bring up only one values.. so if their is a tie then first occurence will be returned
processing one , it has length: 3 processing seven , it has length: 5 processing two , it has length: 3 processing three , it has length: 5 processing four , it has length: 4 processing five , it has length: 4 processing six , it has length: 3
'seven'
Suppose There are some records which name, value and gain
records = [
("TATA", 200.0, 5.5),
("INFY", 2000.0, -5),
("RELIANCE",1505.5, 50),
("HCL",1200, 70.5)]
records
[('TATA', 200.0, 5.5),
('INFY', 2000.0, -5),
('RELIANCE', 1505.5, 50),
('HCL', 1200, 70.5)]
records[0]
('TATA', 200.0, 5.5)
records[-1]
('HCL', 1200, 70.5)
def get_value(record):
return record[1]
def get_name(record):
return record[0]
def get_gain(record):
return record[2]
get_value(records[0])
200.0
max(records, key=get_value) # row with max value
('INFY', 2000.0, -5)
records
[('TATA', 200.0, 5.5),
('INFY', 2000.0, -5),
('RELIANCE', 1505.5, 50),
('HCL', 1200, 70.5)]
max(records, key=get_gain)
('HCL', 1200, 70.5)
min(records, key=get_value)
('TATA', 200.0, 5.5)
min(records, key=get_gain)
('INFY', 2000.0, -5)
sorted([2133, 43, 45, 654, 6])
[6, 43, 45, 654, 2133]
sorted(records, key=get_value)
[('TATA', 200.0, 5.5),
('HCL', 1200, 70.5),
('RELIANCE', 1505.5, 50),
('INFY', 2000.0, -5)]
records
[('TATA', 200.0, 5.5),
('INFY', 2000.0, -5),
('RELIANCE', 1505.5, 50),
('HCL', 1200, 70.5)]
nums = [1,2, 34, 23, 5, 2, 4]
sorted(nums) # a new sorted list is returned
[1, 2, 2, 4, 5, 23, 34]
nums
[1, 2, 34, 23, 5, 2, 4]
nums.sort() # method! it changes orignal data
nums
[1, 2, 2, 4, 5, 23, 34]
sorted(records, key=get_value,reverse=True)
[('INFY', 2000.0, -5),
('RELIANCE', 1505.5, 50),
('HCL', 1200, 70.5),
('TATA', 200.0, 5.5)]
problem using max and key function can you find out a record of a company who has longest name
def get_name_len(r):
name = get_name(r)
return len(name)
max(records, key=get_name_len)
('RELIANCE', 1505.5, 50)
True
True
False
False
"hel" in "hello" # check if string hel is in hello or not!
True
name = "vikrant"
fullname = "vikrant patil"
name in fullname
True
fullname in name
False
fullname not in name
True
"bel" in "hello"
False
"bel" not in "hello"
True
nums
[1, 2, 2, 4, 5, 23, 34]
0 in nums
False
1 in nums
True
t = (0, 1, 2, 3, 45, 5)
-1 in t
False
5 in t
True
scores ={"vikrant":42, "vendant":45, "vrushali":50}
"vikrant" in scores # it will in keys!
True
50 in scores.values()
True
55 in scores.values()
False
"abhishek" in scores # it will check on keys
False
50 in scores # it wil try to search 50 in keys...so it will fail
False
scores.values() # it is some kind of collection
dict_values([42, 45, 50])
x, y = 5, 6
x > y
False
x >= y
False
x == y # true if equal
False
x != y # true if not equal
True
if "hel" in "hello":
print("hel!")
print("blah, blah")
elif "cel" in "hell":
print("cell!")
elif "del" in "bell":
print("dell")
else:
print("oops!")
hel! blah, blah
x , y = 3, 3
if x == y and y != 0:
print(x/y)
1.0
x , y = 0, 0
if x == y and y != 0:
print(x/y)
x , y = 0, 0
if x == y and y != 0:
print(x/y)
else:
print("condition not satified")
condition not satified
x , y = 3, 4
if x == y or y > 0:
print(x/y)
else:
print("condition not satified")
0.75
cond1 and cond2 or cond3 this we can add multiple conditions together
cond1 and (cond2 or cond3)
To iterate over a collection in python you don't need keep track of index! for every_student in class this is how python for loop looks, just like plain english
multiline = """Navya Raj
Gosala Rajeshwari Nidhi
Roychoudhury, Nayana
Ankit Singh
Mittal, Anirudh
Umang Bansal
Shreya Bansal
Himanshu Agarwal
Manav Malhotra
Abhishek Mathur
Abhishek Singh
Chillara Harsha Vardhan
Padamata venkata satyanarayana
Darshil Patel
Snigdha Damaraju
Sakshi Jain
Santosh Kumar
Shyam Kumar Ramasubramanian
Nikhil Menon
Sachin Jaiswal""".replace(",","")
classroom = multiline.split("\n") # split on newline
classroom
['Navya Raj', 'Gosala Rajeshwari Nidhi', 'Roychoudhury Nayana', 'Ankit Singh', 'Mittal Anirudh', 'Umang Bansal', 'Shreya Bansal', 'Himanshu Agarwal', 'Manav Malhotra', 'Abhishek Mathur', 'Abhishek Singh', 'Chillara Harsha Vardhan', 'Padamata venkata satyanarayana', 'Darshil Patel', 'Snigdha Damaraju', 'Sakshi Jain', 'Santosh Kumar', 'Shyam Kumar Ramasubramanian', 'Nikhil Menon', 'Sachin Jaiswal']
def solve_some_problems(student):
print(student, ":", "Yes, I have done it")
for student in classroom: # student is iteration variable created during this for loop which can be used inside for body
solve_some_problems(student)
pass
pass
pass
print("*"*10) # till this it is body of for loop
print("This is outside for loop")
Navya Raj : Yes, I have done it ********** Gosala Rajeshwari Nidhi : Yes, I have done it ********** Roychoudhury Nayana : Yes, I have done it ********** Ankit Singh : Yes, I have done it ********** Mittal Anirudh : Yes, I have done it ********** Umang Bansal : Yes, I have done it ********** Shreya Bansal : Yes, I have done it ********** Himanshu Agarwal : Yes, I have done it ********** Manav Malhotra : Yes, I have done it ********** Abhishek Mathur : Yes, I have done it ********** Abhishek Singh : Yes, I have done it ********** Chillara Harsha Vardhan : Yes, I have done it ********** Padamata venkata satyanarayana : Yes, I have done it ********** Darshil Patel : Yes, I have done it ********** Snigdha Damaraju : Yes, I have done it ********** Sakshi Jain : Yes, I have done it ********** Santosh Kumar : Yes, I have done it ********** Shyam Kumar Ramasubramanian : Yes, I have done it ********** Nikhil Menon : Yes, I have done it ********** Sachin Jaiswal : Yes, I have done it ********** This is outside for loop
words
['one', 'two', 'three', 'four', 'five', 'six', 'seven']
for word in words: # name of iteration variable is your choice... but give meaningfull name so that it reads like english
print(word, ":", len(word))
one : 3 two : 3 three : 5 four : 4 five : 4 six : 3 seven : 5
for char in "some text data":
print(char, end=",") # after every print dont add newline but add comma
s,o,m,e, ,t,e,x,t, ,d,a,t,a,
scores
{'vikrant': 42, 'vendant': 45, 'vrushali': 50}
for key in scores: # loops over keys
print(key)
vikrant vendant vrushali
for student in classroom[:5]: # take only first 5
print(student)
Navya Raj Gosala Rajeshwari Nidhi Roychoudhury Nayana Ankit Singh Mittal Anirudh
for student in classroom[2:]: # drop first two students, but go over remaining
print(student)
Roychoudhury Nayana Ankit Singh Mittal Anirudh Umang Bansal Shreya Bansal Himanshu Agarwal Manav Malhotra Abhishek Mathur Abhishek Singh Chillara Harsha Vardhan Padamata venkata satyanarayana Darshil Patel Snigdha Damaraju Sakshi Jain Santosh Kumar Shyam Kumar Ramasubramanian Nikhil Menon Sachin Jaiswal
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for n in nums[::2]: #take alternate number
print(n, end=",")
1,3,5,7,9,
for key in scores: # loops over keys
print(key)
vikrant vendant vrushali
for key, value in scores.items(): # loops over keys and values
print(key, value)
vikrant 42 vendant 45 vrushali 50
for score in scores.values():
print(score)
42 45 50
scores.items()
dict_items([('vikrant', 42), ('vendant', 45), ('vrushali', 50)])
records
[('TATA', 200.0, 5.5),
('INFY', 2000.0, -5),
('RELIANCE', 1505.5, 50),
('HCL', 1200, 70.5)]
for record in records:
print(record)
('TATA', 200.0, 5.5)
('INFY', 2000.0, -5)
('RELIANCE', 1505.5, 50)
('HCL', 1200, 70.5)
for name, value, gain in records:
print(name, value, gain)
TATA 200.0 5.5 INFY 2000.0 -5 RELIANCE 1505.5 50 HCL 1200 70.5
scores.items() # only for dictianries
dict_items([('vikrant', 42), ('vendant', 45), ('vrushali', 50)])
for name, score in scores.items(): # it will give items in the order by which dictionary has stored it
print(name, score)
vikrant 42 vendant 45 vrushali 50
matrix = [[1, 2, 3],[4, 5, 6], [7,8, 9]]
for col1, col2, col3 in matrix:
print(col1, col2, col3)
1 2 3 4 5 6 7 8 9
for row in matrix: # because every row has 3 items in it I can put three variable as iteration variables as above
print(row)
[1, 2, 3] [4, 5, 6] [7, 8, 9]
def mysum(nums):
"""This computes sum of numbers
"""
s = 0 # usual practice in accumulation ..zero because it is unaffected by addition
for n in nums:
s = s + n
return s
nums
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
mysum(nums)
55
for i in range(10):
print(i, end=",")
0,1,2,3,4,5,6,7,8,9,
mysum(range(1, 101))
5050
mysum(range(1, 11))
55
def product(nums):
"""computes product of all numbers from a list
"""
p = 1
for n in nums:
p = p * n
return p
product(nums)
3628800
product([2, 3, 4])
24
help(product)
Help on function product in module __main__:
product(nums)
computes product of all numbers from a list
help(mysum)
Help on function mysum in module __main__:
mysum(nums)
This computes sum of numbers
def mysum_(nums):
"""This computes sum of numbers
"""
#s = 0 # usual practice in accumulation ..zero because
for n in nums:
s = s + n
return s
mysum_(range(5))
--------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) Input In [282], in <cell line: 1>() ----> 1 mysum_(range(5)) Input In [281], in mysum_(nums) 5 #s = 0 # usual practice in accumulation ..zero because 6 for n in nums: ----> 7 s = s + n 8 return s UnboundLocalError: local variable 's' referenced before assignment
n = 0
while n < 10: #if this condition is something that never occurs then while loop will go in infinite loop
print(n)
n = n + 1
0 1 2 3 4 5 6 7 8 9
inputs = []
for i in range(3):# a convetion to repeate any activity n time
x = input("Enter " + str(i) +"th input:")
inputs.append(x)
inputs
['hello', 'vikrant', 'arcesium']
def take_inputs(n):
inputs = []
for i in range(n):# a convetion to repeate any activity n time
x = input("Enter " + str(i) +"th input:")
inputs.append(x)
return inputs
take_inputs(2)
['hello', 'lksjdsa']