-
[PCCP 기출문제] 4번 / 수식 복원하기코딩 테스트/Level 3 2024. 11. 21. 22:58반응형
https://school.programmers.co.kr/learn/courses/30/lessons/340210
빡 구현 문제...
코드가 지저분 ㅠ,.ㅠ
import string from functools import reduce def solution(expressions): def convert(num, base_): q, r = divmod(num, base_) if q == 0: return string.digits[r] else: return convert(q, base_) + string.digits[r] answer = [] new_expressions = [] numbers = set() for expression in expressions: left, right = expression.replace(' ', '').split('=') operator = '+' if '+' in left else '-' left_a, left_b = left.split(operator) new_expressions.append((left_a, operator, left_b, right)) numbers.update(map(int, set(expression) & set(string.digits))) equalities = (expression for expression in new_expressions if 'X' not in expression) equations = (expression for expression in new_expressions if 'X' in expression) bases_sets = [] for left_a, operator, left_b, right in equalities: temp_base_set = set() for base in range(max(numbers) + 1, 10): if operator == '+': if int(left_a, base) + int(left_b, base) == int(right, base): temp_base_set.add(base) else: if int(left_a, base) - int(left_b, base) == int(right, base): temp_base_set.add(base) bases_sets.append(temp_base_set) bases = reduce(lambda x, y: x & y, bases_sets) if bases_sets else range(max(numbers) + 1, 10) for left_a, operator, left_b, right in equations: result = set(convert((int(left_a, base) + int(left_b, base)) if operator == '+' else ( int(left_a, base) - int(left_b, base)), base) for base in bases) answer.append(f'{left_a} {operator} {left_b} = {tuple(result)[0] if len(result) == 1 else "?"}') return answer
ㅎㅎㅎ 그나마 정리..
import string from functools import reduce def solution(expressions): def convert(num, base_): q, r = divmod(num, base_) return string.digits[r] if q == 0 else convert(q, base_) + string.digits[r] answer, equalities, equations, bases_sets = [], [], [], [] max_number = 0 for expression in expressions: left_a, operator, left_b, _, right = expression.split(' ') if right != 'X': equalities.append((left_a, operator, left_b, right)) else: equations.append((left_a, operator, left_b, right)) max_number = max(max_number, *map(int, set(expression) & set(string.digits))) for left_a, operator, left_b, right in equalities: temp_base_set = set() for base in range(max_number + 1, 10): if ((operator == '+' and int(left_a, base) + int(left_b, base) == int(right, base)) or (operator == '-' and int(left_a, base) - int(left_b, base)) == int(right, base)): temp_base_set.add(base) bases_sets.append(temp_base_set) bases = reduce(lambda x, y: x & y, bases_sets) if bases_sets else range(max_number + 1, 10) for left_a, operator, left_b, right in equations: result = set(convert((int(left_a, base) + int(left_b, base)) if operator == '+' else ( int(left_a, base) - int(left_b, base)), base) for base in bases) answer.append(f'{left_a} {operator} {left_b} = {tuple(result)[0] if len(result) == 1 else "?"}') return answer
반응형