arpan.parikh's blog

By arpan.parikh, history, 4 years ago, In English

Hi there, I am asking for a tips/tricks or a template for python competitive that does the same. For example, One tip would be to use sys.stdin.readline instead of input cause its much faster. It costed me a few contest question before I read a bunch of comments online telling me the same. Which is why I am asking, If anyone knows a good resource or template or tips please share the same. Thanks in advance.

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

| Write comment?
»
4 years ago, # |
Rev. 2   Vote: I like it +8 Vote: I do not like it

Hi, I also started with Python, but switched to C++, because I faced the same issues. However, I did see a library called "PyRival" on github. It contains both a template using FastIO, but also some other nice stuff. I should also say, that I haven't tested it myself. Hope that helps.

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

    Thank you so much for telling me about pyrival. This makes it so much easier

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

I took some notes some time ago and would share them below. Hope it will help.

  • Use an alias for the functions that are called too many times.
  • 'Local variable lookups are much faster than global or built-in variable lookups: the Python "compiler" optimizes most function bodies so that for local variables, no dictionary lookup is necessary, but a simple array indexing operation is sufficient.'
  • Local variables are faster than global; if you use global constants in a loop, copy it to a local variable before the loop. In Python function names (global or build-in) are also global constants
  • Try to use map(), filter(), or reduce() to replace an explicit for loop, but only if you can use a built-in function: map with a built-in function beats for loop, but a for loop with in-line code beats map with a lambda function!
  • For example, if we want to convert each string in a list to upper/lower case we can do that efficiently as new_list = map(str. upper, old_list)
  • In most cases the number of input is huge. That means we have to call input() function many times to read each line. So, every time we call input() function, Python recognizes that input() is a build-in function and looks up for what input() does. After lookup is when it starts executing it. By using alias (assigning a new name to input()) we can save that lookup time.