Created
August 22, 2018 14:58
-
-
Save khawajafarooq/53dd1fc2d6945044ac855b5936660430 to your computer and use it in GitHub Desktop.
Evaluate postfix operation
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
var Operations: [String: (Double, Double) -> Double] = [ | |
"*": { $0 * $1 }, | |
"+": { $0 + $1 }, | |
"-": { $1 - $0 }, | |
"/": { $1 / $0 } | |
] | |
let Operators = ["+", "-", "*", "/"] | |
func postfix(_ expression: String) -> Double { | |
guard !expression.isEmpty else { return 0.0 } | |
let exp = expression.components(separatedBy: " ") | |
var stack = [Double]() | |
for char in exp { | |
switch (Double(char), Operations[char]) { | |
case (.some(let number), _): stack.append(number) | |
case (_, .some(let op)): | |
let lastNumber = stack.removeLast() | |
stack.append(op(stack.last!, lastNumber)) | |
default: | |
print("Not an operand or operations") | |
} | |
} | |
return stack.last! | |
} | |
postfix("1 2 * 3 *") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment