Skip to content

Instantly share code, notes, and snippets.

@rombr
Created June 3, 2016 14:13
Show Gist options
  • Save rombr/f4b1270c8f689a14a0bc23f99200138e to your computer and use it in GitHub Desktop.
Save rombr/f4b1270c8f689a14a0bc23f99200138e to your computer and use it in GitHub Desktop.
Gwheels test task
#!/usr/bin/env python2
# coding: utf-8
'''
Напишите функцию, получающую на входе строку,
содержащую математическое выражение в обратной польской нотации
(например, «5 8 3 + *»), и возвращающую
значение этого выражения (в примере — 55).
Run in shell:
$ ./test_task.py '5 8 3 + *'
For python -m doctest -v test_task.py
>>> compute('5 8 3 + *')
55
'''
from __future__ import unicode_literals
import sys
import operator
OPERATION_MAP = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.div,
}
def compute(record):
'''
Compute Reverse Polish notation
'''
# Need record validation and float support
operation_stack = []
for value in record.split():
if value.isdigit():
operation_stack.append(int(value))
else:
if value not in OPERATION_MAP:
raise Exception('Operation "%s" is not supported' % value)
operation_stack.append(OPERATION_MAP[value](
operation_stack.pop(),
operation_stack.pop()
))
result = operation_stack.pop()
assert not operation_stack
return result
if __name__ == '__main__':
try:
record = sys.argv[1]
except IndexError:
print('Need param')
else:
print(compute(record))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment