如何将变量乘以Python中的字符?

时间:2016-05-10 02:17:38

标签: python random operators

我正在使用Python开发一个项目,它涉及随机选择一个运算符(乘法,除法,加法和减法),然后在两个整数上执行该操作。到目前为止,我的代码将以char的形式随机选择运算符。我正在努力的实际上是在做数学。这是我的代码:

from random import randint
inputA = 2
inputB = 3
output = 0

desiredOutput = 5;
#possible operations: addition, subtraction, multiplication, division

add = "+"
multiply = "*"
divide = "/"
subtract = "-"

#choose randomely between the four

chooser = randint(1,4)
chosen = add
if chooser == 1:
    chosen = add
if chooser == 2:
    chosen = multiply
if chooser == 3:
    chosen = divide
if chooser == 4:
    chosen = subtract

现在我要做的是从输入B中取输入A并分别对它进行乘法,除法,加法或减法(使用"选择"运算符")。

谢谢,Avidh

4 个答案:

答案 0 :(得分:4)

您可以执行操作,而不是将运算符存储在变量中。你的ifs会是这样的:

result = None
if chooser == 1:
    result = inputA + inputB
if chooser == 2:
    result = inputA * inputB
if chooser == 3:
    result = inputA / inputB
if chooser == 4:
    result = inputA - inputB
print(result)

答案 1 :(得分:3)

更好的方法是使用函数而不是字符串,并将操作符字符串映射到字典中的函数。

模块operator包含您需要的功能:add()sub()mul()div()。您可以设置如下字典:

import operator

ops = {'+': operator.add,
       '-': operator.sub,
       '*': operator.mul,
       '/': operator.div} 

要随机选择一个运算符,请从字典的键中随机选择:

import random

op = random.choice(ops.keys())
result = ops[op](inputA, inputB)
print('{} {} {} = {}'.format(inputA, op, inputB, result)

或者你可以使用元组列表:

ops = [('+', operator.add), ('-', operator.sub), ...]
op, func = random.choice(ops)
result = func(inputA, inputB)
print('{} {} {} = {}'.format(inputA, op, inputB, result)

答案 2 :(得分:2)

使用具有lambda函数的字典

import random

my_operators = {'+' : lambda a, b: a + b,
    '-': lambda a, b: a - b,
    '*': lambda a, b: a * b,
    '/': lambda a, b: a / b
}

actions = list(my_operators.keys())

chosen = random.choice(actions)
print (my_operators[chosen] (inputA, inputB))

请注意,python有operator module可用,您可以使用它来完成此任务:

import operator
my_operators = {'+' : operator.add,
    '-': operator.add,
    '*': operator.mul,
    '/': operator.div
}

答案 3 :(得分:0)

(这看起来像是一个家庭作业问题,但这里......)

更直接和Pythonic的方法之一是使用函数式编程样式并将每个操作与执行该函数的匿名函数(lambda)配对:

from random import choice
inputA = 2
inputB = 3
output = 0

desiredOutput = 5;
#possible operations: addition, subtraction, multiplication, division

ops = dict(
    add = ("+", lambda a,b: a+b),
    multiply = ("*", lambda a,b: a*b),
    divide = ("/", lambda a,b: a/b),
    subtract = ("-", lambda a,b: a-b),
)

#choose randomly among the four operations

symbol, function = ops[ choice(ops.keys()) ]
output = function(inputA, inputB)
print ( "{inputA} {symbol} {inputB} = {output}".format(**locals()) )

抢先罢工:任何告诉您使用execeval的人都不了解Python,如果您不明白为什么这是一个坏主意,请阅读this。 (实际上是there are reasons why they're dangerous for the real experts too。)