如何在Python中压缩一堆函数?

时间:2015-08-24 13:46:22

标签: python

所以我试图制作一个转换单位的程序,以便我可以避免在物理课中使用因子标签方法。我已经找到了它的通用代码,但到最后我将有35个函数来定义。下面是我到目前为止的代码,每个单元我希望能够在顶部之间进行转换。在这些单位的正下方是使用这些单位的每次可能的转换麻烦的是我希望不为每个可能的转换创建函数。到目前为止我完成的代码仅适用于其中的一些单元,但可以在此链接的小饰品中找到:

             # km  &  m  &  cm  &  mm  &  M  &  ft  &  In 
#km to m   |  m to km  |  cm to km  |  mm to km  |  M to km  |  ft to km  |  In to km
#km to cm  |  m to cm  |  cm to m   |  mm to m   |  M to m   |  ft to m   |  In to m
#km to mm  |  m to mm  |  cm to mm  |  mm to cm  |  M to cm  |  ft to cm  |  In to cm
#km to M   |  m to M   |  cm to M   |  mm to M   |  M to mm  |  ft to mm  |  In to mm
#km to ft  |  m to ft  |  cm to ft  |  mm to ft  |  M to ft  |  ft to M   |  In to M
#km to In  |  m to In  |  cm to In  |  mm to In  |  M to In  |  ft to In  |  In to ft



def km_to_M_conv():
  km=float(input("How many km?"))
  result = km * .621371192
  sentence = '{} km is equal to {} M.'.format(km, result)
  print sentence

def M_to_km_conv():
  M=float(input("How many m?"))
  result = M * 1.60934
  sentence = '{} M is equal to {} km.'.format(M, result)
  print sentence

def km_to_m_conv():
  km=float(input("How many km?"))
  result = km * 1000
  sentence = '{} km is equal to {} m.'.format(km, result)
  print sentence

def mm_to_cm_conv():
  mm=float(input("How many mm?"))
  result = mm * .1
  sentence = '{} mm is equal to {} cm.'.format(mm, result)
  print sentence

def cm_to_mm_conv():
  cm=float(input("How many cm?"))
  result = cm * 10
  sentence = '{} cm  is equal to {} mm.'.format(cm, result)
  print sentence

welcome=input("What would you like to convert?")
if welcome == ("mm to cm"):
  mm_to_cm_conv()
if welcome == ("cm to mm"):
  cm_to_mm_conv()
if welcome == ("km to M"):
  km_to_M_conv()
if welcome == ("M to km"):
  M_to_km_conv()

我还是相当陌生的Python,所以请耐心等待。谢谢!

3 个答案:

答案 0 :(得分:4)

考虑公共代码:

def converter(source, target, factor):
  qty = float(input("How many %s?"))
  result = qty * factor
  print '{} {} is equal to {} {}.'.format(qty, source, result, target)

def km_to_miles(km):
   converter('km', 'miles', 0.621371)

更新

如果你想要非常聪明,你可以动态生成如下函数:

CONVERSIONS = (
    ('km', 'miles', 0.621371),
    ('metres', 'feet', 3.28084),
    ('litres', 'gallons', 0.264172),
)

for from, to, factor in CONVERSIONS:
    func_name = '%s_to_%s' % (from, to)
    func = lambda x: x * factor
    globals()[func_name] = func

    reverse_func_name = '%s_to_%s' % (to, from)
    reverse_func = lambda x: x * (1 / factor)
    globals()[reverse_func_name] = reverse_func

答案 1 :(得分:4)

我会选择一个标准长度(可能是米)并保留一个字典(如果你不知道dictionary是什么,然后查找它们/稍微有点玩,因为它们非常有用)存储每个单位在标准单位中的时间。例如:

conversion_factors_dict = {'m': 1,
                           'cm': 0.01,
                           'ft':0.305}

然后你的功能必须采用数字,“源”单位和“目的地”单位。首先将源单位转换为标准(米),然后将其转换为目标单位。例如:

def convert(number, source, destination, conversion_factors_dict):
    input_in_metres = number * conversion_factors_dict[source]
    input_in_destination_units = input_in_metres / conversion_factors_dict[destination]
    return "{}{} = {}{}".format(number, source, input_in_destination_units, destination)

答案 2 :(得分:0)

解决此问题的更好方法可能是在字典下创建针对选项的所有因素分组,然后根据用户输入调用键的相应值。它可以被视为:

factors = {'mm to cm' : 0.1, 'cm to mm' : 10, 'km to M' : .621371192} # You may like to define more conversion factors here

welcome = input("What would you like to convert?")
frm, _, to = welcome.split()
distance = input("How many "+frm+" ?")

print (str(distance)+frm+' is equal to ' +str(float(distance)*factors[welcome])+ to