solution.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/python3
  2. import sys
  3. import math
  4. snafu_to_base10 = { '=': -2, '-': -1, '0': 0,'1': 1,'2': 2, }
  5. base5_to_snafu = { -2: '=', -1: '-', 0: '0', 1: '1', 2: '2', }
  6. def construct_number(target, digits, num, snafu):
  7. if num < 0:
  8. return snafu, num
  9. if digits == 0:
  10. return snafu, num
  11. if target - num > 5 * 5**digits:
  12. print(target - num, 2 * 5**digits)
  13. print(target, digits, num, snafu)
  14. return snafu, num
  15. for i in [ '1', '2', '0', '-', '=' ]:
  16. diff = 5**digits * snafu_to_base10[i]
  17. if digits % 9 == 0: print(target, digits, num, snafu)
  18. curnum = num + diff
  19. new_snafu = snafu + i
  20. new_snafu, result = construct_number(target, digits - 1, curnum, new_snafu)
  21. if result == target:
  22. return new_snafu, result
  23. return snafu, -1
  24. def to_base_b(num, b):
  25. num_n = 0
  26. i = 0
  27. while num > 0:
  28. num, rem = divmod(num, b)
  29. num_n += 10**i * rem
  30. i += 1
  31. return num_n
  32. def solution():
  33. numsum = 0
  34. for line in sys.stdin:
  35. num = sum([snafu_to_base10[digit] * 5**i for i, digit in enumerate(line.strip()[::-1])])
  36. numsum += num
  37. print(num)
  38. print(numsum)
  39. #snafu, _ = construct_number(numsum, len(str(numsum)) + 5, 0, '')
  40. #snafu = snafu.lstrip('0')
  41. #print(f'the sum {numsum} has snafu number {snafu}')
  42. result = ''
  43. carry = 0
  44. for digit in str(to_base_b(numsum, 5))[::-1]:
  45. digint = int(digit) + carry
  46. if digint > 2:
  47. result += base5_to_snafu[digint - 5]
  48. carry = 1
  49. else:
  50. result += base5_to_snafu[digint]
  51. carry = 0
  52. print(result[::-1])
  53. if sys.argv[1] in '1':
  54. solution()
  55. else:
  56. solution()