2017-06-21 63 views
0

我正在研究一個簡單的計算器,它可以帶多個數字。我從我寫的一個更簡單的計算器中獲得了所需的其他代碼。運算符問題和分解數學表達式

這段代碼試圖分解字符串。我在oper_lib變量變量 中放置運算符時遇到問題此外,我可以使用泛型變量定義函數,並在需要使用它的任何東西上調用相同的函數?

>""" basic calc - designed to take multiple >variables   """ 

    from datetime import * 

    now = datetime.now() 

    #Intro 

    print ("\n") 

    print ("Welcome to BasicCalc:Unstable! \n") 

    print ("If you need HELP, type help \n") 


    print (now) 

    #Beginning processing intake 


    ui1 = input("Please enter figure: ") 


    intake_list = ui1.split(" ") 

    lenth_list= len(intake_list) 


    if lenth_list % 2 == 0: 
     print ("invalid entry") 
    else: 
     print ("") 

    """ 
    Thoughts on this/ ideas: 

    - build a secondary math op list 
    - add two for - in loops in quick succession 
    """ 

    def do_math(intake_list): 
     """ proforms math function from a list""" 

    oper_lib = [ 
      "+" , 
      "-" , 
      "*" , 
      "/" 
       ] 


    for i in intake_list: 
     for n in i: 
      if n in oper_lib: 
       intake_list.insert(i-1 , " ") 
       intake_list.insert(i+1 , " ") 
       print(intake_list) 



    print (do_math(intake_list))  
    print (intake_list) 
    print (lenth_list) 
+0

該程序請求一個數字。這個數字是一個數字,一個表達式,是什麼?我輸入了22,然後用不同的方式輸出這三個結果:無['22'] 1.你可以給出你期望輸出結果的提示嗎? –

+0

這個想法是你輸入一個完整的表達式,每個整數/操作數之間有一個空格。該程序將其作爲一個字符串,將其分解成一個列表並處理furthor並返回一個答案。所以如果你嘗試用5-5來運行程序,> do_math應該把它分解爲> ['5',' - ','5'] – user43850

+0

我認爲你是自相矛盾的。它看起來像你試圖讓它'['5','','','','5']'。此外,'do_math(...)'將始終返回None,因爲除非您指定具有相應值的'return'關鍵字,否則函數將返回None。 – BLaZuRE

回答

0

在數學中,您遍歷用戶輸入的字符列表。如果用戶輸入'5 - 5',intake_list包含['5',' - ','5']。所以當你迭代它時,使用迭代變量i時會發生錯誤,它的值是' - '。你的程序正試圖從減1「 - 」在該行:

intake_list.insert(i-1 , " ") 

我建議這樣做:)

ui1 = input("Please enter figure: ") 

try: 
    print(eval(ui1)) 
except: 
    print("Error on input") 
sys.exit() 
0

它可以幫助,至少在開始的時候,要想到的循環遍歷「set」/「array」/「list」/ etc中的每個項目。正確的術語是for循環在提供的可迭代中的每個值上重複

for *variable* in *iterable* 
    #do something 

for listValue in [12, 'apple', 24] 
    print listValue 

上面會打印(安慰......從返回關鍵字不同)

12 
apple 
24 

然而

for listValue in '12' 
    print(listValue) 

上面會打印

12 

我我想我明白你想要什麼o做第二個循環,但你做了太多的工作,它會給你不正確的結果。 (爲自己和未來幾年/幾十年的調試提示:使用簡單輸入(例如具有0,1或2值的列表)在您的頭部或紙張上運行代碼,並充當程序並逐行運行看看它會做什麼。)你可以迭代一次字符串的次數是一次。基於以上所述,in都不會在列表中提供有關索引/鍵/「放置」的任何信息,這就是您想要插入到列表中的那種東西。

你想要做的就是抓住當前的「放置」並用迭代器上的空格包圍它。

一個簡單的解決方案可能是保留一個計數器(每個數字或運算符添加1)。這將允許您跟蹤需要爲當前值放置空間的位置。

另一種解決方案可能是統計新列表中的項目數量並根據該數量進行追加。

+0

不會第二個循環能夠迭代列表中的對象嗎?我一直試圖做到這一點無濟於事。在python中做「合法」嗎? – user43850

+0

任何對象都不是可迭代的。你想通過迭代一件事來達到什麼目的?你所做的只是'listValue ='12'',除非它是一個數字,在這種情況下你會錯誤的。 '12!='12''如果某件事是合法的並不意味着你應該這樣做。 – BLaZuRE