IKASHU's blog

By IKASHU, history, 5 months ago, In English

My friend used the same logic as me but I'm getting TLE

He is using C++ and I'm using Python. Is this a python specific issue?

His Code: 247782555

My Code: 247785278

  • Vote: I like it
  • -3
  • Vote: I do not like it

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

Python is slower than C++. Hence for the same code/logic, python code will give TLE, but C++ would pass.

»
5 months ago, # |
  Vote: I like it +51 Vote: I do not like it

Reading input using the built-in input() function is slow in Python because it flushes. You can fix this by adding something like

import sys
input = lambda: sys.stdin.readline().rstrip()

to the top of your program. Using this, your code gets AC 247808788.

  • »
    »
    5 months ago, # ^ |
      Vote: I like it +43 Vote: I do not like it

    Btw your friend using C++ has a similar problem. By switching endl to '\n' and adding

    cin.sync_with_stdio(0);
    cin.tie(0);
    

    to the start of main, the solution goes from taking 1154 ms 247782555 to 92 ms 247809134.

    • »
      »
      »
      5 months ago, # ^ |
        Vote: I like it +8 Vote: I do not like it

      Thank you, i tried it and it worked :)

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

    hello, I've seen someone also uses input = lambda: sys.stdin.buffer.read().decode(). So, which one is faster?