0% found this document useful (0 votes)
15 views

Pcap Session 18

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Pcap Session 18

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

PYTHON – OOP

SESSION 18 - Embed lambda functions into the code, Define and use
closures, Input/Output operations (FILE I/O)
Lambda
• Sometimes you need a simply arithmetic function
• Its silly to write a method for it, but redundant not
too
• With lambda we can create quick simple functions
• Facts
– Lambda functions can only be comprised of a single
expression
– No loops, no calling other methods
– Lambda functions can take any number of variables

Syntax:
lambda param1,…,paramn : expression
Lambda Syntax

1 #Example 1
2 square_func = lambda x : x**2
3 square_func(4) #return: 16
4
5 #Example 2
6 close_enough = lambda x, y : abs(x – y) < 3
7 close_enough(2, 4) #return: True
8
9 #Example 3
0 def get_func(n) :
1 return lambda x : x * n + x % n
2 my_func = get_func(13)
3 my_func(4) #return: 56
Map
map(function, iterable, ...)

• Map applies function to each element of


iterable and creates a list of the results
• You can optionally provide more iterables as
parameters to map and it will place tuples in
the result list
• Map returns an iterator which can be cast to
list
Map Examples

1
2 nums = [0, 4, 7, 2, 1, 0 , 9 , 3, 5, 6, 8, 0, 3]
3
4 nums = list(map(lambda x : x % 5, nums))
5
6 print(nums)
7 #[0, 4, 2, 2, 1, 0, 4, 3, 0, 1, 3, 0, 3]
8
9 def even (x):
10 if (x % 2 == 0):
11 return "even"
12 else:
13 return "odd"
14
15 list (map(even, nums))
16 #['even', 'even', 'odd', 'even', 'odd', 'even',
'odd', 'odd', 'odd', 'even', 'even', 'even', 'odd']
Functions as Parameters
Functions can be assigned to variables and/or passed
as parameters

1 >>> list = ['once', 'upon', 'a', 'time', 'in', 'a']


2
3 >>> def foo (x):
4 return x * 3
5
6 >>> bar = foo
7
>>> my_map (foo, list)
>>> ['onceonceonce', 'uponuponupon', 'aaa', 'timetimetime',
'ininin', 'aaa']
>>> my_map (bar, list)
>>> ['onceonceonce', 'uponuponupon', 'aaa', 'timetimetime',
'ininin', 'aaa']
Map Code

1
2 >>> def my_map (fun, list):
3 ... nlist = []
4 ... for item in list:
5 ... nlist.append(fun(item))
6 ... return nlist
7
Reduce
reduce(function, iterable[,initializer])

• Reduce will apply function to each element in


iterable and create a cumulative sum of the results
• function must take two parameters
• If initializer is provided, initializer will stand as the
first argument in the sum
• Unfortunately in python 3 reduce() requires an
import statement from functools import reduce
Reduce Examples

1
2
3 nums = [9, 2, 0, -4, 0, 0, 7, 5, 3, 8]
4
5 reduce(lambda x, y: x+y, nums)
6 # 30
7
foo = ['once', 'upon', 'a', 'time', 'in', 'a', 'far',
'away']
reduce(lambda x, y : x + y, foo)
# 'onceuponatimeinafaraway'
Reduce Examples

1
2 numlists = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
3
4 reduce(lambda a, b: a + b, numlists, [])
5
6 # [1, 2, 3, 4, 5, 6, 7, 8, 9]
7

nums = [1, 2, 3, 4, 5, 6, 7, 8]
nums = list(reduce(lambda x, y : (x, y), nums))
print(nums) #(((((((1, 2), 3), 4), 5), 6), 7), 8)
Reduce Problem
Goal: given a list of numbers I want to find the
average of those numbers in as few lines as
possible using reduce()

For Loop Method:


- sum up every element of the list
- divide the sum by the length of the list
Reduce Problem

Solution

1 nums = [92, 27, 63, 43, 88, 8, 38, 91, 47, 74, 18, 16,
2 29, 21, 60, 27, 62, 59, 86, 56]
3
4 sum = reduce(lambda x, y : x + y, nums) / len(nums)
Iterators, Generators and
Closures
Iterators
Python iterator objects are required to support two methods
while following the iterator protocol.

__iter__ returns the iterator object itself. This is used


in for and in statements.

__next__ method returns the next value from the iterator. If


there is no more items to return then it should
raise StopIteration exception.
Iterators
Now we can use this iterator in our code.
Iterators
Using the iterator in for loop example we saw,
the following example tries to show the code
behind the scenes.

Remember that an iterator object can be used only


once. It means after it raises StopIteration once, it
will keep raising the same exception.
Generators
It is an easier way to create iterators using a keyword yield from a function.

In the above example we create a simple generator using the yield statements. We can use it in a
for loop just like we use any other iterators.
Generators
In the next example we will create the same Counter class using a generator function
and use it in a for loop..

Inside the while loop when it reaches to the yield statement, the value
of low is returned and the generator state is suspended. During the
second next call the generator resumed where it freeze-ed before and
then the value of low is increased by one. It continues with the while
loop and comes to the yield statement again.
Infinite Generators
We can have generators which produces infinite values. The following is
a one such example
Closures
Closures are nothing but functions that are returned by another
function.
We use closures to remove code duplication.

