Last active
June 17, 2021 13:48
-
-
Save potados99/83ac3420b7948250c9d5aa00110f9d8a to your computer and use it in GitHub Desktop.
How to deal with polynomials
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
def addPoly(a: list, b: list): | |
index_a = 0 | |
index_b = 0 | |
len_a = len(a) | |
len_b = len(b) | |
result = [] | |
while True: | |
pick_from_a = a[index_a] if index_a < len_a else None | |
pick_from_b = b[index_b] if index_b < len_b else None | |
if pick_from_a is None and pick_from_b is None: | |
return result | |
if pick_from_a is None: | |
result.append(pick_from_b) | |
index_b += 1 | |
elif pick_from_b is None: | |
result.append(pick_from_a) | |
index_a += 1 | |
else: | |
if pick_from_a[0] > pick_from_b[0]: | |
result.append(pick_from_a) | |
index_a += 1 | |
elif pick_from_a[0] < pick_from_b[0]: | |
result.append(pick_from_b) | |
index_b += 1 | |
else: | |
result.append([pick_from_a[0], pick_from_a[1] + pick_from_b[1]]) | |
index_a += 1 | |
index_b += 1 | |
def multiplyPoly(a: list, b: list): | |
# 한줄솔루션 | |
# return list(map(lambda exp: [exp, sum(map(lambda term: term[1], filter(lambda term: term[0] == exp, [[from_a[0] + from_b[0], from_a[1] * from_b[1]] for from_a in a for from_b in b])))], sorted(list(set(map(lambda term: term[0], [[from_a[0] + from_b[0], from_a[1] * from_b[1]] for from_a in a for from_b in b]))), reverse=True))) | |
result = [] | |
for pick_from_a in a: | |
for pick_from_b in b: | |
result.append([ | |
pick_from_a[0] + pick_from_b[0], # 지수는 더하구 | |
pick_from_a[1] * pick_from_b[1] # 계수는 곱하구 | |
]) | |
return list(map(lambda exp: [exp, sum(map(lambda term: term[1], filter(lambda term: term[0] == exp, result)))], sorted(list(set(map(lambda term: term[0], result))), reverse=True))) | |
if __name__ == '__main__': | |
print( | |
addPoly( | |
[[5, 3], [3, 5], [1, 4], [0, 2]], | |
[[5, 2], [2, 4], [1, 3]] | |
) | |
) | |
print( | |
multiplyPoly( | |
[[5, 3], [3, 5], [1, 4], [0, 2]], | |
[[5, 2], [2, 4], [1, 3]] | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment