|
| 1 | +# SOLUTION (Run: O(n), Space: O(n), N = number of characters in string) |
| 2 | +This was one given during an onsite interview at google. I did this question with recursion which I believe was a mistake. |
| 3 | +Before the interview, he said he was testing my ability to write in Python, but the recursion method wasn't a good way to show that. |
| 4 | +Now this solution is the dirty way to do, there is a cleaner pythonic method to this down below. |
| 5 | + |
| 6 | +Overall, this is a medium question, as long as you can see that stacks need to be used in one way or the other, the question is fairly straight forward. |
| 7 | + |
| 8 | +``` |
| 9 | +def calculate_string(input): |
| 10 | + num_stack, op_stack = list([0]), list(['+']) |
| 11 | + curr_index = 0 |
| 12 | + while curr_index < len(input): |
| 13 | + #print(num_stack, op_stack) |
| 14 | + ch = input[curr_index] |
| 15 | + if ch.isnumeric(): |
| 16 | + operator = op_stack.pop() |
| 17 | + num1 = num_stack.pop() |
| 18 | + num2 = int(ch) |
| 19 | + result = get_result(num1, num2, operator) |
| 20 | + num_stack.append(result) |
| 21 | + elif ch == '[': |
| 22 | + curr_index += 1 |
| 23 | + num = int(input[curr_index]) |
| 24 | + num_stack.append(num) |
| 25 | + elif ch == ']': |
| 26 | + num2 = num_stack.pop() |
| 27 | + num1 = num_stack.pop() |
| 28 | + operator = op_stack.pop() |
| 29 | + result = get_result(num1, num2, operator) |
| 30 | + num_stack.append(result) |
| 31 | + else: # operator |
| 32 | + op_stack.append(ch) |
| 33 | + curr_index += 1 |
| 34 | + return sum(num_stack) |
| 35 | + |
| 36 | +def get_result(n1, n2, operator): |
| 37 | + if operator == '+': |
| 38 | + return n1 + n2 |
| 39 | + elif operator == '-': |
| 40 | + return n1 - n2 |
| 41 | +
|
| 42 | +assert calculate_string('1+2-[3+4]') == -4 |
| 43 | +assert calculate_string('[1-2]+[3+4]') == 6 |
| 44 | +assert calculate_string('1+2-3-4') == -4 |
| 45 | +assert calculate_string('[1-2]+3-4') == -2 |
| 46 | +assert calculate_string('[1-2]+3-4-[5-6]') == -1 |
| 47 | +assert calculate_string('[1]-[2]+[3]-[4]') == -2 |
| 48 | +assert calculate_string('-1') == -1 |
| 49 | +assert calculate_string('-1+2') == 1 |
| 50 | +``` |
| 51 | + |
| 52 | +# SOLUTION 2 (Clean Pythonic Way) |
| 53 | +Making use of a dictionary as a way to switch between cases, will greatly simplify the code. |
| 54 | +''' |
| 55 | + |
| 56 | +''' |
0 commit comments