2014-10-04 40 views
0
from sys import stdin 
t=int(stdin.readline()) 
while(t): 
    s=stdin.readline() 
    str = [] 
    top=-1 
    for i in range(0, len(s)): 
     c=s.index(i) 
     if(c>='a' and c<='z'): 
      print(c) 
     elif(c=='('): 
      pass 
     elif(c==')'): 
      print(str[top]) 
      top-=1 
     else: 
      top+=1 
      str[top] = c 
    t-=1 

輸入:用括號變換的代數表達式成RPN(逆波蘭表示法)形式

1 
(a+b) 

錯誤:

Traceback (most recent call last): 
    File "C:\Users\Anurag\AppData\Roaming\NetBeans\8.0.1\nb_test_runner.py", line 216, in <module> 
    module = __import__(module_name, globals(), locals(), module_name) 
    File "__pyclasspath__/opn.py", line 8, in <module> 
Finished in 0.0 seconds. 
TypeError: expected a str 
0 tests, 0 failures, 0 errors 

提供1(a+b)如上誤差輸入得到顯示之後。

+1

請不要用'str'作爲變量名:它的混亂,它阻止你使用內置'STR()'函數。 – 2014-10-04 10:24:15

回答

1

報告的錯誤發生,因爲s.index()沒有做什麼,你認爲它。 s.index(substr)返回s中substr的索引。有關詳細信息,請參閱文檔。嘗試

c = s[i] 

甚至更​​好,改變的開始for循環

for c in s: 

還有一些其他問題與您的代碼。如果str是一個空列表例如,str[top]將失敗。

下面的代碼將運行,但zstr = [None]*20行是一個創可貼的解決方案&您真的需要在這裏使用更好的邏輯。另外,你當前的算法需要將表達式加括號,這是有點限制的。

from sys import stdin 

t = int(stdin.readline()) 
while t: 
    s = stdin.readline() 
    zstr = [None]*20 
    top = -1 
    for c in s: 
     if c.islower(): 
      print(c) 
     elif c=='(': 
      pass 
     elif c==')': 
      print(zstr[top]) 
      top -= 1 
     else: 
      top += 1 
      zstr[top] = c 
    t-=1 

測試

echo -e "2\n(x-y)\n((a+b)*(c+d))" | python qtest.py

輸出

x 
y 
- 
a 
b 
+ 
c 
d 
+ 
* 

編輯

一種有效的方式來獲得在一行上所有的輸出是收集輸出字符串到一個列表,然後將它們連接成一個字符串。 OTOH,只是將它們放在一個列表中可能會有用。

而且,這是一個好主意,讓你的處理邏輯分開的輸入和輸出,其中實用。當然,對於計算器程序來說,這可能不實際。

rpntest.py

#! /usr/bin/env python 

''' Transform an algebraic expression with brackets into RPN (Reverse Polish Notation) form 
From http://stackoverflow.com/questions/26191707/transform-an-algebraic-expression-with-brackets-into-rpn-reverse-polish-notatio 
''' 

import sys 
import readline 

def to_rpn(s): 
    rpn = [] 
    zstr = [None] * 20 
    top = -1 
    for c in s: 
     if c.islower(): 
      rpn.append(c) 
      #print c 
     elif c=='(': 
      pass 
     elif c==')': 
      rpn.append(zstr[top]) 
      #print zstr[top] 
      top -= 1 
     else: 
      top += 1 
      zstr[top] = c 
    return ' '.join(rpn) 


def main(): 
    #for line in sys.stdin: 
    while True: 
     try: 
      line = raw_input() 
     except EOFError: 
      break 
     if line == '': 
      continue 
     rpn = to_rpn(line) 
     print rpn 


if __name__ == '__main__': 
    main() 

我已經改變了程序的一個小的輸入邏輯。現在您不需要指定要轉換的表達式數量。程序仍然每行讀取一個代數表達式,但忽略空行。通過導入readline,它也提供了一些行編輯功能,所以可以使用箭頭鍵。要退出程序,您需要發送文件結束信號 - 在Ctrl-D的Linux上,我認爲在Windows上它是Ctrl-Z。您仍然可以將輸入輸入到程序中,例如echo -e "(x-y)\n((a+b)*(c+d))" | python rpntest.py

+0

如何在單個語句中獲得此輸出? – MetaD 2014-10-04 15:24:51