2016-10-01 24 views
2

我有一個使數學表生成的代碼,我覺得可以減少I重複使用三個相同的代碼,但每個if/elif語句的解決方案略有不同。如何在'while'語句內的'if''elif'語句內如何濃縮'for x in range'語句

num=10 
x=str(input("Enter Math Operation (+, -, *): ")) 
while (x != "+" and x != "-" and x != "*"): 
    x=str(input("\tEnter Math Operation: ")) 
    if x=="+": 
     for table in range(1,11): 
      print(str(num),str(x),table,"=",num+table) 
    elif x=="-": 
     for table in range(1,11): 
      print(str(num),str(x),table,"=",num-table) 
    elif x=="*": 
     for table in range(1,11): 
      print(str(num),str(x),table,"=",num*table) 

請告訴我該代碼如何被壓縮。

+0

你可以做一個for循環包含了如果的,但它會用大桌子慢一點。你可以使用右側運算符的exec作爲字符串,但它會很慢並且很脆弱。你可以將一個add,subtract等函數傳遞給迭代列表的循環,但是它會過度並且更慢。總之,我認爲這裏的代碼重用量是可以接受的。幹,但不能太乾... –

回答

2

您可以使用一個查找表來存儲不同的功能

num=10 
x=str(input("Enter Math Operation (+, -, *): ")) 
while (x != "+" and x != "-" and x != "*"): 
    x=str(input("\tEnter Math Operation: ")) 
ops = { 
    '+': lambda x, y: x+y, 
    '-': lambda x, y: x-y, 
    '*': lambda x, y: x*y} 

fn = ops[x] 
for table in range(1,11): 
    print(str(num),str(x),table,"=",fn(num,table)) 
+0

他可以,但你會這樣做,在這種簡單的情況下? –

+0

@JacquesdeHooge我可能不會,但我希望代碼審查人員能夠告訴我,我重複了兩行代碼三次 - 這足以觸發DRY。如果他們這樣做,我一定會修復它。 –

+0

這是比我更好的答案 - 表而不是elif鏈更優雅。 –

2

函數是蟒蛇第一類對象。將正確的功能分配給一個變量,然後使用它。

num=10 
x=str(input("Enter Math Operation (+, -, *): ")) 
# Read operation 
while (x != "+" and x != "-" and x != "*"): 
    x=str(input("\tEnter Math Operation: ")) 
# Select appropriate function 
if x=="+": 
    op = lambda x, y : x + y 
elif x=="-": 
    op = lambda x, y : x - y 
elif x=="*": 
    op = lambda x, y : x * y 

# Use function 
for table in range(1,11): 
    val = op(num, table) 
    print(str(num), str(x),table,"=", val) 
6

你通常會做這樣的事情:

  • 商店運營商作爲一個變量

  • 功能使用字典查找運營商

  • 使用.format()而不是將大量的字符串拼在一起

  • 不要使用str()如果參數已經是一個字符串

這裏是什麼樣子:

import operator 
x = 10 
operators = { 
    '+': operator.add, 
    '-': operator.sub, 
    '*': operator.mul, 
} 
while True: 
    op_name = input('Enter Math Operation ({}): '.format(', '.join(operators))) 
    op_func = operators.get(op_name) 
    if op_func is not None: 
     break 
for y in range(1, 11): 
    print('{} {} {} = {}'.format(x, op_name, y, op_func(x, y))) 
+0

天哪,這比以前的答案質量好得多(我是其中一個的作者)!這是知道python的人和真正的專家之間的區別。 –