2016-10-26 56 views
-2

這裏的數學運算是在Python計算器代碼:簡化代碼 - 執行基於運營商

import time 
#Returns the sum of num1 and num2 
def add(num1, num2): 
    return num1 + num2 

#Returns the difference of num1 and num2 
def subtract(num1, num2): 
    return num1 - num2 

#Returns the quotient of num1 and num2 
def divide(num1, num2): 
    return num1/num2 

#Returns the product of num1 and num2 
def multiply(num1, num2): 
    return num1 * num2 

#Returns the exponentiation of num1 and num2 
def power(num1, num2): 
    return num1 ** num2 

import time 

def main(): 
    operation = input("What do you want to do? (+, -, *, /, ^): ") 
    if(operation != "+" and operation != "-" and operation != "*" and operation != "/" and operation != "^"): 
     #invalid operation 
     print("You must enter a valid operation") 
     time.sleep(3) 
    else: 
     var1 = int(input("Enter num1: ")) #variable one is identified 
     var2 = int(input("Enter num2: ")) #variable two is identified 
     if(operation == "+"): 
      print (add(var1, var2)) 
     elif(operation == "-"): 
      print (subtract(var1, var2)) 
     elif(operation == "/"): 
      print (divide(var1, var2)) 
     elif(operation == "*"): 
      print (multiply(var1, var2)) 
     else: 
      print (power(var1, var2)) 
main() 
input("Press enter to exit") 
exit() 

大約30分鐘前,我發現我的老Python的文件夾,並拍了一下從8我所有的基本腳本+個月前。我找到了我的計算器迷你腳本,並認爲在儘可能少的行中重新創建它會很有趣(我剛剛學習lambda)。這裏是我有什麼:

main = lambda operation,var1,var2: var1+var2 if operation=='+' else var1-var2 if operation=='-' else var1*var2 if operation=='*' else var1/var2 if operation=='/' else 'None' 
print(main(input('What operation would you like to perform? [+,-,*,/]: '),int(input('Enter num1: ')),int(input('Enter num2: ')))) 
input('Press enter to exit') 

我知道這是一個基於我的具體情況的個人問題,但我將不勝感激任何幫助使其縮短。有沒有辦法讓它變得更加Pythonic?我正確使用lambda?有沒有辦法處理我的縮短版本中的錯誤?任何幫助,將不勝感激。我對此很陌生。謝謝!

+1

爲了使它更Python,把方法拿過來,讓人類可讀 – Sayse

+0

此外,也許更適合[codereview.se],但發佈 – Sayse

+0

@Adler之前檢查他們的準則:新增答案。這是你需要的嗎?將答案標記爲已接受,如果您在將來以其他方式查看時獲得了您想要的內容作爲參考 –

回答

0

爲了簡化代碼,我會建議:

  1. 創建執行操作以字典的幫助功能。

    注:我根據用戶提到的要求設計lambda函數。個人而言,我會用operator

    使用operator

    import operator 
    
    def perform_operation(my_operator): 
        return { 
         '+': operator.add, 
         '-': operator.sub, 
         '*': operator.mul, 
         '/': operator.truediv, # "operator.div" in python 2 
         '^': operator.pow, 
        }.get(my_operator, '^') # using `^` as defualt value since in your 
              # "else" block you are calculating the `pow` 
    

    使用lambda

    def perform_operation(my_operator): 
        return { 
         '+': lambda x, y: x + y, 
         '-': lambda x, y: x - y, 
         '*': lambda x, y: x * y, 
         '/': lambda x, y: x/float(y), 
         '^': lambda x, y: x ** y, 
        }.get(my_operator, '^') # using `^` as defualt value since in your 
              # "else" block you are calculating the `pow()` 
    

    採樣運行:

    >>> perform_operation('/')(3, 5) 
    0.6 
    

    PS:縱觀認定中你會得到這個想法爲什麼使用operatorlambda

  2. 更新您的else塊更Python撥打電話給它爲:

    var1 = int(input("Enter num1: ")) 
    var2 = int(input("Enter num2: ")) 
    perform_operation(operation)(var1, var2) # Making call to function created above 
    # THE END - nothing more in else block 
    
  3. 簡化您的if條件有:

    if operation not in ["+", "-", "*", "/", "^"]: 
        # invalid operation 
    
+0

哇,謝謝!我不知道「操作員」,這使得一切都更容易解釋。將來我一定會使用它。 Lambda很混亂,而且往往難以閱讀。我很欣賞答案。 –

0

我知道這是一個有趣的自我挑戰(我對你壓縮它的能力印象深刻),但我不妨給你一些關於lambda和pythonicity的一般建議,就像你問的那樣。只有在你使用內聯代碼時才使用它們。

PEP-8表明使用lambda的唯一好處是它們可以嵌入到更大的表達式中。例如:

result = sorted(some_weird_iterable, key=lambda x: abs(x[0] - x[-1])) 

當你想將標識符分配給的方法,始終使用def因爲它可以讓你在堆棧跟蹤和了解有價值的信息。事實上,如果它不是最微不足道的情況,我建議完全避免使用lambda表達式,以使其更清晰地表達你正在做的事情。

def as_the_bird_flies_distance(x): 
    return abs(x[0] - x[-1]) 

result = sorted(some_weird_iterable, key=as_the_bird_flies_distance) 

製造更多「Pythonic」的概念不是縮短它。但要更易於閱讀,維護和擴展。

Python 2.7.11 (default, Jan 22 2016, 08:29:18) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import this 
The Zen of Python, by Tim Peters 

Beautiful is better than ugly. 
Explicit is better than implicit. 
Simple is better than complex. 
Complex is better than complicated. 
Flat is better than nested. 
Sparse is better than dense. 
Readability counts. 
Special cases aren't special enough to break the rules. 
Although practicality beats purity. 
Errors should never pass silently. 
Unless explicitly silenced. 
In the face of ambiguity, refuse the temptation to guess. 
There should be one-- and preferably only one --obvious way to do it. 
Although that way may not be obvious at first unless you're Dutch. 
Now is better than never. 
Although never is often better than *right* now. 
If the implementation is hard to explain, it's a bad idea. 
If the implementation is easy to explain, it may be a good idea. 
Namespaces are one honking great idea -- let's do more of those! 
+0

感謝您的提示。當我第一次發現'lambda'時,我在一個表達式的pygame文件中發現它。我很困惑爲什麼有人會讓事情變得比他們需要的更復雜,但現在我明白了。 Lambda非常有用,因爲它避免了跳來跳去(並且可以像你說的那樣將它嵌入到一行中),但是當你創建的函數並不簡單時,它會讓人感到困惑。這是lambda的想法嗎?感謝您的迴應。我終於明白爲什麼更長,更多的間隔代碼是首選。 –

+0

@AdlerWeber。如果lambda不能幫助清晰起見,請不要使用它。它會讓你的代碼更難以調試,並且在你回來之後嘗試修改它會讓你感到困惑。 – SCB