thekushalghosh's blog

By thekushalghosh, history, 3 years ago, In English

Hello Codeforces Community,

Actually all of the Python users over here would agree that "sometimes" we need to write a bit long for taking input in Python, and it is also slow.

That's why I made a good template for taking Quick And Fast Input, which I would like to share.

import sys
input = sys.stdin.readline

############ ---- Input Functions ---- ############
def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(list(s[:len(s) - 1]))
def invr():
    return(map(int,input().split()))

Just paste this template at the beginning of your Code.

It comprises of 4 functions :-

1) inp — For taking integer inputs.

2) inlt — For taking List inputs.

3) insr — For taking string inputs. Actually it returns a List of Characters, instead of a string, which is easier to use in Python, because in Python, Strings are Immutable.

4) invr — For taking space seperated integer variable inputs.

The input = sys.stdin.readline is actually for Faster Inputs, because line reading through System STDIN (Standard Input) is faster in Python.

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

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

This blog may be useful.

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

I have read this before somewhere else.

  • »
    »
    3 years ago, # ^ |
    Rev. 4   Vote: I like it 0 Vote: I do not like it

    The quick input functions were made by me, which I have personally used for a long time. You may have read about the fast input through STDIN (which is obviously built-in, and I haven't made :p)

    • »
      »
      »
      2 months ago, # ^ |
        Vote: I like it -10 Vote: I do not like it

      Is it applicable in Codeforces problem solution?

      Is Sys or Numpy is installed here on Python 3 interpreter in Codeforces

      If Yes

      send me one solution link of yours like that Thanks in Advance

      • »
        »
        »
        »
        2 months ago, # ^ |
        Rev. 2   Vote: I like it -10 Vote: I do not like it

        Numpy isn't available.... But sys is.... Check any of my recent solutions :p

»
2 years ago, # |
  Vote: I like it +1 Vote: I do not like it

Thank You! This is so useful!

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

Hi, I just want to ask when to use sys.stdin.readline, because once I used it and it gave me wrong output (WA) and when I removed it, my code was Accepted. Here are my submissions:

With sys.stdin.readline: 108547882 Without: 108548171

  • »
    »
    17 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    sys.stdin.readline also reads end of line "\n" character. See here vs here

    Also, note how does the blog takes string input in insr() function. It explicitly removes the last character.

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

can anyone share the full template for Python please

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

    Check the downloads section of https://thekushalghosh.github.io

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

    I won't say my template is the best out there for Python. But I think it might be of some use to you. Sharing it below, I have made separate ones for both Codechef and Codeforces. Here you go. Hope you find it helpful :)

    # ENTER YOUR DETAILS HERE -------------------->
    '''
            // -- Template by A_*_A -- //
                                                '''
    #       <----------------------------------------
    
    # ENTER YOUR CODE HERE  -------------------->
    # sys.setrecursionlimit(1000)
    
    ''' #   0.7 sec average INTEST    -   best for Codechef
    import atexit,io,os,sys
    ss=io.BytesIO()
    _write=ss.write
    ss.write=lambda s:_write(s.encode())
    atexit.register(lambda:os.write(1,ss.getvalue()))
    y_in=open(0).read().split("\n")
    def y_inf():
        for y_id in range(len(y_in)):
            yield y_id
    y_ino=y_inf()
    input=lambda:y_in[next(y_ino)]
    # '''
    
    ''' #   1.1 sec average INTEST
    import sys
    input=sys.stdin.readline
    # input=lambda:sys.stdin.readline().rstrip("\r\n")
    # '''
    
    # ''' # REGION FASTIO   1.7 sec average INTEST    -   best for Codeforces
    import os,sys
    from io import BytesIO,IOBase
    BUFSIZ=8192
    class FastIO(IOBase):
        newlines=0
        def __init__(self,file):
            self._fd=file.fileno()
            self.buffer=BytesIO()
            self.writable="n"in file.mode or "r" not in file.mode
            self.write=self.buffer.write if self.writable else None
        def read(self):
            while True:
                b=os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZ))
                if not b:
                    break
                ptr=self.buffer.tell()
                self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr)
            self.newlines=0
            return self.buffer.read()
        def readline(self):
            while self.newlines==0:
                b=os.read(self._fd,max(os.fstat(self._fd).st_size, BUFSIZ))
                self.newlines=b.count(b"\n")+(not b)
                ptr=self.buffer.tell()
                self.buffer.seek(0, 2),self.buffer.write(b),self.buffer.seek(ptr)
            self.newlines-=1
            return self.buffer.readline()
        def flush(self):
            if self.writable:
                os.write(self._fd,self.buffer.getvalue())
                self.buffer.truncate(0),self.buffer.seek(0)
    class IOWrapper(IOBase):
        def __init__(self, file):
            self.buffer=FastIO(file)
            self.flush=self.buffer.flush
            self.writable=self.buffer.writable
            self.write=lambda s:self.buffer.write(s.encode("ascii"))
            self.read=lambda:self.buffer.read().decode("ascii")
            self.readline=lambda:self.buffer.readline().decode("ascii")
    if sys.version_info[0]<3:
        sys.stdin,sys.stdout=FastIO(sys.stdin),FastIO(sys.stdout)
    else:
        sys.stdin,sys.stdout=IOWrapper(sys.stdin),IOWrapper(sys.stdout)
    input=lambda:sys.stdin.readline().rstrip("\r\n")
    # END REGION '''
    
    #   2.1 sec average INTEST
    tcs = 1
    # tcs = int(input())
    for tc in range(tcs):
        print("Hello World!")
    
    #       <----------------------------------------
    
    # ENTER YOUR NOTES HERE -------------------->
    '''
            // -- Template by A_*_A -- //
                                                '''
    #       <----------------------------------------
    
    
    • »
      »
      »
      5 weeks ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      @a_vantik_a Thanks! though I need to understand it all, looks daunting. Do you've a blog or something of that sort explaining it in chunks? Would be of big BIG help !

      • »
        »
        »
        »
        4 weeks ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        Hey, you are welcome. I am glad you found it helpful :) I have added commments to the code below, to make it a bit easy to understand. In case you want more reference or meaning about the code, you can simply google it. I referred a lot of blogs to come up with this FASTIO :)

        # ''' # 0.65 sec - NOTE: ONLY SEND STRINGS TO STDOUT
        import atexit, io, os
        inputt = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline   # read STDIN in 1 go
        input = lambda: inputt()   # use for integer input
        # input = lambda: inputt().decode().strip()   # use for string input
        ss = io.BytesIO()
        _write = ss.write
        ss.write = lambda s: _write(s.encode())     # byte text optimization
        atexit.register(lambda: os.write(1, ss.getvalue()))     # os.write is fast!!!
        print=ss.write
        # END REGION '''
        

        Have a good day, cheers!

      • »
        »
        »
        »
        4 weeks ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        I know using Python in Codeforces on a long term basis isn't really a good idea. But I am doing it for my own research reasons. Here is the whole list of FASTIO Comparisons I did for Python3, to come up with the best case for both Codechef and Codeforces, results were taken using best of 3 runs for each template. Hope you find it helpful :)


        # ''' # FASTIO BEGINS 0.34 sec # FASTIO ENDS ''' import sys;k=int(sys.stdin.readline().split()[1]);sys.stdout.write('%d'%sum(1 for x in map(int,sys.stdin.buffer) if not x%k)) ---------------------------------------------------------------- # ''' # FASTIO BEGINS 0.37 sec import sys # FASTIO ENDS ''' _, k = map(int, sys.stdin.readline().split()) count = sum(1 for x in map(int, sys.stdin.buffer) if not x % k) sys.stdout.write(str(count)) ---------------------------------------------------------------- # ''' # FASTIO BEGINS 0.64 sec import sys input=sys.stdin.readline # FASTIO ENDS ''' y0, y1 = [int(x) for x in input().split()] c = sum(not int(input()) % y1 for i in range(y0)) print(c) ---------------------------------------------------------------- # ''' # FASTIO BEGINS 0.65 sec import atexit, io, os inputt = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline input = lambda: inputt() # int # input = lambda: inputt().decode().strip() # str ss = io.BytesIO() _write = ss.write ss.write = lambda s: _write(s.encode()) atexit.register(lambda: os.write(1, ss.getvalue())) # FASTIO ENDS ''' y0, y1 = [int(x) for x in input().split()] c = sum(not int(input()) % y1 for i in range(y0)) print(c) ---------------------------------------------------------------- # ''' # FASTIO BEGINS 0.87 sec import sys input=lambda:sys.stdin.readline() # FASTIO ENDS ''' y0, y1 = [int(x) for x in input().split()] c = sum(not int(input()) % y1 for i in range(y0)) print(c) ---------------------------------------------------------------- # ''' # FASTIO BEGINS 0.94 sec import atexit,io,os,sys ss=io.BytesIO() _write=ss.write ss.write=lambda sett:_write(sett.encode()) atexit.register(lambda:os.write(1,ss.getvalue())) y_in=open(0).read().split("\n") def y_inf(): for y_id in range(len(y_in)): yield y_id y_ino=y_inf() input=lambda:y_in[next(y_ino)] # FASTIO ENDS ''' y0, y1 = [int(x) for x in input().split()] c = sum(not int(input()) % y1 for i in range(y0)) print(c) ---------------------------------------------------------------- # ''' # FASTIO BEGINS 1.08 sec import sys input=lambda:sys.stdin.readline().rstrip("\r\n") # FASTIO ENDS ''' y0, y1 = [int(x) for x in input().split()] c = sum(not int(input()) % y1 for i in range(y0)) print(c) ---------------------------------------------------------------- # ''' # FASTIO BEGINS 1.8 sec import os,sys from io import BytesIO,IOBase BUFSIZ=8192 class FastIO(IOBase): newlines=0 def __init__(self,file): self._fd=file.fileno() self.buffer=BytesIO() self.writable="n"in file.mode or "r" not in file.mode self.write=self.buffer.write if self.writable else None def read(self): while True: b=os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZ)) if not b: break ptr=self.buffer.tell() self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr) self.newlines=0 return self.buffer.read() def readline(self): while self.newlines==0: b=os.read(self._fd,max(os.fstat(self._fd).st_size, BUFSIZ)) self.newlines=b.count(b"\n")+(not b) ptr=self.buffer.tell() self.buffer.seek(0, 2),self.buffer.write(b),self.buffer.seek(ptr) self.newlines-=1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd,self.buffer.getvalue()) self.buffer.truncate(0),self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer=FastIO(file) self.flush=self.buffer.flush self.writable=self.buffer.writable self.write=lambda sett:self.buffer.write(sett.encode("ascii")) self.read=lambda:self.buffer.read().decode("ascii") self.readline=lambda:self.buffer.readline().decode("ascii") if sys.version_info[0]<3: sys.stdin,sys.stdout=FastIO(sys.stdin),FastIO(sys.stdout) else: sys.stdin,sys.stdout=IOWrapper(sys.stdin),IOWrapper(sys.stdout) input=lambda:sys.stdin.readline().rstrip("\r\n") # FASTIO ENDS ''' y0, y1 = [int(x) for x in input().split()] c = sum(not int(input()) % y1 for i in range(y0)) print(c) ---------------------------------------------------------------- # ''' # FASTIO BEGINS 2.1 sec # FASTIO ENDS ''' y0, y1 = [int(x) for x in input().split()] c = sum(not int(input()) % y1 for i in range(y0)) print(c)