diff options
author | William Carroll <wpcarro@gmail.com> | 2020-11-12T14·37+0000 |
---|---|---|
committer | William Carroll <wpcarro@gmail.com> | 2020-11-12T14·37+0000 |
commit | aa66d9b83d5793bdbb7fe28368e0642f7c3dceac (patch) | |
tree | a0e6ad240fe1cdfd2fcdba7266931beea9fbe0d6 /scratch/facebook/infix-to-postfix.py | |
parent | d2d772e43e0d4fb1bfaaa58d7de0c9e2cc274a25 (diff) |
Add coding exercises for Facebook interviews
Add attempts at solving coding problems to Briefcase.
Diffstat (limited to 'scratch/facebook/infix-to-postfix.py')
-rw-r--r-- | scratch/facebook/infix-to-postfix.py | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/scratch/facebook/infix-to-postfix.py b/scratch/facebook/infix-to-postfix.py new file mode 100644 index 000000000000..4c6d64494d95 --- /dev/null +++ b/scratch/facebook/infix-to-postfix.py @@ -0,0 +1,51 @@ +operators = { + '*': 1, + '+': 0, +} + +def tokenize(xs): + result = [] + i = 0 + while i < len(xs): + current = xs[i] + if current in operators.keys(): + result.append(current) + i += 1 + continue + else: + i += 1 + while i < len(xs) and xs[i] in {str(n) for n in range(10)}: + current += xs[i] + i += 1 + result.append(int(current)) + return result + +def postfix(xs): + result = [] + s = [] + for x in xs: + if x in operators.keys(): + while s and operators[s[-1]] >= operators[x]: + result.append(s.pop()) + s.append(x) + else: + result.append(x) + while s: + result.append(s.pop()) + return result + +def evaluate(xs): + s = [] + for x in xs: + print(s, x) + if x == '*': + s.append(s.pop() * s.pop()) + elif x == '+': + s.append(s.pop() + s.pop()) + else: + s.append(x) + print(s) + return s[-1] + + +print(evaluate(postfix(tokenize("12+3*10")))) |