A Complete Beginner-Level Python Course to Learn Data Science and Machine Learning
Day 4: Map, Filter & File I/O
It is the third day of our journey to Learn all the Python we need for Machine Learning and DataScience. All of my new code is linked to the previous code from the earlier parts of this series. You can find them below.
Day 04: Map, Filter & File I/O
Map
Definition
The Python map() method is used to perform a function on every item in a list, dictionary, tuple, or set. The map() method accepts a function and an object to apply that the function will operate on. Python includes a built-in method of applying a specific function to all elements within an iterable object: map()
Purpose
The map() function returns a map object (which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple, etc.). It is a function to which map passes each element of a given iterable.
Importance
The Python map() function is used to apply a function on all the elements of specified iterable and return map object. Python map object is an iterator, so we can iterate over its elements. We can also convert map objects to sequence objects such as lists, tuples, etc.
Strengths
Advantages of map include the size property, an easy way to get the number of items on the map. With an Object, you would be on your own to figure out its size.
Weakness
The map is a pretty awesome function that helps us a lot in applying the single function to the whole list. The weakness is the wrong way of using it like if you mistakenly give it the wrong function to apply on the list.
Example 01
Task
use the map function to map the lambda function that find the length of the string onto the list of strings to find the length of each element string in the list
Code
checkString='The quick brown fox jumps over the lazy dog'words=checkString.split()print(words)lengths=map(lambda word:len(word),words)list(lengths)
Output
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog'][3, 5, 5, 3, 5, 4, 3, 4, 3]
Example 02
Task
map the lambda function that finds if the string is a palindrome and apply it onto the list
Code
resultOfPalindrom=map(lambda word:checkPalindrom(word),words)list(resultOfPalindrom)
Output
The is a palindrom
quick is a not palindrom
brown is a not palindrom
fox is a palindrom
jumps is a not palindrom
over is a not palindrom
the is a palindrom
lazy is a not palindrom
dog is a palindrom[True, False, False, True, False, False, True, False, True]
Example 03
Task
map the greetings function onto the list and print it
Code
def greetings(student):print("Hy {studentName} you has got {studentCGPA} CGPA".format(studentName=student[0],studentCGPA=student[1]))return "Hy {studentName} you has got {studentCGPA} CGPA\n".format(studentName=student[0],studentCGPA=student[1])greetingsStudent=map(greetings,studentsResult)greetingsStudent=list(greetingsStudent)
Output
Hy Muhammad Umair you has got 3.06 CGPA
Hy Hamdad Ijaz you has got 2.8 CGPA
Hy Muhammad Abdullah Tahir you has got 2.7 CGPA
Filter
Definition
The filter() method constructs an iterator from elements of an iterable for which a function returns true. In simple words, the filter() method filters the given iterable with the help of a function that tests each element in the iterable to be true or not.
Purpose
The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.
Importance
The filter() function in Python is a built-in function that filters a given input sequence(an iterable) of data based on a function that generally returns either true or false for data elements of the input sequence
Strengths
Filters methods belong to the category of feature selection methods that select features independently of the machine learning algorithm model. filter methods are that they are very fast.
Weakness
the weakness of the filter function is that if we will give it the wrong condition to apply. It will take large time for a large amount of Data
Example 04
Task
use the filter function to filter out the even numbers from the list of Fibonacci series
Code
evenFib=filter(lambda x:x%2,fibList)list(evenFib)studentsResult
Output
[1, 1, 3, 5, 13, 21, 55]
(('Muhammad Umair', 3.06), ('Hamdad Ijaz', 2.8), ('Muhammad Abdullah Tahir', 2.7))
Example 05
Task
Use the filter function to filter out the students that have CGPA greater than 2 from the tuple using lambda functions
Code
passStudetsList=filter(lambda student:student[1]>2,studentsResult)
list(passStudetsList)
Output
[('Muhammad Umair', 3.06), ('Hamdad Ijaz', 2.8), ('Muhammad Abdullah Tahir', 2.7)]
File I/O
Definition
A file is some information or data which stays in the computer storage devices. … Python gives you easy ways to manipulate these files. Generally, we divide files into two categories, text file, and binary file. Text files are simple text whereas binary files contain binary data which is only readable by a computer.
Purpose
Python file handling (a.k.a File I/O) is one of the essential topics for programmers and automation testers. It is required to work with files for either writing to a file or read data from it.
Also, if you are not already aware, I/O operations are the costliest operations where a program can stumble. Hence, you should be quite careful while implementing file handling for reporting or any other purpose. Optimizing a single file operation can help you produce a high-performing application or a robust solution for automated software testing.
Let’s take an example, say, you are going to create a big project in Python that contains a no. of workflows. Then, it’s inevitable for you not to create a log file. And you’ll also be doing both the read/write operations on the log file. Log files are a great tool to debug large programs. It’s always better to think about a scalable design from the beginning, as you won’t regret it later that you didn’t do it.
Importance
File handling is one of the most important parts of any language. Python language supports two types of files. The first one is a text file that store data in the form of text and is readable by humans and computers. The second one is a binary file that stores binary data and is readable by computer only.
Strengths
Files are used to save the important data produced during the execution of the program. For example, you want to save the username after providing the user an input field to take his name and then to save it into the file to use later
Weakness
The weakness of the files is that they contain important information if they get deleted all the information will lose and we can mistakenly overwrite the data that also create the data loss
Example 06
Task
Use the input function to take input from user and store it into the variable and print it.
Code
from six.moves import inputstring = input("Enter your name: ");print(string)
Output
Enter your name:
Example 07
Task
Create a text file and write something into it
Code
fileOpen = open("Bio.txt", "w")for greetings in greetingsStudent:fileOpen.write(greetings);fileOpen.close()
Output
The File has been created and the Data has been inserted in It.
Example 08
Task
Create a text file and read something from it
Code
fileOpen = open("Bio.txt", "r+")str = fileOpen.read();print (str)fileOpen.close()
Output
Hy Muhammad Umair you has got 3.06 CGPA
Hy Hamdad Ijaz you has got 2.8 CGPA
Hy Muhammad Abdullah Tahir you has got 2.7 CGPA
Code
fo = open("Bio.txt", "r+")str = fo.read(10);print ("Read String is : \n", str)position = fo.tell();print ("Current file position : \n", position)position = fo.seek(11, 0);str = fo.read(10);print ("Again read String is : \n", str)# Close opend filefo.close()import osos.rename("Bio.txt", "StudentsGreetings.txt")
Output
Read String is : Hy Muhamma
Current file position : 10
Again read String is : Umair you
More content at plainenglish.io