Skip to content

Instantly share code, notes, and snippets.

@JarkoDubbeldam
Created December 25, 2022 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JarkoDubbeldam/e7498cf6a7342a13a8def97d09fda515 to your computer and use it in GitHub Desktop.
Save JarkoDubbeldam/e7498cf6a7342a13a8def97d09fda515 to your computer and use it in GitHub Desktop.
VALUES = {"2": 2, "1": 1, "0": 0, "-": -1, "=": -2}
LETTERS = {2: "2", 1: "1", 0: "0", -1: "-", -2: "="}
def add_snafu(left: str, right: str) -> str:
carry = 0
left_list, right_list = list(left), list(right)
sum = []
while left_list or right_list or carry:
try:
left_value = VALUES[left_list.pop()]
except IndexError:
left_value = 0
try:
right_value = VALUES[right_list.pop()]
except IndexError:
right_value = 0
value = left_value + right_value + carry
if value > 2:
value -= 5
carry = 1
elif value < -2:
value += 5
carry = -1
else:
carry = 0
sum.append(value)
return "".join([LETTERS[value] for value in sum[::-1]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment