thekushalghosh's blog

By thekushalghosh, 4 months ago, In English

Hello CodeForces Community,

Input / Output in Python can be sometimes time taking in cases when the input is huge or we have to output many number of lines, or a huge number of arrays(lists) line after line.

I have come across many questions on CodeForces where the style of taking input and printing makes your code quite faster.

For Input :-

Normally, the input is taken from STDIN in the form of String using input(). And this STDIN is provided in the Judge's file. So why not try reading the input directly from the Judge's file using the Operating system(os) module, and input / output(io) module. This reading can be done in the form of bytes.

The code for that would be :-

import io,os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

or a native method (which can be used for not too large inputs) :-

import sys
input = sys.stdin.readline

Now for Output :-

Instead of throwing the output to the STDOUT, we can try writing to the Judge's sytem file. The code for that would be to use sys.stdout.write instead of print. But remember you can only output strings using this, so convert the output to string using str or map.

Examples :-

For printing an integer, instead of

print(n)

Use :-

sys.stdout.write(str(n) + "\n")

For printing a list of integers, instead of

print(*list)

Use :-

sys.stdout.write(" ".join(map(str,list)) + "\n")

Now Program examples On CodeForces, where this was useful :-

Question 1
TLE Solution
AC Solution

Question 2
Earlier Solution
Faster Solution

 
 
 
 
  • Vote: I like it
  • +19
  • Vote: I do not like it

»
4 months ago, # |
Rev. 2   Vote: I like it +6 Vote: I do not like it

I want to add something. When using BytesIO method of input, reading strings does not work normally like the STDIN method. Rather it returns a bytecoded string (I say bytecoded string, I am not sure what it's really called).

Suppose you input a string somestring as follows, and then print it

s=input()
print(s)

It will print b'somestring' ,rather than somestring. If you want to print somestring you will have to decode the bytecoded string, and do something like this:

s=input().decode()
print(s)

So, the overall code will be:

import io,os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
s=input().decode()
print(s)

Remember this only happens in the case of strings. Integers behave normally.

»
2 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Hi, still can't solve Lonely Numbers problem with fast I/O 98989136. — My code complexity O(1e6) + O(log(1e6)), thanks. — See u tmw, I will sleep now.

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Thanks a lot! I was getting TLE of 2 sec problem. After implementing this i made it in 1091 ms. It is very very helpful when you have to take input or give output in a loop/several times.