Home > Software design >  can somebody explain what this function does?
can somebody explain what this function does?

Time:02-12

I am doing online coding questions, and this is the recommended format to take inputs from the website:

numStudents = map(int, input().split())

I'm also wondering how I'm meant to know what type of output the website is giving if they're not directly telling me.

CodePudding user response:

numStudents = map(int, input().split())

This is just the general format they are actually not telling you to use int. You can simplify it by

numStudents = int(input().split())

They are the same. And map function is not generally used nowaydays

CodePudding user response:

Basically, map() is a function that takes two parameters, first a function and then the iterable object

map(func, iterable)

In your example, the input().split() is making a list by splitting the input whenever there is a space, so input like 78 45 12 becomes ['78','45','12'] then the map function is taking the individual splitter strings from this list then passes them to the int() function resulting in an iterable object that contains a list of integer cast numbers.

According to the example provided, the website is going to give you a string of numbers separated by whitespace as a input.

CodePudding user response:

map() function takes 2 arguments: First a function and then an iterable. It applies the function to each element in the iterable and returns a new iterable.
split() function takes a single parameter: Which character/string to split the string with. If none is specified then it defaults to whitespace(' ').
input() just asks the user to enter a line. It interprets everything as a singular string.

numStudents = map(int, input().split())

So this code asks the user to enter a line, splits this string based on whitespace and then converts each of those splitted strings to int and returns it as a new map object. It is usually followed by list() function like this to convert it into a list:

numStudents = list(map(int, input().split()))
  • Related