8  Module 1 - Day 3

Topics

For today’s practice make use of notebook module1-day3.ipynb created in your enviroment. Shut down kernel for all previous notebooks by right cliking on notbeook on left hand side file browser.

%load_problem square
Problem: Square

Write a function square to compute the square of a number.

>>> square(4)
16

You can verify your solution using:

%verify_problem square

# your code here

def square(x):
    return x*x
%verify_problem square
Found 2 checks
βœ“ verify square(2)
βœ“ verify square(4)
πŸŽ‰ Congratulations! You have successfully solved problem square!!

8.1 Methods

8.1.1 string methods

setentece = "These are some wise or otherwise words!"
setentece.startswith("This")
False
setentece.startswith("These")
True
setentece.endswith("?")
False

8.1.1.1 methods that manipulate the data

setentece.split() # it splits given text into words/small subsets of text. 
# it creates a list and returns
['These', 'are', 'some', 'wise', 'or', 'otherwise', 'words!']
setentece.split("or")
['These are some wise ', ' otherwise w', 'ds!']
comma_separated = "symbol,value,high,low,volume"
comma_separated.split(",") # spliting on comma on a csv text, you will get the fields separated
['symbol', 'value', 'high', 'low', 'volume']
path = "/home/jupyter-vikrant/"
path.split("/")
['', 'home', 'jupyter-vikrant', '']
tab_separated = "one\ttwo\tthree"
print(tab_separated)
one two three
tab_separated.split()
['one', 'two', 'three']
multiline = """one
two
three
four"""
multiline
'one\ntwo\nthree\nfour'
print(multiline)
one
two
three
four
multiline.split() # split without any argument or parameter will split on white spaces
# white spaces include space, tab, new line or mixture of it
['one', 'two', 'three', 'four']
words = ["one", "two", "three", "four"]
" ".join(words)
'one two three four'
sentence = " ".join(words)
sentence
'one two three four'
line = "    some line from a file which has white space at start and also at end     "
line
'    some line from a file which has white space at start and also at end     '
line.strip() # will strip trailing white spaces
'some line from a file which has white space at start and also at end'
text = "one          two"
text.strip() # it will remove only trailing spaces
'one          two'

problems

  • On a website login only alphanumeric usernames are allowed. a string is stored in a variable username. How will you check if username is as per rules?

  • A sentence has hyphen between every two words. >>> sentence = "Yet-another-sentence-with-nothing-in-it" How can you transorm it such that there will be space between every two words.

  • A path to file is given for a linux system. on a linux system path seperator is β€œ/”

      >>> path = "/home/vikrant/training/day1.html"

    How will you find only name of file from given path?

  • Using string methods can you find extension of a file if filename is stored in a variable filename = "hello.xlsx"

sentence = "   hello method chaining!   "
sentence.strip().split()[-1]
#--->------>----->------>----->
'chaining!'
path = "/home/vikrant/training/day1.html"
path.split("/")
['', 'home', 'vikrant', 'training', 'day1.html']
path.split("/")[-1]
'day1.html'
def find_filename(path):
    """This will work only on linux/unix/mac
    """
    return path.split("/")[-1]
find_filename("/home/vikrant/trainings/2025/arcesium-finop-dec25/hello.csv")
'hello.csv'
filename = "hello.xlsx" # in this etension is xlsx
zippedfile = "training.tar.gz" # extension is gz
filename.split(".")[-1]
'xlsx'
def find_extension(filename):
    return filename.split(".")[-1]
find_extension(zippedfile)
'gz'
find_extension(filename)
'xlsx'
username1 = "vikrant123"
username2 = "vikrant_patil"
username1.isalnum()
True
username2.isalnum()
False
def check_username(username):
    """This function will check if username is alpha numeric !
    """
    return username.isalnum()
check_username("vikrant323")
True
check_username("vikrant_patil")
False
sentence = "Yet-another-sentence-with-nothing-in-it"
words  = sentence.split("-")
words
['Yet', 'another', 'sentence', 'with', 'nothing', 'in', 'it']
words[0]
'Yet'
words[1]
'another'
words[-1]
'it'
words
['Yet', 'another', 'sentence', 'with', 'nothing', 'in', 'it']
nums = [1, 2, 3, 4, 5, 6] # this actual list does not have comma in it
text_list = "[1, 2, 3, 4, 5, 6]"
text_list[0]
'['
words
['Yet', 'another', 'sentence', 'with', 'nothing', 'in', 'it']
12
12
"12"
'12'
["one", "two", "three", "four"]
['one', 'two', 'three', 'four']
print(words)
['Yet', 'another', 'sentence', 'with', 'nothing', 'in', 'it']

