Python Input Method for Competitive Programming:

Python is amazing, except for it is a bit slow compared to other languages like C, C++, and Java. On online coding platforms if for C/C++ time provided is X, then Python will be 5X while doing same data science functions.

For improving the speed of code execution, we have various input and output procedures.

Example:

Suppose we have to find the sum of N numbers. Firs we will input the value of N and then we will write N numbers separate by single space in a line.

Input Method for Competitive Programming in Python for Data Science

Python solutions for the above problem:

Normal Method Python (Python 2.7):

  1. raw_input(): It will take an optional prompt argument. It will also strip the trailing new line character from the string when it is return.
  2. print: It is a thin wrapper that formats the inputs and calls the write function of an object.

Input Method for Competitive Programming in Python for Data Science

A faster method by using in-built stdin, stdout (Python 2.7):
  1. stdin: It is a file object. It is the creation of another file object which could be create for reading input from the file. The file will be a standard input buffer in this case.
  2. write(‘D\n’): It is much faster than the print ‘D’ function.
  3. write(“”.join(list-comprehension)): It is an even faster method but in this memory usage is dependent on the size of the input.

Input Method for Competitive Programming in Python for Data Science

The difference in time is below:

Addition of buffered pipe io (Python 2.7):

  1. The output can be made faster simply by adding the buffered IO code before the submission code.
  2. The main benefit of BytesIO is that it implements a common-ish interface (commonly called file like object). BytesIO objects consists of an internal pointer, and for every call to read(n) the pointer will advance.
  3. The module atexit provides a simple interface for registration of functions to be called when program closes normally. Even the sys module provides a hook, sys.exitfunc but the problem is we can only register one function here. We can use the atexit registry for multiple modules and libraries simultaneously.

Note: We need to simply replace the raw_input() with input() syntax of Python 3.X for using the above codes in Python 3.X.

So, to learn more about it in python for data science, you can check this and this as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.