【问题标题】:Choosing optional functions with parameters by user由用户选择带参数的可选函数
【发布时间】:2018-03-23 10:02:16
【问题描述】:

在 Stackoverflow 用户的帮助下,我发现了如何使用 optional functions 编写程序。但问题仍然是另一种形式:

根据以下代码,用户可以选择a,b,c函数中的每一个用于计算,可以是其中一个或全部。但是他们的参数呢? 如果我们想为所选函数中的参数导入值?

例如用户想要使用函数ac并导入不同的xyhsd。这些参数完全不同,必须由用户自己导入。 ln 将在代码中计算,而不是由用户计算。

Results=(a(x1,y1,h1,n)+c(s1,d1,l))-(a(x2,y2,h2,n)+c(s2,d2,l))) 我们的功能是:

def a(x,y,h,n):
    return x + y    
def b(z,l):
    return z - t    
def c(s,d):
    return s*d

原代码为:

def a():
       return 2 + 3

def b():
       return 3 - 2

def c():
       return 2*3

dic = {}
dic['a'] = a
dic['b'] = b
dic['c'] = c

funcs = str(input("which functions would you like to use?: "))
funcs = funcs.split(',')

result = 0

for i in funcs:
    result += dic[i]()

print (result)

【问题讨论】:

  • 您所说的“...想要导入所选函数中的参数值”到底是什么意思? import 在 Python 中的意思是非常具体的东西(实际上它是一个关键字)——你的意思是那个意义上的还是你真正的意思是“输入”?
  • @Martineau 我的意思是选择任意值。
  • 如何选择它们?

标签: python function dictionary


【解决方案1】:

如果函数的参数是固定的并且您事先知道它们,那么下面的 sn-p 可以帮助您。在 python 3.6 中尝试和测试

dic_var = {"a": ["x","y","h"],"b": ["z"], "c":["s","d"] }

funcs = ["a","c"]
for i in funcs:
    vars_here = dic_var[i]
    for item in vars_here:
        exec("{} = int(input('Input values for:{}'))".format(item, item) )

编辑:1

# Let us define n and l 
n = 10
l = 5

dic_var = {"a": ["x","y","h"],"b": ["z"], "c":["s","d"] }
execute_fun = {"a": "a(x,y,h,n)", "b": "b(z,l)", "c": "c(s,d)"}

def a(x,y,h,n):
    return x + y    
def b(z,l):
    return z - l    
def c(s,d):
    return s*d

dic = {}
dic['a'] = a
dic['b'] = b
dic['c'] = c

funcs = str(input("which functions would you like to use?: "))
funcs = funcs.split(',')

result = 0

for i in funcs:
    vars_here = dic_var[i]
    for item in vars_here:
        exec("{} = int(input('Input values for:{}'))".format(item, item) )
    exec("val = {}".format(execute_fun[i]))
    result += val

print (result)

【讨论】:

  • 谢谢,但重要的是保持不动。你的代码是否满足这个陈述? Results=(a(x1,y1,h1,n)+c(s1,d1,l))-(a(x2,y2,h2,n)+c(s2,d2,l))) 你的代码如何理解这样做?
  • x2,y2 和... 在程序中,但代码如何理解在resuts 之后在resuts 右侧选择函数ab .示例:c(s1,d1,l)+b(z1,l)-c(s2,d2,l)+b(z2,l)。减去后,方程将根据用户的选择而变化。
  • @Bob 见编辑:1
  • 对任意用户输入应用exec() 是一个(可能很严重的)安全风险。
  • @RaoSahab 亲爱的 Rao,等式在减号之前和减号之后有两部分。我们选择减号之前的函数,但减号之后的函数必须由程序选择并且相同。我现在评价了你的答案。我正好需要上面提到的等式。
猜你喜欢
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2018-06-23
  • 2016-10-12
  • 2011-01-09
  • 2014-11-23
  • 2013-09-10
相关资源
最近更新 更多