8.1.2 list methods

nums = [1, 2, 3, 4, 5, 6]
nums.index(4) # 
3
words
['Yet', 'another', 'sentence', 'with', 'nothing', 'in', 'it']
words.index("in")
5
words.count("Yet")
1
ones = [1, 1, 1, 1, 1, 1]
ones.count(1)
6
ones.count(2)
0
nums[0]
1
nums[3] # given an index what is the item at that index
4
nums.index(4) # given an item what is the index of that item
3
words[0] # what is the word at 0 index
'Yet'
words.index("in") # what is the index of in!
5
empty = [] 
empty.append(0)# append an item at last
empty
[0]
empty.append("one")
empty
[0, 'one']
empty.append(2)
empty
[0, 'one', 2]
empty.insert(0, -1) # insert at given location  insert(location, value)
empty
[-1, 0, 'one', 2]
empty.remove('one')
ones
[1, 1, 1, 1, 1, 1]
ones.remove(1) # will always remove first occurence of the given item
ones
[1, 1, 1, 1, 1]

observe that which methods return some value and which do not return

words
['Yet', 'another', 'sentence', 'with', 'nothing', 'in', 'it']
empty
[-1, 0, 2]
empty.append(1)
empty.append(1)
empty
[-1, 0, 2, 1, 1]
empty = []
empty.append(1)
empty
[1, 1, 1]
empty = []
empty.append(1)
empty
[1]
words
['Yet', 'another', 'sentence', 'with', 'nothing', 'in', 'it']
words.pop() # will pop last item (it will return that item) and also remove it from the list
'it'
words
['Yet', 'another', 'sentence', 'with', 'nothing', 'in']
words.reverse() # reverse the list in place
words
['in', 'nothing', 'with', 'sentence', 'another', 'Yet']

problem

What will this print?

x = 10 def foo(): x = 20

foo() print(x)

x = 10

def foo():
    x = 20

foo() # these statements are outside function, how? look at indentation
print(x) # this is from global context/namespace/scope
10

What will this print?::

x = 10

def foo(): print(x)

foo()

x = 10

def foo():
    print(x) # if variable is not defined locally it will read (only read) from global

foo()
10

What will this print?::

x = 10

def foo(): x = x + 1

foo() print(x)

x = 10

def foo():
    x = x + 1

foo()
print(x)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
Cell In[148], line 6
      3 def foo():
      4     x = x + 1
----> 6 foo()
      7 print(x)

Cell In[148], line 4, in foo()
      3 def foo():
----> 4     x = x + 1

UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
[1, 2, 3] + [4, 5]
[1, 2, 3, 4, 5]
words
['in', 'nothing', 'with', 'sentence', 'another', 'Yet']
words.append("hello") # this will modify original list
words + ["hello"] # will new create a new list
['in', 'nothing', 'with', 'sentence', 'another', 'Yet', 'hello', 'hello']
words = ['in', 'nothing', 'with', 'sentence', 'another', 'Yet']
print("addition", words + ["hello"])
print("original list", words)
words.append("hello")
print("origianl list after append", words)
addition ['in', 'nothing', 'with', 'sentence', 'another', 'Yet', 'hello']
original list ['in', 'nothing', 'with', 'sentence', 'another', 'Yet']
origianl list after append ['in', 'nothing', 'with', 'sentence', 'another', 'Yet', 'hello']

What will this print?::

x = [1, 1, 1]

def appendzero(y):
    y.append(0)

appendzero(x)
print(x)
x = [1, 1, 1]

def appendzero(y):
    y.append(0)

appendzero(x)
print(x)
[1, 1, 1, 0]
x = [1, 1, 1]

def appendzero(y):
    return y + [0]

z = appendzero(x)
print(x)
print(z)
[1, 1, 1]
[1, 1, 1, 0]
y = [1, 1, 1]

def appendzero(y): # we defined function..
    y.append(0)

print(y)
[1, 1, 1]
y = [1, 1, 1]

def appendzero(y): # we defined function..
    y.append(0)

