|
1 | 1 | # |
2 | 2 | # Utility to generate code template for a question. |
3 | 3 | # |
4 | | -# Read problem description from a file. |
| 4 | +# Read from a file. |
5 | 5 | # The first line of the file is the question number. |
| 6 | +# Remaining lines are the problem's description. |
| 7 | + |
6 | 8 | # Generate an output file with the description included in a block comment. |
7 | 9 | # with each line less than 80. |
8 | 10 | # and create question function and test function. |
9 | 11 | # |
| 12 | +import os |
10 | 13 |
|
11 | | -from_file = "src/question.txt" |
12 | | -to_file = "src/daily.py" |
| 14 | +from_file = "src/utils/question.txt" |
| 15 | +to_dir = "src/" |
13 | 16 |
|
14 | 17 |
|
15 | 18 | def format_question(text: str, num: int, limit: int) -> str: |
@@ -46,30 +49,26 @@ def read_and_format(input_file, output_file): |
46 | 49 | with open(input_file, "r") as input_obj: |
47 | 50 | lines = input_obj.readlines() |
48 | 51 | text = "" |
| 52 | + suffix = "" |
49 | 53 | for i, line in enumerate(lines): |
50 | 54 | if i == 0: |
| 55 | + suffix = line.strip() |
| 56 | + while len(suffix) < 3: |
| 57 | + suffix = "0" + suffix |
51 | 58 | num = int(line.strip()) |
52 | 59 | else: |
53 | 60 | text += line |
54 | | - |
| 61 | + output_file += suffix + ".py" |
| 62 | + if os.path.isfile(output_file): |
| 63 | + print(output_file, "already exists. Do nothing.") |
| 64 | + return |
55 | 65 | output = format_question(text, num, 80) |
56 | | - test_method = "test_" + str(num) + "()" |
57 | | - with open(output_file, "a+") as output_obj: |
58 | | - output_obj.seek(0) |
59 | | - lines = output_obj.readlines() |
60 | | - for line in lines: |
61 | | - if test_method in line: |
62 | | - print( |
63 | | - "The question is already included in ", |
64 | | - output_file + ".", |
65 | | - "Do Nothing.", |
66 | | - ) |
67 | | - return |
| 66 | + with open(output_file, "w") as output_obj: |
68 | 67 | output_obj.write(output) |
69 | 68 |
|
70 | 69 |
|
71 | 70 | def generate(): |
72 | | - read_and_format(from_file, to_file) |
| 71 | + read_and_format(from_file, to_dir) |
73 | 72 |
|
74 | 73 |
|
75 | 74 | if __name__ == "__main__": |
|
0 commit comments