Competitive Programming with Python for Beginners : Getting Started 2

Greetings

I suppose that you have read Python for Competitive Programming : Getting Started 1. If not, kindly go to the link -

So, now we have a task to input a list of numbers
For eg, if we have to input the list -

1 2 3 4 5 6 7 8 9 10

We can use input().split(), but that would return [‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘10’].

Notice that all numbers are of string datatype.

Well, we can use the int() function whenever we refer to an item in this list in a program, but wouldn’t it be a headache?

Or if you are smart enough, you can obviously run a ‘for loop’, converting all datatypes from str to int of that list. But that would be time-consuming, and competitive programming is all about time complexity!

Here comes to rescue, the map() function.

The map() function takes 2 parameters, another function, and an iterable datatype. (Eg - List)

The map() function calls another function on each element of the iterable.

Many pieces of information coming together in your mind?

Nice. We are going all fine…

So, returning back to the map() function.

Now, if we have the list [‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘10’] we can use int() function on each element of that list.

That would be map(int,[‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘10’]).
That would return us with <map object at 0x105938b38>.
But that is not what we want?

Well, the map function returns us the id of the result.

So, we can simply use the list() function to convert it to a list.
easy - peasy!

Notice that we didn’t use the parenthesis with the function in the map function. This is because parenthesis is used for the object to come in, on which the function is to be called. But, with the map function, the objected is presented with a comma (’,’).

We can also use any other user-defined function also, give it a shot!

Now, summarising the article, we can input a list with calling a function on each element of that list by using map() function. But, remember to use list() function with the map() function.

Finally, for a list of integers, use
list(map(int,input().split()))

Notice how we also used input().split() also in the same line of code? Well, this saves memory by not declaring a variable for the old list. We can directly store this in a variable!

Keep following these articles to learn more tips and tricks and master competitive coding with Python !

New article arriving very soon !

Thanks for reading !

Some problems you can try now -





https://www.codechef.com/problems/WATSCORE



You can always refer to the editorials if you get stuck anywhere!

Do not hesitate to ask any doubts emerging in your mind!

Please Share if you like !

2 Likes

great work brother.

Thanks a Lot! More Coming Soon.

Share if you Like It !