appendzero(y)
print(y)
[1, 1, 1, 0]
x = [1, 1, 1]
a = x # this is not copy this is alias
b = x[:]   # or use method x.copy() 

def appendzero(y):
    y.append(0)

appendzero(b)
print(x)
print(b)
[1, 1, 1]
[1, 1, 1, 0]

8.2 Functions as first class object

def sumofsqaures(a, b, c):
    return square(a) + square(b) + square(c)

def sumofcubes(a, b, c):
    return cube(a) + cube(b) + cube(c)

def square(x):
    return x*x

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

def sumof(a, b, c, func):
    return func(a) + func(b) + func(c)
sumofsqaures(4, 6, 9)
133
sumof(4, 6, 9, square)
133
sumofcubes(3, 5, 7)
495
sumof(3, 5, 7, cube)
495
x, y, z = 10, 20 , 5
sumofcubes(x, y, z)
9125
sumof(x, y, z, cube)
9125
words = ["one", "two", "three", "four", "five", "six"]
max(words)
'two'
def add(a, b):
    return a + b
add(2, 3) # arguments by position
5
max(words, key=len)
'three'
min(words, key=len)
'one'
sorted(words)
['five', 'four', 'one', 'six', 'three', 'two']
sorted(words, key=len)
['one', 'two', 'six', 'four', 'five', 'three']
records = [
    ("TATA", 200.0, 5.5),
    ("INFY", 2000.0, -5),
    ("RELIANCE", 1505.5, 50.0),
    ("HCL", 1200, 70.5)
]
records[0]
('TATA', 200.0, 5.5)
max(records)
('TATA', 200.0, 5.5)
len("one")
3
r = ('TATA', 200.0, 5.5)
def get_value(r):
    return r[1]

def get_gain(r):
    return r[2]
records
[('TATA', 200.0, 5.5),
 ('INFY', 2000.0, -5),
 ('RELIANCE', 1505.5, 50.0),
 ('HCL', 1200, 70.5)]
max(records, key=get_value)
('INFY', 2000.0, -5)
min(records, key=get_value)
('TATA', 200.0, 5.5)
max(records, key=get_gain)
('HCL', 1200, 70.5)
sorted(records, key=get_value)
[('TATA', 200.0, 5.5),
 ('HCL', 1200, 70.5),
 ('RELIANCE', 1505.5, 50.0),
 ('INFY', 2000.0, -5)]
max("one", "two", "three", "four", "five") # dictionary order
'two'
max("one", "two", "three", "four", "five", key=len)
'three'
('TATA', 200.0, 5.5) ('HCL', 1200, 70.5) ('RELIANCE', 1505.5, 50.0) ('INFY', 2000.0, -5)
       |
    get_value()          get_value()          get_value()               get_value()
    200.0                   1200.0              1505.5                     2000.0

8.3 Porgramming constructs - loops

words
['one', 'two', 'three', 'four', 'five', 'six']
for word in words:
    WORD = word.upper()
    print(WORD)
ONE
TWO
THREE
FOUR
FIVE
SIX
for char in "this statement":
    print(char)
t
h
i
s
 
s
t
a
t
e
m
e
n
t
for char in "this statement":
    print(char, end=",")
t,h,i,s, ,s,t,a,t,e,m,e,n,t,
primes = [1, 2, 3, 5, 7, 11, 13, 17, 19]
for p in primes:
    print(p*p)
1
4
9
25
49
121
169
289
361
sqr = []
for p in primes:
    psqr = p*p
    sqr.append(psqr)
sqr
[1, 4, 9, 25, 49, 121, 169, 289, 361]
def mysum(numbers): # first code block
    s = 0
    for i in numbers: # i will take values 1, 2, 3, 5, ....
        s = s + i
    return s  # the moment you come back to indentation level which was for loop

mysum(primes)
78
primes
[1, 2, 3, 5, 7, 11, 13, 17, 19]
for p in primes:
    print(p)
1
2
3
5
7
11
13
17
19
for x in primes:
    print(x)
1
2
3
5
7
11
13
17
19
for w in words:
    print(w)
one
two
three
four
five
six
for word in words:
    print(word)
one
two
three
four
five
six

8.4 Homework

  • 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. Hint : Use function range(1,n) to generate numbers from 1 to n. if you put for loop on this range(1,n) it will give numbers 1 to n
  >>> 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]