25.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import math
  2. lines = [line.strip() for line in open("25.input")]
  3. def to_dec(num):
  4. total = 0
  5. for i, c in enumerate(reversed(num)):
  6. if c in ["0", "1", "2"]:
  7. total += (5 ** i) * int(c)
  8. elif c == "-":
  9. total -= (5 ** i)
  10. elif c == "=":
  11. total -= (5 ** i) * 2
  12. return total
  13. def from_dec(num):
  14. if num == 1:
  15. return "1"
  16. rem = num
  17. exp = 0
  18. while num > to_dec("2" + "2" * exp):
  19. exp += 1
  20. result = []
  21. while exp >= 0:
  22. if rem == 0:
  23. result.append("0")
  24. elif rem >= to_dec("2" + "=" * exp):
  25. result.append("2")
  26. rem -= (5 ** exp) * 2
  27. elif rem >= to_dec("1" + "=" * exp):
  28. result.append("1")
  29. rem -= (5 ** exp) * 1
  30. elif rem <= to_dec("=" + "2" * exp):
  31. result.append("=")
  32. rem += (5 ** exp) * 2
  33. elif rem <= to_dec("-" + "2" * exp):
  34. result.append("-")
  35. rem += (5 ** exp)
  36. else:
  37. result.append("0")
  38. #print("res=", "".join(result), ", rem=", rem)
  39. exp -= 1
  40. return "".join(result)
  41. result = sum(to_dec(line) for line in lines)
  42. print(result, "=", from_dec(result))