2017-12-03 114 views
0

例如,我需要 listBuilder('24+3-65*2') 返回 ['24', '+', '3', '-', '65', '*', '2']字符串列出與整數分組

我們不允許使用自定義的導入函數。我必須在沒有他們的情況下做這項工作。這是我迄今爲止...

def listBuilder(expr): 
    operators = ['+', '-', '*', '/', '^'] 
    result = [] 
    temp = [] 
    for i in range(len(expr)): 
     if expr[i] in operators: 
      result.append(expr[i]) 
     elif isNumber(expr[i]): #isNumber() returns true if the string can convert to float 
      temp += expr[i] 
      if expr[i+1] in operators: 
       tempTwo = ''.join(temp) 
       result.append(tempTwo) 
       temp = [] 
       tempTwo = [] 
      elif expr[i+1] == None: 
       break 
      else: 
       continue 

    return result 

在這一點上,我得到一個錯誤,串索引超出範圍包括expr[i+1]行。幫助將不勝感激。我一直堅持了幾個小時。

+0

也許重複的問題https://stackoverflow.com/questions/47616114/how-to-loop-over-the-elementary-arithmetic-symbols – dkato

+0

你是如何處理的負數? – RoadRunner

回答

1

您正在遍歷列表中的所有組件,包括最後一個項目,然後測試下一個項目是否爲運算符。這意味着當你的循環到達最後一個項目時,沒有更多項目要測試,因此索引錯誤。

請注意,運算符絕不會出現在表達式的末尾。也就是說,你不會得到像2+3-這樣的東西,因爲這沒有意義。因此,您可以測試除最後一個之外的所有項目:

for idx, item in enumerate(expr): 
    if item in operators or (idx == len(expr)-1): 
     result.append(item) 
    elif idx != len(expr)-1: 
     temp += item 
     if expr[idx+1] in operators: 
      tempTwo = ''.join(temp) 
      result.append(tempTwo) 
      temp = [] 
      tempTwo = [] 
     elif expr[idx+1] == None: 
      break 
     else: 
      continue 
0

我不確定這是否是最佳解決方案,但適用於特定情況。

operators = ['+', '-', '*', '/', '^'] 
s = '24+3-65*2/25' 

result = [] 
temp = '' 

for c in s: 
    if c.isdigit(): 
     temp += c 
    else: 
     result.append(temp) 
     result.append(c) 
     temp = '' 
# append the last operand to the result list 
result.append(temp) 

print result 


# Output: ['24', '+', '3', '-', '65', '*', '2', '/', '25'] 
0

我想出了一個更簡潔的函數版本,避免使用字符串標記,這在Python中更快。

您的代碼拋出了索引錯誤,因爲在上一次迭代中,您正在檢查位置i + 1處的某個東西,這是位於列表末尾的一處。該生產線

if expression[i+1] in operators: 

,因爲在最後的迭代i是最終名單索引,而檢查不存在的列表項引發錯誤。

def list_builder(expression): 
    operators = ['+','-','*','/','^'] 
    temp_string = '' 
    results = [] 

    for item in expression: 
     if item in operators: 
      if temp_string: 
       results.append(temp_string) 
       temp_string = '' 
      results.append(item) 

     else: 
      if isNumber(item): 
       temp_string = ''.join([temp_string, item]) 

    results.append(temp_string) #Put the last token in results 

    return results