Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node():
- def __init__(self, char=None, copy=None):
- if char:
- self.powers = [ [int(ord(char) - ord('a') == i) for i in range(26)] ]
- self.consts = [ 1 ]
- if copy:
- self.powers = copy.powers[:]
- self.consts = copy.consts[:]
- def __pos__(self):
- return self
- def __neg__(self):
- res = Node(copy=self)
- res.consts = [-i for i in res.consts]
- return res
- def __add__(self, val):
- res = Node(copy=self)
- res.powers += val.powers
- res.consts += val.consts
- return res
- def __sub__(self, val):
- val = val.__neg__()
- return self.__add__(val)
- def __mul__(self, val):
- res = Node(copy=self)
- res.powers = [[i[k] + j[k] for k in range(26)] for i in self.powers for j in val.powers]
- res.consts = [i*j for i in self.consts for j in val.consts]
- return res
- def __str__(self):
- #return "POWS: " + str(self.powers) + "; CONSTS: " + str(self.consts)
- arr_sorted = sorted(tuple([(self.consts[i], self.powers[i]) for i in range(len(self.consts))]), key=lambda x:x[1])
- self.consts = [i[0] for i in arr_sorted]
- self.powers = [i[1] for i in arr_sorted]
- i = 0
- j = 1
- while i < len(self.powers):
- j = i+1
- const = self.consts[i]
- while j < len(self.powers) and self.powers[i] == self.powers[j]:
- const += self.consts[j]
- self.consts = self.consts[:j] + self.consts[j+1:]
- self.powers = self.powers[:j] + self.powers[j+1:]
- self.consts[i] = const
- i = j
- res = ""
- if self.consts.count(0) == len(self.consts):
- res = "0"
- else:
- for const_id in range(len(self.consts)):
- const = self.consts[const_id]
- if const != 0:
- if len(res) > 0 and const > 0:
- res += "+"
- visited = False
- if const != 1:
- if const == -1:
- res += "-"
- else:
- res += str(const)
- visited = True
- for char_id in range(26):
- power = self.powers[const_id][char_id]
- if power != 0:
- if visited:
- res += "*"
- else:
- visited = True
- res += chr(ord("a")+char_id)
- if power != 1:
- res += "^"+str(power)
- return res
- for i in range(26):
- char = chr(ord("a") + i)
- exec(char + " = Node('" + char +"')")
- i = Node("i")
- with open("input.txt", "r") as fin, open("output.txt", "w") as fout:
- x = str(eval(fin.read()))
- print(x)
- fout.write(x)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement