Pcap Session 18
Pcap Session 18
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, ...)
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
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])
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()
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.
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.
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)
• 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:
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.