Search code examples
pythondictionaryraw-input

using map(int, raw_input().split())


Though I like python very much, When I need to get multiple integer inputs in the same line, I prefer C/C++. If I use python, I use:

a = map(int, raw_input().split())

Is this the only way or is there any pythonic way to do it? And does this cost much as far as time is considered?


Solution

  • If you're using map with built-in function then it can be slightly faster than LC:

    >>> strs = " ".join(str(x) for x in xrange(10**5))
    >>> %timeit [int(x) for x in strs.split()]
    1 loops, best of 3: 111 ms per loop
    >>> %timeit map(int, strs.split())
    1 loops, best of 3: 105 ms per loop
    

    With user-defined function:

    >>> def func(x):
    ...     return int(x)
    
    >>> %timeit map(func, strs.split())
    1 loops, best of 3: 129 ms per loop
    >>> %timeit [func(x) for x in strs.split()]
    1 loops, best of 3: 128 ms per loop
    

    Python 3.3.1 comparisons:

    >>> strs = " ".join([str(x) for x in range(10**5)])
    >>> %timeit list(map(int, strs.split()))
    10 loops, best of 3: 59 ms per loop
    >>> %timeit [int(x) for x in strs.split()]
    10 loops, best of 3: 79.2 ms per loop
    
    >>> def func(x):                         
        return int(x)
    ... 
    >>> %timeit list(map(func, strs.split()))
    10 loops, best of 3: 94.6 ms per loop
    >>> %timeit [func(x) for x in strs.split()]
    1 loops, best of 3: 92 ms per loop
    

    From Python performance tips page:

    The only restriction is that the "loop body" of map must be a function call. Besides the syntactic benefit of list comprehensions, they are often as fast or faster than equivalent use of map.