Python template for Codeforces-manual test-

background

The background of the problem is surprisingly fun to read.

It's been a while since I've had a lot of professional competition, so I've been solving simple problems as a rehabilitation for the past few days. Since it is a good idea, I changed the environment of C ++ + Emacs that I used in the past to Python + PyCharm.

At that time, I have created a template that makes it easy to add tests (as it is), so I will post it here. Below is a description of the created template.

Targets and constraints

First of all, it is the iron rule of the competition professional to check the constraints.

This time, we will target Codeforces among the many competition pro sites. Codeforces has the following features:

  1. Communicate with standard I / O
  2. There are at most 3 test cases
  3. You can submit the file as it is

First of all, since there are few test cases available, the key is how easy it is to add your own tests. (Conversely, there is little need to automatically generate test cases from problem statements.)

The number one feature is that it becomes a bottleneck at that time. When exchanging function arguments and return values (contests such as TopCoder), you can write unit tests normally, so it is easy to receive IDE support. However, standard input / output is not supported so much, and it seems difficult to test even with jUnit. Therefore, it is necessary to take a slightly troublesome method.

Also, if you submit the file as it is, it will be easier, so I want to make it so that it can be submitted as it is.

Template made

Fit into the mold.

The introduction has become long, but I will put the template I made here. There are 2 files, One is a file that you can write the code and submit as it is, The other is a file that describes the test.

First, the file that writes the code. Don't look! After (CV: Umez), you don't need to see it while solving the problem.

main.py


# -*- coding: utf-8 -*-
import sys
#Increase the required import


class Solver(object):

    def run(self):
        ###List the answer here###


####################################
#Don't look from here!

###List the library here###

if __name__ == '__main__':
    Solver().run()

Next, the file to write the test.

test_solver.py


# -*- coding: utf-8 -*-
from unittest import TestCase


data = [
    (
        """
Input 1
""".strip()
        ,
        """
Answer 1
""".strip()
    ),

    (
        """
Input 2
""".strip()
        ,
        """
Answer 2
""".strip()
    ),
]


########################################
#Don't look from here!

class TestSolver(TestCase):
    def test_run(self):
        import os
        import sys
        from StringIO import StringIO
        import main

        for i, testdata in enumerate(data):
            print(str(i) + " test...")
            saved_stdout = sys.stdout
            try:
                with open("temp_data.txt", "w+") as temp:
                    temp.write(testdata[0])

                fd = os.open("temp_data.txt", os.O_RDONLY)
                os.dup2(fd, sys.stdin.fileno())

                out = StringIO()
                sys.stdout = out

                main.Solver().run()
                output = out.getvalue().strip()

                self.assertEquals(output, testdata[1])
            finally:
                sys.stdout = saved_stdout

Description

Running TestSolver.test_run () in test_solver.py runs the test case group defined near the beginning of the file. In this function Receives standard input from a file Redirect standard output to variables doing. This allows you to replace standard input and standard output.

Ingenuity

The test cases use here-documents, so you can easily add them by copying. No mouse training required.

Doesn't standard input need to go through a file? I thought, but for some reason I couldn't do it, so I gave up (a detailed person plz). Also, I purposely write the place that I could write using tempfile to the actual file, but Windows? In a minor OS like that, I get angry because I don't have permission to read tempfile. It's troublesome to avoid it ... I couldn't do it, so I gave up (a detailed person plz).

How to use

Almost as you can see. Basically, all you have to do is edit the area above the file.

Summary

recursive call

The template is just a file, so you can use it in combination with your favorite editor. PyCharm is easy and nice as a comfortable coder. There is auto-completion, and it's easy to execute with shortcut keys. Of course, it's also a good idea to combine it with Emacs or Vim and fight with a familiar editor. There is no point in having Emacs coming first.

Finally

This will make it even more convenient! If you have the knowledge, please comment.

Recommended Posts

Python template for Codeforces-manual test-
python unit test template
Competitive programming, coding test template: Python3
Preprocessing template for data analysis (Python)
Created AtCoder test tool for Python
python [for myself]
Template for writing batch scripts in python
Python Integrity Test
python argparse template
[Python] Tkinter template
Template for creating command line applications in Python
Python template for log analysis at explosive speed
Primality test by Python
Primality test with Python
Python basics ② for statement
Python basics 8 numpy test
Competitive Pro Template (Python)
About Python, for ~ (range)
Primality test with python
python textbook for beginners
python for android Toolchain
Python data analysis template
Jinja2 | Python template engine
python tag integration test
Python template engine empy
OpenCV for Python beginners
Test automation for work
Install Python (for Windows)
[Python] for statement error
Python environment for projects
Python memo (for myself): Array
Python list, for statement, dictionary
Python for Data Analysis Chapter 4
I touched the latest automatic test tool "Playwright for Python"
Modern Python for intermediate users
Learning flow for Python beginners
Python 3.6 installation procedure [for Windows]
Algorithm in Python (primality test)
BigQuery integration for Python users
For the G test 2020 # 2 exam
Pre-processing pipeline template for DataLiner
Python learning plan for AI learning
Set Up for Mac (Python)
Search for strings in Python
Python Tkinter notes (for myself)
OpenCV3 installation for Python3 @macOS
[Python] xmp tag for photos
Python environment construction For Mac
Test code for evaluating decorators
Techniques for sorting in Python
pp4 (python power for anything)
Python3 environment construction (for beginners)
Python 3 series installation for mac
Python #function 2 for super beginners
Basic Python grammar for beginners
3 months note for starting Python
Qt for Python app self-update
Python debug and test module
Solving 2015 Center Test for University Admissions Mathematics IIB in Python
Python for Data Analysis Chapter 2
100 Pandas knocks for Python beginners