2013-04-11 131 views
3

如何擺脫這段代碼中的過多重複?Python:使此代碼更緊湊?

代碼:http://pastebin.com/13e2nWM9

程序計算基於由用戶提供的數據中的運動(SUVAT方程)的方程。

我指的是截面爲:

while True: 
     a = raw_input("What is the value of a? Make sure it is in standard units, however, do not include the unit.") 
     try: 
      float(a) 
      print "a is " + str(a) + " ms^-2" 
      break 
     except: 
      print"You must enter a number. Don't include units!" 

這被重複許多次,保存爲變量時重複塊,其改變「a」和所述單元。

非常感謝。

+0

它可以是更pythonic,但爲什麼這個代碼效率不夠?這只是一個任務,並且是一個浮球 - 這裏沒有太多的改進空間。 –

+2

我可以看到沒有理由認爲這個代碼會有任何需要,或者事實上,任何用途都可以提高效率。這裏的限制因素是控制檯輸出的速度。 – AJMansfield

+4

對於最大的加速,添加閃爍的燈光和戲劇性的音樂,使用戶輸入更快。 –

回答

0

我可以看到沒有理由認爲這個代碼會有任何需要,或者事實上,任何使用,以提高效率。這裏的限制因素是控制檯輸出的速度。

但是......

如果它可以節省你是真的,真的很重要,在某種程度上,可以加速它(我覺得最大的方式,儘管它實際上可能慢下來因爲額外的幾納秒解釋)是在不同的打印語句中分別輸出打印的東西,因此它不必在內存中構造2個額外的字符串來表示"a is " + str(a)"a is " + str(a) + " ms^-2"的值。爲了節省幾個納秒,用編譯成機器碼的語言編寫程序。或者,如果您的意思是使用較少的代碼來完成同樣的事情,請像其他人所說的那樣封裝輸入。

1

不要使用原始的excepts,並封裝測試,就是這樣。 所以不是

while True: 
     a = raw_input("What is the value of a? Make sure it is in standard units, however, do not include the unit.") 
     try: 
      float(a) 
      print "a is " + str(a) + " ms^-2" 
      break 
     except: 
      print"You must enter a number. Don't include units!" 

a = my_input(valuename='a', unit='m^-2', unitformat=float) 

和my_input做測試(和提示)。

my_input可能看起來像:

def my_input(valuename, unit, unitformat=float): 
    while True: 
    val = raw_input("What is the value of %s? Make sure it is in standard units"+ 
        "(%s), however, do not include the unit." % (valuename, unit)) 
    try: 
     unitformat(val) 
    except ValueError: 
     print"You must enter a number. Don't include units!" 
    else: 
     print "%s is %s %s" % (valuename, val, unit) 
     return val 
3

這裏是一個選項,把下面的函數定義您的模塊的頂部:

def get_float(name, units): 
    prompt = "What is the value of {0}? Make sure it is in standard units, however, do not include the unit.".format(name) 
    while True: 
     val = raw_input(prompt) 
     try: 
      val = float(val) 
      print '{0} is {1} {2}'.format(name, val, units) 
      return val 
     except Exception: 
      print "You must enter a number. Don't include units!" 

這裏是你如何可以用一個例子它,下面的代碼可以取代從第72行到第100行的所有內容:

name_units_pairs = [('v', 'ms^-1'), ('a', 'ms^-2'), ('t', 's'),] 
vals = {} 
for name, units in name_units_pairs: 
    vals[name] = get_float(name, units) 
u = vals['v'] - vals['a'] * vals['t'] 
0

你c使用循環來自動化輸入,將值存儲在字典中,然後在最後進行所有的數學運算。

import math 

units = {'s': 'm', 'u': 'ms^-1', 'v': 'ms^-1', 'a': 'ms^-2', 't': 's'} 
variables = ['s', 'u', 'v', 'a', 't'] 
suvat = dict((k, None) for k in variables) 
input_variables = [] 

def pick_from_list(prompt, L): 
    while True: 
     pick = raw_input(prompt % str(L)) 
     if pick in L: 
      print "You have chosen", pick 
      return pick 
     print """Sorry, I didn't understand that, try again. Make sure your spelling is 
      correct (Case Sensitive), and that you did not inlcude the quotation marks.""" 

aim = pick_from_list("""Welcome to Mattin's SUVAT Simulator! Choose the value you are 
        trying to find. You can pick from variables %s""", 
        variables) 

for order in 'first', 'second', 'third': 
    prompt = 'Please choose which variable to input %s. You can pick from %%s' % order 
    choices = [k for k in variables if not (k is aim or k in input_variables)] 
    input_variables.append(pick_from_list(prompt, choices)) 

for v in input_variables: 
    while True: 
     raw_input("""What is the value of %s? Make sure it is in standard 
units, however, do not include the unit.""" % v) 
     try: 
      suvat[v] = float(val) 
      print "%s is %s%s" % (v, val, units[v]) 
      break 
     except: 
      print "You must enter a number. Don't include units!" 

# for readability of the maths, turn dictionary into variables 
s, u, v, a, t = [suvat[k] for k in variables] 

# (not tested) 
if s is None: 
    if t is None: 
     t = (v - u)/a 
    if v is None: 
     s = u * t + .5 * a * t * t 
    elif a is None: 
     s = .5 * (u + v) * t 
    else: 
     s = v * t - .5 * a * t * t 
if v is None: 
    if u is None: 
     u = s/t - .5 * a * t * t 
    if t is None: 
     v = math.sqrt(u * u + 2 * a * s) 
    else: 
     v = 2 * s/t - u 
if u is None: 
    if a is None: 
     a = 2 * v/t - s/(t * t) 
    u = math.sqrt(v * v - 2 * a * s) 
if a is None: 
    a = (v * v - u * u)/(2 * s) 
if t is None: 
    t = (v - u)/a 

# turn the set of variables back into a dictionary 
solutions = dict(zip(variables, [s, u, v, a, t])) 
print 'Solution: %s=%s%s' % (aim, solutions[aim], units[aim])