Created
June 24, 2020 14:18
-
-
Save aksnell/2d5b9c1c808d9a16ce4e5e75d9edcf79 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
def simplify(poly): | |
poly = re.findall(r'([+-])?(\d)?([a-z]+)',poly) | |
poly_groups = [[group[0], ''.join(sorted(group[2]))] if group[0] == '-' | |
else ['+', ''.join(sorted(group[2]))] | |
for group in poly | |
for x in range(max([int(y) | |
for y in filter(lambda z: z.isdigit(), ['1',group[1]])]))] | |
new_poly = [] | |
def cancelExtra(): | |
for i in poly_groups: | |
if i[0] == '-': | |
for x in poly_groups: | |
if sorted(x[1]) == sorted(i[1]) and x[0] != '-': | |
poly_groups.remove(i) | |
poly_groups.remove(x) | |
return cancelExtra() | |
cancelExtra() | |
simple = [[i[0], str(poly_groups.count(i)), i[1]] | |
if poly_groups.count(i) > 1 | |
else [i[0], i[1]] | |
for i in poly_groups] | |
for i in simple: | |
if i not in new_poly: | |
new_poly.append(i) | |
new_poly = ''.join([''.join(x) for x in sorted(new_poly, key=lambda x: (len(x[-1]), x[-1]))]) | |
return new_poly[1::] if new_poly[0] == '+' else new_poly |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment