Created
April 15, 2021 15:26
-
-
Save mesiriak/87085d4d08abd11451768a952ddd622b to your computer and use it in GitHub Desktop.
Codewars. Python
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
from math import factorial | |
def expand(expr): | |
print(expr) | |
expr = expr.split("^") # Splitting expression | |
expr[0] = expr[0][1:-1:1] | |
m = list(expr[0]) | |
m.reverse() | |
sign = "" | |
for i in range(len(m)): | |
if m[i] == "-" or m[i] == "+": | |
if m[i] == "+": sign += "+" | |
else: sign += "-" | |
m.insert(i," ") | |
m.insert(i+2," ") | |
expr[0] = "".join(reversed(m)) | |
break | |
if expr[0].split()[0][0:-1:1] == "": a = 1 # conversion to coefficients and unknowns | |
elif expr[0].split()[0][0:-1:1] == "-" and len(expr[0].split()[0][0:-1:1]) == 1: a = -1 | |
else: a = int(expr[0].split()[0][0:-1:1]) | |
koef = expr[0].split()[0][-1] | |
if sign == "-": b = -int(expr[0].split()[2]) | |
else: b = int(expr[0].split()[2]) | |
if expr[1] == "0": return ("1") | |
elif expr[1] == "1": return ("".join(expr[0].split())) | |
elif int(b) == 0: expr[0] = "".join(expr[0].split()); return (f"{koef}^{expr[1]}") if a == 1 else (f"{str(a)+koef}^{expr[1]}") | |
pusher = [] | |
n = int(expr[1]) | |
i = 0 | |
for k in range(n+1): #newton's binomial theorem | |
val = "" | |
val += (str((factorial(n) // (factorial(k) * factorial(n-k)))*(b**k)*(a**(n-k))) + koef +f"^{n-k}") | |
if val[0] == "-": pusher.append(val) | |
else: pusher.append("+"+val) | |
res = "" | |
for i in range(len(pusher)): #conversion in string | |
if i == 0: | |
if pusher[i][1] == "1" and pusher[i][2] == koef and pusher[i][0] == "-": | |
res += (pusher[i][0]+pusher[i][2::]) | |
elif pusher[i][1] == "1" and pusher[i][2] == koef and pusher[i][0] == "+": | |
res += (pusher[i][2::]) | |
elif pusher[i][0] == "+": | |
res += pusher[i][1::] | |
else: | |
res += pusher[i] | |
elif pusher[i].split("^")[1] == "1": | |
res += pusher[i].split("^")[0] | |
elif pusher[i].split("^")[1] == "0": | |
res += (pusher[i].split("^")[0][:-1:]) | |
else: | |
res += pusher[i] | |
return res #sorry for shitty code in this kata, i hope in future ill write better |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment