你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])
它可以是更pythonic,但爲什麼這個代碼效率不夠?這只是一個任務,並且是一個浮球 - 這裏沒有太多的改進空間。 –
我可以看到沒有理由認爲這個代碼會有任何需要,或者事實上,任何用途都可以提高效率。這裏的限制因素是控制檯輸出的速度。 – AJMansfield
對於最大的加速,添加閃爍的燈光和戲劇性的音樂,使用戶輸入更快。 –