簡體   English   中英

使用隨機運算符將兩個數相加

[英]Adding two numbers using a randomised operator

以下是我的代碼,它可以工作。 它創建兩個隨機數,一個隨機運算符並將它們放在一起,但是這樣做后不求和。 我需要的是程序將其識別為方程式,而不是簡單地打印出各個變量。

因此,避免混淆; 我的問題是:如何使用所選的任何operatorfirstNumbersecondNumber求和在一起,而不是簡單地將它們一起打印出來?

from random import choice
from random import randint

ranOperator = ["*", "/", "+", "-"]

def askQuestion():
    firstNumber = randint(1,10)
    secondNumber = randint(1,10)
    operator = choice(ranOperator)

    generateQuestion = ' '.join((str(firstNumber), operator, str(secondNumber)))
    print(generateQuestion)

askQuestion()

當前輸出(示例):

4 + 3

使用上面相同的數字,我想發生的事情:

7

一種不依賴eval是使用operator模塊來表示操作。

from random import choice
from random import randint
from operator import add, sub, truediv, mul

ranOperator = [add, sub, truediv, mul]

def askQuestion():
    firstNumber = randint(1,10)
    secondNumber = randint(1,10)
    the_operator = choice(ranOperator)

    result = the_operator(firstNumber, secondNumber)
    print(result)

您需要的是eval()

eval() 計算所傳遞的字符串作為Python表達式並返回結果。

from random import choice
from random import randint

ranOperator = ["*", "/", "+", "-"]

def askQuestion():
    firstNumber = randint(1,10)
    secondNumber = randint(1,10)
    operator = choice(ranOperator)

    generateQuestion = ' '.join((str(firstNumber), operator, str(secondNumber)))
    print(eval(generateQuestion))

askQuestion()

演示:

>>> eval('1+1')
2
>>> eval('5-3')
2
>>> eval('2*3')
6
>>> eval('6/3')
2

擴展dseuss的答案以合並任何函數,並通過使用字典將函數映射到其符號來打印類似數學的方程式

from random import choice
from random import randint

add = lambda x,y: x+y
substract = lambda x,y: x-y
divide = lambda x,y: x/y
multiply = lambda x,y: x*y

ranOperator = {"*":multiply, "/":divide, "+":add, "-":substract}

def askQuestion():
    firstNumber = randint(1,10)
    secondNumber = randint(1,10)
    operator_key = choice(list(ranOperator.keys()))

    answer = ranOperator[operator_key](firstNumber,secondNumber)
    print("{} {} {} = {}".format(firstNumber, operator_key, secondNumber, answer))

askQuestion()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM