תיאור
מחשבון RPN פשוט,המקבל כקלט ביטוי RPN ומחזיר פתרון או תרגיל מתמטי רגיל.
מידע נוסף:
http://www.calculator.org/rpn.html רמת הקושי: קל
פתרונות
נא לצרף פתרונות כקובץ מצורף. אם הפתרונות קצרים, אפשר לשלב את הקובץ המצורף בדף עצמו על ידי תגית inline:attachment_name
1 """
2 RPN calculator
3
4 Enter numbers and operators separated by white space using RPN notation.
5
6 Example:
7 >>> 1 2 3 + -
8 4.0
9
10 By Nir Soffer <nirs at freeshell dot org>
11 """
12
13 # Strings to operations mapping
14 import operator
15 strToOperator = {
16 '+': operator.add,
17 '-': operator.sub,
18 '*': operator.mul,
19 '/': operator.div
20 }
21
22 def calc_rpn(rpn):
23 rpn = rpn.split()
24
25 # Get numbers
26 numbers = []
27 for item in rpn:
28 if not item.isdigit():
29 break
30 numbers.append(float(item))
31 # And operators
32 operators = [strToOperator[item] for item in rpn[len(numbers):]]
33
34 # Calculate - pop the last two numbers, apply the operator
35 # and append to numbers.
36 for op in operators:
37 numbers.append(op(numbers.pop(), numbers.pop()))
38 return numbers[-1]
39
40
41 while 1:
42 rpn = raw_input("Enter RPN input: ")
43 print calc_rpn(rpn)
דיון
קטגוריה היפי קטגוריה אתגרים בפייתון