# Anthony Lekan
# Bergen County Academies
# Intermediate

BASE_DIAGRAMS = {
	'A': ( (1,1,0,0), (1,1,0,0), (1,1,0,0), (1,1,0,0) ),
	'~A': ( (0,0,1,1), (0,0,1,1), (0,0,1,1), (0,0,1,1) ),
	'B': ( (1,1,1,1), (1,1,1,1), (0,0,0,0), (0,0,0,0) ),
	'~B': ( (0,0,0,0), (0,0,0,0), (1,1,1,1), (1,1,1,1) ),
	'C': ( (0,1,1,0), (0,1,1,0), (0,1,1,0), (0,1,1,0) ),
	'~C': ( (1,0,0,1), (1,0,0,1), (1,0,0,1), (1,0,0,1) ),
	'D': ( (0,0,0,0), (1,1,1,1), (1,1,1,1), (0,0,0,0) ),
	'~D': ( (1,1,1,1), (0,0,0,0), (0,0,0,0), (1,1,1,1) ),
}

def blank_diagram():
	return [ [0 for x in range(4)] for x in range(4) ]

def build_diagram(statement):
	final_diagram = None
	tokens = []

	negateNext = False

	# retrieve token
	for c in statement:
		if c == "~":
			negateNext = not negateNext
		elif negateNext:
			# check if positive value not in tokens
			if not c in tokens:
				tokens.append('~%s' % c)
			else:
				tokens.remove(c)

			negateNext = False
		else:
			# check if negated value not in tokens
			negated_value = '~%s' % c

			if not negated_value in tokens:
				tokens.append(c)
			else:
				tokens.remove(negated_value)

	# build diagram
	for token in tokens:
		base_diagram = BASE_DIAGRAMS[token]

		if not final_diagram is None:
			final_diagram = and_join(final_diagram, base_diagram)
		else:
			final_diagram = base_diagram

	return (final_diagram or blank_diagram())

def and_join(d1, d2):
	combined = blank_diagram()

	for row in range(0, len(combined)):
		for col in range(0, len(combined)):
			combined[row][col] = d1[row][col] and d2[row][col]

	return combined

def or_join(d1, d2):
	combined = blank_diagram()

	for row in range(0, len(combined)):
		for col in range(0, len(combined)):
			combined[row][col] = d1[row][col] or d2[row][col]

	return combined

def diagram_to_hex(diagram):
	binary_rep = []

	for row in diagram:
		joined_binary_row = ''.join([ str(x) for x in row]).zfill(4)
		binary_rep.append(joined_binary_row)

	output = str(hex(int(''.join(binary_rep), 2))).replace("0x", "").upper()

	return output.zfill(4)

def main():

	with open('3int_sampledata.txt') as file:
		for line in file:
			diagrams = []
			statements = line.strip().replace(" ", "").split('+')

			for statement in statements:
				diagrams.append(build_diagram(statement))

			final_diagram = diagrams[0]

			for i in range(1, len(diagrams)):
				diagram = diagrams[i]

				final_diagram = or_join(final_diagram, diagram)

			output = diagram_to_hex(final_diagram)
			print(output)

main()