Skip to main content

MAP, LAMBDA AND SETS IN PYTHON


Hello guys, welcome to my blog. Here I am going to tell you about the map, lambda, and sets in python.

MAP FUNCTION IN PYTHON:

When working with iterables in the python-like lists, we use for loops to apply the operations on elements of the iterables, but we know that for loops in the python are quite slow. Don't worry, for this, we have MAP function in the python. Its syntax is

map(fun,iterable)

It creates a map object. The 1st argument in the map function is the operation we do on the elements of the iterable. The 2nd argument in it is iterable on which you perform the operation. The map function returns the list containing the elements on which the operation is done. Look at the below example:

l1=[1,2,3]
def func(x):
    return 2*x
l=list(map(func,l1))
print(l1)

Output:

[2,4,6]

In the above example, the function func accepts the element and returns the double of the element. To perform this operation on an iterable we loop through it. But here we used map function which performs the func operation on every element in the list and creates an object. Here, we used list(), constructor, it turns the map object into a list, which contains the elements which are the return values of func. 

LAMBDA FUNCTION IN PYTHON:

Lambda expressions in Python are similar to functions in python. Its syntax is

lambda arguments: expression

It can have any number of arguments, but it has only one expression. See the below example.

A=lambda x,y: x+y

print(A(2,5))

In the above example, the lambda function has two arguments and returns the sum of two arguments.
So, the output of the above code is 7.

WHY USE LAMBDA FUNCTIONS:

For, this you should see the below example,


l1=[1,2,3]
l=list(map(lambda x: 2*x,l1))

Output:

[2,4,6]

I think your doubt is cleared now.

SETS IN PYTHON:

Now, let us see the sets in python. A set in Python is an unordered collection of elements of any data type and it has no duplicate elements. It takes iterable as its argument. Note that each and every element in the set must be an immutable object. It takes the iterable as its argument. See the examples

s=set() #it creates an empty set , here if you print s, the output will be set()
s=set([1,2,3]) #takes the list as it's argument
s={1,2,3} #another type of declaration of sets 
print(s)

Output:
{1,2,3} 

Note that the output is the same for both the type of declarations.

l=[1,2,3,4,3,4]
s=set(l)
print(s)

Output:
{1,2,3,4}

As a set should not allow duplicate elements into it, the output will be the set of unique elements.

A set element should always be an immutable object. See the below example,

set([1,2,[1,2]]) #if you try to execute this, an error will occur
set([1,2,(2,3)]) #this will run successfully because the tuple is also an immutable object. 

There are so many methods are there in sets. To know about them, visit: https://docs.python.org/2/library/sets.html


Now, I will explain the code of Sock Merchant in Hackerrank

n=int(input())
l=list(map(int,input().split()))
l1=set(l)
f=l.count
l2=list(map(lambda x: f(x)//2,l1))
print(sum(l2))

Here, the first line will the number of socks. The second line will take the n space-separated integers describing the colors of the socks in the pile. 

In the 2nd line, the arguments in the map are int and input().split() as the input entered by the user is delimited by space we use .split() function which returns the list of elements of input of type string. The map function maps this list to int which converts the elements in the list to data type int and returns the list of elements of type int. 

In the third line, the set function returns the set of elements into the l1 variable without duplicate elements.

In the 4th line, I assigned the method of list .count() f to make the code to run faster, as we are calling this method in the 5th line, many no. of times.

In the 5th line, we are using map and lambda functions instead of a loop, and we optimized our code. Now, l2 contains the elements which are the no. of pairs of each color of sock.

In the last line, we just printed out the total no. of pairs.

THANKYOU... HOPE YOU HAVE ENJOYED MY TUTORIAL. FOR MORE, SUBSCRIBE TO MY BLOG AND GET THE EMAIL NOTIFICATIONS FOR THE LATEST POSTS. 

AND ALSO SUBSCRIBE TO MY YOUTUBE CHANNEL: https://www.youtube.com/channel/UCPnw9O8cvhX9mS195imI8Sw

FOLLOW ME ON GITHUB: https://github.com/VallamkondaNeelima/MyCodes/tree/master






























 












Comments

Popular posts from this blog

CHATBOT WITH SPEECH RECOGNITION AND PYTTSX3 USING PYTHON

NOTE: VIEW THIS POST IN DESKTOP SITE FOR THE BEST EXPERIENCE Hello guys. Welcome to my blog. Here I will explain to you how to create a chatbot that has speech as it’s both input and also output. So, let us get started. In this tutorial, I am using some of the libraries in Python like SpeechRecognition, Pyaudio, Chatterbot et cetera. I am going to explain to you how to install these libraries and work with them one by one separately and at last how to integrate them. SPEECH TO TEXT At first, you have to install the Speech Recognition library. You should not use the Python3.7 version because it does not support speech recognition. I am using a 3.6 version for this tutorial. Now, you should install the speech recognition library from the command prompt. Use the following command. pip3.6 install SpeechRecognition Now, you should install PyAudio. First, you have to find the version of your Python and also the configuration of your machine. Open your cmd and type p...

LENGTH OF LONGEST VALID SUBSTRING

GIVEN A STRING OF PARENTHESIS, PRINT THE LENGTH OF THE LONGEST BALANCED SUBSTRING . FOR EXAMPLE: GIVEN,                1.  ()() ---> 4                 2.  ()())()()() ---> 6  Brute Force Approach:   It is to find all the substrings, and check whether they are balanced or not, and simultaneously updating the result if we find a larger valid substring than the previous one. But, this takes the time of O(N^3), since finding all the substrings take O(N^2), and for each substring, to find whether it is a valid substring, it takes a time of O(N), so this constitutes a total of O(N^3).  USING STACK:  In this approach, we will maintain a stack to store the indices of the traversed opening brackets i.e., '('. [YOU WILL KNOW THE REASON SOON, KEEP READING THE POST].  And a variable res , to store the length of the longest substring known till now....

RECOGNITION OF HANDWRITTEN DIGITS(MNIST DATA) PART ONE USING PYTORCH

HELLO GUYS, IN THIS BLOG POST I WANT TO SHOW THE BASIC INTRO TO IDENTIFICATION OF HANDWRITTEN DIGITS USING PYTORCH MNIST DATA. MNIST DATA IS THE COLLECTION OF HANDWRITTEN DIGITS. MNIST CONTAINS 70,000 HANDWRITTEN DIGITS, 60,000 FOR TRAINING AND REMAINING 10,000 ARE FOR TESTING.  THE  IMAGES ARE GRAYSCALE AND 28x28 PIXELS. WE CAN DOWNLOAD THE DATASET USING THE CODE BELOW. Here, the parameters batch_size is kept to 64 so that the training images are grouped into 64 each and shuffle is kept to TRUE, such that each time we run the code it shuffles the data and returns an iterable with new groups of batch_size. As the trainloader is iterable, we are iterating through it and collecting the first batch of images and it's corresponding labels into images and labels respectively. Now, run the above code and see the output. you will see something like this. torch.Size([64, 1, 28, 28]) torch.Size([64])  It shows that there are 64 images with grayscale an...