In the following example we create a simple closure for adding


numbers.

adder is a closure which adds a


given number to a pre-defined one.
Introduction to
File I/O
Files are named locations on disk to store related information. They are used to
permanently store data in a non-volatile memory.
When we want to read from or write to a file, we need to open it first. When we
are done, it needs to be closed so that the resources that are tied with the file are
freed.

Hence, in Python, a file operation takes place in the following order:

(1) Open a file


(2) Read or write (perform operation)
(3) Close the file
Opening Files in Python:
Python has a built-in open() function to open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.

Files are divided into two category:


Text Files - simple texts in human readable format.
Binary Files - have binary data which is understood by the computer.

Syntax: file_object = open(file_name [, access_mode])


f = open("test.txt") # open file in current directory
f = open("C:/Python38/README.txt") # specifying full path
file_name: File name contains a string type value containing the name of the file
which we want to acess.

access_mode: The value of access_mode specifies the mode in which we want to


open the file, i.e, read, write, append, etc.
f = open("test.txt") # equivalent to 'r'
f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'rb+') # read and write in binary mode

Closing a File:
When the operations that are to be performed on an opened file are finished, we have to
close the file in order to release the resources. The closing of file is done with a built-in
function close()
Syntax: fileobject.close()

Example:
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)

# Close opend file


fo.close()
• Most recommended way of using file is along with ‘with’ keyword.
• Because, once the ‘with’ block exits, file is automatically closed and file object is
destroyed.
Eg.,
with open(“test.txt”) as f:
print(f.read())

• The closing method will close the file instantly, It is not safe.
• When we are performing some operations on a file and an exception occurs, the
code exits without closing the file.
• Hence , we should use try...finally block
The file Object Attributes:

file.closed : Returns true if file is closed, false otherwise.


file.mode : Returns access mode with which file was opened.
file.name : Returns name of the file.
file.softspace : Returns false if space explicitly required with
print, true otherwise.
Eg.,
Output:
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name Name of the file: foo.txt
print "Closed or not : ", fo.closed Closed or not : False
Opening mode : wb
print "Opening mode : ", fo.mode Softspace flag : 0
print "Softspace flag : ", fo.softspace
Reading and Writing
Files
• Writing to a File:
The write() method writes any string to an open file. It is important to note that
Python strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the
string.
Syntax : fileObject.write(string)
writelines() method writes the items of a list to the file.

• Reading from a File:


The read() method reads a string from an open file. It is important to note that
Python strings can have binary data. apart from text data.
Syntax : fileObject.read([size])
size - This parameter gives the number of bytes to be read from an opened file.
readline() - This method is used to read the file contents line by line.
whenever we write fileobject.readline(), it prints one line from that file and continues in
this way until the end of the file.

readlines() - This method returns a list containing each line in the file as a list item.
Use the hint parameter to limit the number of lines returned. If the total number of
bytes returned exceeds the specified number, no more lines are returned.

• We can also use the following method to read the content from the file
f = open("test.txt", "r+")
for each in f:
print(each)
• split() using file handling:
This splits the variable when space is encountered. You can also split using any characters
as we wish.
with open("file.text", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word )

File positions:
The tell() method
returns the current file
position in a file
stream.
The seek() method is used to change the position of the File Handle to a given specific
Renaming a File:
• This is done by using rename() method.
• This method is passed with two arguments, the current filename and the new
filename
Syntax : os.rename(current_filename, new_filename)
Deleting a File:
• This is done with the help of the remove() method.
• It takes the filename as an argument to be deleted.
Syntax : os.remove(filename)
File Related
Methods
Sl. No. Methods with Description
1 file.close()
Close the file. A closed file cannot be read or written any more.

2 file.flush()
Flush the internal buffer memory.
3 file.fileno()
Returns the integer file descriptor that is used by the underlying implementation to request I/O
operations from the operating system.
4 file. next ()
Returns the next line from the file each time it is being called
5 file.read([size])
Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes).
6 file.readline([size])
Reads one entire line from the file. A trailing newline character is kept in the string.
7 file.readlines([sizehint])
It reads until the end of the file using readline. It returns the list of lines read.
File Related
Methods
Sl. No. Methods with Description
8 file.seek(offset)
Sets the file's current position

9 file.tell()
Returns the file's current position
10 file.truncate([size])
Truncates the file's size. If the optional size argument is present, the file is truncated to (at most) that
size.
11 file.write(str)
Writes a string to the file. There is no return value.
12 file.writelines(sequence)
Writes a sequence of strings to the file. The sequence can be any iterable object producing strings,
typically a list of strings
13 file.isatty()
Returns True if the file is connected to a tty(-like) device, else False.
Programming Exercise:
(1) Write a program to read a file line by line and store it into a list.
(2) Write a program to find the longest word.
(3) Write a program to remove newline characters from a file.
(4)Write a program to read contents from a file and write the content to another file
after eliminating duplicates.
(5) Write a Python program to count the frequency of words in a file.

You might also like