Advertisement
Guest User

Untitled

a guest
Dec 25th, 2022
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1. # Input: Lines containing 2 1 0 - (-1) = (-2)
  2. #        e.g. 2=-01 -> 2*625 + -2*125 + -1*25 + 0*5 + 1*1 = 976
  3. # Output: Sum of values, expressed in same way
  4.  
  5. def snafu_to_decimal(s):
  6.     last_character = s[len(s) - 1]
  7.     if last_character == "2":
  8.         last_digit = 2
  9.     if last_character == "1":
  10.         last_digit = 1
  11.     if last_character == "0":
  12.         last_digit = 0
  13.     if last_character == "-":
  14.         last_digit = -1
  15.     if last_character == "=":
  16.         last_digit = -2
  17.     if len(s) == 1:
  18.         return last_digit
  19.     return 5 * snafu_to_decimal(s[0:len(s) - 1]) + last_digit
  20.  
  21. def decimal_to_snafu(i):
  22.     s = "2"
  23.     while snafu_to_decimal(s) < i:
  24.         s += "2"
  25.     for p in range(0, len(s)):
  26.         for new_digit in ["1", "0", "-", "="]:
  27.             new_s = s[0:p] + new_digit + s[p+1:len(s)]
  28.             if snafu_to_decimal(new_s) >= i:
  29.                 s = new_s
  30.     return s
  31.  
  32. total = 0
  33.  
  34. input_data = open(r"c:\users\edward\desktop\personal\aoc2022\25_input.txt")
  35. for input_line in input_data.read().splitlines():
  36.     input_line = input_line.replace("\n", "")
  37.     total += snafu_to_decimal(input_line)
  38.    
  39. print (decimal_to_snafu(total))
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement