Describe one problem to solve.
| 138 | |
| 139 | |
| 140 | class Problem: |
| 141 | """Describe one problem to solve.""" |
| 142 | |
| 143 | @classmethod |
| 144 | def from_txt_file( |
| 145 | cls, fname: str, to_dict: bool = False, translate: bool = True |
| 146 | ): |
| 147 | """Load a problem from a text file.""" |
| 148 | with open(fname, 'r') as f: |
| 149 | lines = f.read().split('\n') |
| 150 | |
| 151 | lines = [l for l in lines if l] |
| 152 | data = [ |
| 153 | cls.from_txt(url + '\n' + problem, translate) |
| 154 | for (url, problem) in reshape(lines, 2) |
| 155 | ] |
| 156 | if to_dict: |
| 157 | return cls.to_dict(data) |
| 158 | return data |
| 159 | |
| 160 | @classmethod |
| 161 | def from_txt(cls, data: str, translate: bool = True) -> Problem: |
| 162 | """Load a problem from a str object.""" |
| 163 | url = '' |
| 164 | if '\n' in data: |
| 165 | url, data = data.split('\n') |
| 166 | |
| 167 | if ' ? ' in data: |
| 168 | clauses, goal = data.split(' ? ') |
| 169 | goal = Construction.from_txt(goal) |
| 170 | else: |
| 171 | clauses, goal = data, None |
| 172 | |
| 173 | clauses = clauses.split('; ') |
| 174 | problem = Problem( |
| 175 | url=url, clauses=[Clause.from_txt(c) for c in clauses], goal=goal |
| 176 | ) |
| 177 | if translate: |
| 178 | return problem.translate() |
| 179 | return problem |
| 180 | |
| 181 | @classmethod |
| 182 | def to_dict(cls, data: list[Problem]) -> dict[str, Problem]: |
| 183 | return {p.url: p for p in data} |
| 184 | |
| 185 | def __init__(self, url: str, clauses: list[Clause], goal: Construction): |
| 186 | self.url = url |
| 187 | self.clauses = clauses |
| 188 | self.goal = goal |
| 189 | |
| 190 | def copy(self) -> Problem: |
| 191 | return Problem(self.url, list(self.clauses), self.goal) |
| 192 | |
| 193 | def translate(self) -> Problem: # to single-char point names |
| 194 | """Translate point names into alphabetical.""" |
| 195 | mapping = {} |
| 196 | clauses = [] |
| 197 |