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
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
def digit_count(nums1,els1):
num = str(nums1)
els = str(els1)
return num.count(els)
digit_count(1231, 1)
2
digit_count(1231, 3)
1
digit_count(1231, 9)
0
def digit_count(number,digit):
numbertoString=str(number)
digittoString=str(digit)
return int((numbertoString.count(digittoString)))
digit_count(1231, 1) # 2
digit_count(1231, 3) # 1
digit_count(1231, 9) # 0
0
2 + 3
5**5
1**32 # interpreter will respond only for last line
1
digit_count(1231, 1)
2
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
num = 1234566
str_digits = str(num)
str_digits[::-1]
'6654321'
num = 1234566
str_digits = str(num)
int(str_digits[::-1])
6654321
def reverse_digits(num):
str_digits = str(num)
return int(str_digits[::-1])
reverse_digits(1232432)
2342321
reverse_digits(6785)
5876
def reverse_digits(num):
digits = list(str(num))
digits.reverse()
return int("".join(digits))
def numeric_value(strnum):
""">>> numeric_value("(121323)")
-121323
>>> numeric_value("232")
232
"""
new_chars = strnum.replace("(", "-").replace(")", "")
return int(new_chars)
numeric_value("(123)")
-123
numeric_value("345454")
345454
"(2323)".replace("(", "-").strip(")")
'-2323'
"text".endswith("t") # this one way of checking
True
strnum = "(121232)"
"(" in strnum
True
"-" in strnum
False
evens = list(range(2, 20, 2))
evens
[2, 4, 6, 8, 10, 12, 14, 16, 18]
1 in evens
False
4 in evens
True
3 not in evens
True
4 not in evens
False
check = ")" in strnum
check
True
x = 5
y = 4
x > 5
False
x < 5
False
x >= 5
True
x != y
True
x == y #check if x and y are equal
False
"hello" == strnum
False
s = {1, 1, 2, 2, 3, 4}
2 in s
True
x = 10
y = 10
x == y
True
x = 10
y = 10
x == y
True
x==y
True
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
if True:
pass
elif True:
pass
def even(n):
if n%2 == 0:
return True
else:
return False
even(5)
False
even(2)
True
def even(n):
return n%2 == 0
even(4)
True
even(5)
False
def is_palindrom(text):
return text == text[::-1]
is_palindrom("madam")
True
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
is_palindrom(str(121))
True
Question: What is subscriptable?
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
mymax1(5, 6)
6
mymax2(5, 6)
6
mymax1(20, 4)
20
mymax2(20, 4)
20
both codes are same ..because the way return works
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
add1(5, True)
10
add2(5, True)
17
if 5:
print(" I am 5")
I am 5
What all results True if you don't give condition , but give some object directly
What results into False
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.
words = "one two three four five six".split()
words
['one', 'two', 'three', 'four', 'five', 'six']
plain english
for every word in words , capitalize the word
for word in words:
print(word.capitalize())
One Two Three Four Five Six
words
['one', 'two', 'three', 'four', 'five', 'six']
caps_words = []
for word in words:
W = word.capitalize()
caps_words.append(W)
caps_words
['One', 'Two', 'Three', 'Four', 'Five', 'Six']
evens
[2, 4, 6, 8, 10, 12, 14, 16, 18]
for every number in evens, square the number
for number in evens:
print(number**2)
4 16 36 64 100 144 196 256 324
sqr_evens = []
for e in evens:
s = e**2
sqr_evens.append(s)
sqr_evens
[4, 16, 36, 64, 100, 144, 196, 256, 324]
text = "Some text with some data in it"
for every char in text, print char and space
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
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
for e in evens:
print(e) # this add newline
2 4 6 8 10 12 14 16 18
for e in evens:
print(e, end=",")
2,4,6,8,10,12,14,16,18,
print(2, 3, 4, 5)
2 3 4 5
print(2) # sep will come into picture only when I give multiple items to print
2
print(2, 5)
2 5
print(2, " ")
print(2, 3, 4, 5, sep="_")
2_3_4_5
digits = {"one" : 1,
"two" : 2,
"three" : 3,
"four": 4}
for w in words:
print(w,end="_")
one_two_three_four_five_six_
digits = {"one" : 1,
"two" : 2,
"three" : 3,
"four": 4}
for key in digits:
print(key)
one two three four
for key in digits:
print(key, digits[key])
one 1 two 2 three 3 four 4
for key, value in digits.items():
print(key, value)
one 1 two 2 three 3 four 4
we want to implement mysum exactly like built in sum
sum(evens)
90
s = 0
for n in evens:
s = s + n
s
90
s = 10
def mysum(nums):
s = 0
for num in nums:
s = s + num
return s
mysum(range(10))
45
mysum(range(100))
4950
def mysum_(nums):
s = 0
for num in nums:
s = s + num
return s # this statement sould be outside for loop
mysum(evens)
2
s = 10
def mysum_(nums):
for num in nums:
s = s + num
return s
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
def mysum_(nums, s):
for num in nums:
s = s + num
return s
mysum_(evens, 0)
90
problems
product which finds product of all elements from a list.>>> product([3, 2, 4])
24
factorial to find factorial of a number.>>> factorial(5)
120
findlens which finds lengths of every word from a given list of words.>>> findlens(["one", "two", "three"])
[3, 3, 5]
find_words_of_len to find words of given length from given list.:>>> find_words_of_len(words, 3)
['one', 'two', 'six']
def product(nums):
pr = 1
for n in nums:
pr = pr * n
return pr
def factorial(n):
return product(range(1, n +1))
factorial(6)
720
factorial(5)
120
range(5)
range(0, 5)
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
list(range(1, 5))
[1, 2, 3, 4]
list(range(5, 4))
[]
n = 5
list(range(1, n+1))
[1, 2, 3, 4, 5]
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
words
findlens(words)
[3, 3, 5, 4, 4, 3]
words
['one', 'two', 'three', 'four', 'five', 'six']
find_words_of_len(words, 5)
['three']
find_words_of_len(words, 4)
['four', 'five']
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)
sumof(5, 6, square)
61
sumofsqures(5, 6)
61
max(evens)
18
evens
[2, 4, 6, 8, 10, 12, 14, 16, 18]
words
['one', 'two', 'three', 'four', 'five', 'six']
max(words) # you want word with maximum lenght
'two'
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
mymaxwords(words)
'three'
def mymaxnums(nums):
maxnum = nums[0]
for num in nums:
if num > maxnum:
maxnum = num
return maxnum
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
mymaxwords(words)
'three'
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
mymaxnums(evens)
18
def mymax(items, comparator=comparenums):
maxitem = items[0]
for item in items:
if comparator(item, maxitem):
maxitem = item
return maxitem
mymax(words, comparator=comparewords)
'three'
mymax(evens)
18
max(evens)
18
max(words, key=len)
'three'
mymax(evens, comparator=comparenums)
18
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.
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'
max(words, key=len)
'three'
records = [
("TATA", 200.0, 5.5),
("INFY", 2000.0, -5),
("RELIANCE", 1505.5, 50.0),
("HCL", 1200, 70.5)
]
max(records) # by default first column, then second....
('TATA', 200.0, 5.5)
def get_value(record):
return record[1]
def get_gain(record):
return record[2]
max(records, key=get_value)
('INFY', 2000.0, -5)
max(records, key=get_gain)
('HCL', 1200, 70.5)
def mylen(w):
print("Finding len of ", w)
return len(w)
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
'three'
words[0]
'one'
records[0]
('TATA', 200.0, 5.5)