Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- operator = ["(", ")", "/", "*", "+", "-", "^"]
- priorityDict = {"+": 1, "-": 1, "*": 2, "/": 2, "(": 0, "^": 3}
- def refine(f):
- f = "".join(f.strip().split())
- print(f)
- result = ""
- for char in f:
- if char in operator:
- result += " " + char + " "
- else:
- result += char
- return result.strip()
- def getPriority(operator):
- return priorityDict[operator]
- def toPostfix(f):
- result = []
- stack = []
- def processWord(word):
- if word not in operator:
- result.append(word)
- else:
- if word == "(":
- stack.append(word)
- elif word == ")":
- char = ""
- while char != "(":
- char = stack.pop()
- if char != "(":
- result.append(char)
- elif word in ["+", "-", "*", "/", "^"]:
- while stack and getPriority(word) <= getPriority(stack[-1]):
- result.append(stack.pop())
- stack.append(word)
- for word in f.split():
- processWord(word)
- while stack:
- result.append(stack.pop())
- return result
- def toInfix(fStack):
- stack = []
- for index, item in enumerate(fStack):
- if item not in operator:
- stack.append(item)
- else:
- first = stack.pop()
- second = stack.pop()
- stack.append("( " + second + " " + item + " " + first + " )")
- return stack[0]
- def getExp(fStack):
- stack = []
- for index, item in enumerate(fStack):
- if item not in operator:
- stack.append(item)
- else:
- if index == len(fStack) - 1:
- exp1 = toPostfix(refine(stack.pop()))
- exp2 = toPostfix(refine(stack.pop()))
- return (exp2, exp1)
- else:
- first = stack.pop()
- second = stack.pop()
- stack.append("( " + second + " " + item + " " + first + " )")
- def getDerivative(fStack):
- if len(fStack) == 1:
- if fStack[0] == "x":
- return ["1"]
- elif fStack[0].isnumeric:
- return ["0"]
- else:
- _operator = fStack[-1]
- exp1, exp2 = getExp(fStack)
- derivative1, derivative2 = getDerivative(exp1), getDerivative(exp2)
- print("Derivatives: ")
- print(derivative1)
- print(derivative2)
- if _operator == "+":
- return derivative1 + derivative2 + ["+"]
- elif _operator == "-":
- return derivative1 + derivative2 + ["-"]
- elif _operator == "*":
- firstExp = derivative1 + exp2 + ["*"]
- secondExp = derivative2 + exp1 + ["*"]
- return firstExp + secondExp + ["-"]
- elif _operator == "/":
- firstExp = derivative1 + exp2 + ["*"]
- secondExp = derivative2 + exp1 + ["*"]
- numerator = firstExp + secondExp + ["-"]
- denominator = secondExp + ["2"] + ["^"]
- print("Derivative Calculator Beta (default June 14) :: Tran Viet Anh")
- print("type 'operator' for help and list of math operation")
- print("f(x) = ", end="")
- function = input()
- function = refine(function)
- print("Refined function: ", function)
- toPostfix(function)
- postFixStack = toPostfix(function)
- print("Postfix stack: ", postFixStack)
- derivativeResult = getDerivative(postFixStack)
- print(toInfix(derivativeResult))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement