Dremov's blog

By Dremov, 14 years ago, In Russian
Кто какой шаблон использует для сдачи на питоне?

Мне на настоящий момент приходится раскомментировать строчку с чтением данных из stdin, это неудобно и потенциально можно забыть (уже один раз забывал).

Так что созрели вопросы:
1) Как сделать шаблон который подхватывает stdin, если ее запускают в тестах?
2) Как сделать так, чтобы прогонялось сразу несколько тестов и, даже, возможно писались результаты (номера не пройденных тестов)
3) Для задач с жестким тайм-лимитом, какие вы используете оптимизации? Как я понимаю полезными явлются упаковки циклов в map и использование типизированных массивов вместо стандартных питоновских листов. Что еще есть?
  • Vote: I like it
  • +6
  • Vote: I do not like it

14 years ago, # |
  Vote: I like it 0 Vote: I do not like it
Now my template is:

from sys import stdin
in = [ '', '', '' ]
# in = stdin.readlines()

def int_values(line) :
    return map( int, i.split(' ') )

lines = map( int_values, map( lambda x: x.strip(), in ) )
  • 14 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it
    with adamax help:
    we can upgrade template to

    from sys import stdin

    in_lines = ""
    if __debug__ :
        in_lines = """
    2
    3 4
    5 6
        """
        in_lines = filter( lambda x: x, map( lambda l: l.strip(), in_lines.split('\n') ) )
    else :
        in_lines = stdin.readlines()

    def int_values(line) :
        return map( int, line.split(' ') )

    lines = map( int_values, map( lambda x:x.strip(), in_lines  ) )

14 years ago, # |
  Vote: I like it 0 Vote: I do not like it
My template is fairly simple, usually something like this:

#!/usr/bin/python
import sys
n = int (sys.stdin.readline ())
a = [int (x) for x in sys.stdin.readline ()]
...

This one reads n from the first line, and then the second line consisting of some (hopefully n) integers. Just "assert len (a) == n" if not sure :) .

1) To use stdin/stdout, run your program like "python x.py <x.in >x.out". Then, fill the input in "x.in" and get output in "x.out". For convenience, "x" could be the problem letter ("a", "b", "c", etc.). You can use batch files or Far manager and keyboard shortcuts to do that.

2) To process multiple tests, the template could be extended to something like:

#!/usr/bin/python
while True:
    s = sys.stdin.readline ()
    if s == '':
       break
    n = int (s)
    a = [int (x) for x in sys.stdin.readline ()]
    ...

3) I don't use any hard-core optimizations. I just use other languages for problems where time is critical.
  • 14 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it
    I think it can be processed without any external scripting like 'python x.py <x.in >x.out'. It is simpler to have one file with code and tests in it then set of files and scripts. May be somebody knows any way?
    • 14 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it
      Wrap the solution in a function, then, and call that function with different inputs.

      One advantage of working with stdin/stdout is that you don't need to change anything when submitting your solution.

      I wonder if there's some "ONLINE_JUDGE = True" added to the program on the judge, to allow conditionally reading the input or using local tests, like:

      if ONLINE_JUDGE:
          n, a, b = read_input ()
      else:
          n, a, b = 5, [1, 2, 3, 4, 5], [2, 5, 4, 3, 1]
      • 14 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it
        The same thing I want to know. May be there is some variable like that exists in C and JAVA (I see it in somebody's java code)