簡體   English   中英

在Python 3中生成隨機數學

[英]Generate Random Math in Python 3

該程序將詢問用戶有關兩個數字的一​​系列問題。 這兩個數字將在1到10之間隨機生成,並會詢問用戶10次。 在這10個問題的末尾,程序將顯示從這些問題中有多少用戶正確了。 每個問題都應在決定乘積,總和或差額之間隨機決定。 將詢問的問題以及驗證用戶輸入分開。

我嘗試使用三個乘積,總和或差隨機生成。 我嘗試使用z = random.randint(1, 4)是從1是乘積,2是和或3是差中選擇,然后與變量z為1時進行乘積運算,或者如果var z為3,那么應該像x / y那樣有所不同,但是我無法確定它是否完成了它。 初次使用產品時,我有預期的結果,但是它可以工作,所以我只需要加上總和和差額即可。

產品的預期輸出某些分數測試不正確 ):

> python3 rand3.py
What is 3 x 4
Enter a number: 12
What is 3 x 7
Enter a number: 27
What is 6 x 3
Enter a number: 18
What is 7 x 10
Enter a number: 70
What is 9 x 10
Enter a number: 90
What is 9 x 7
Enter a number: 72
What is 5 x 9
Enter a number: 54
What is 6 x 8
Enter a number:
Incorrect Input!
Enter a number: 48
What is 1 x 5
Enter a number: 5
What is 10 x 3
Enter a number: 30
You got 7 correct out of 10

我的僅產品工作( 成功 ):

import random

def askNum():
  while(1):
    try:
      userInput = int(input("Enter a number: "))
      break
    except ValueError:
      print("Incorrect Input!")

  return userInput

def askQuestion():

  x = random.randint(1, 100)
  y = random.randint(1, 100)

  print("What is " + str(x) + " x " +str(y))

  u = askNum()

  if (u == x * y):
    return 1
  else:
    return 0

amount = 10
correct = 0
for i in range(amount):
  correct += askQuestion()

print("You got %d correct out of %d" % (correct, amount))

我目前的工作:(我正在努力增加總和和差額,如預期的輸出

更新 :在預期的輸出與產品很好地工作之后,所以我試圖為1-3添加z新隨機整數,這意味着我使用1表示產品,2表示和,而3表示差異,使用if語句,給定隨機選擇。 我很努力地在這里停下來,弄清楚如何隨機進行數學運算,因為我現在一個月才接觸Python。

import random

def askNum():
  while(1):
    try:
      userInput = int(input("Enter a number: "))
      break
    except ValueError:
      print("Incorrect Input!")

  return userInput

def askQuestion():

  x = random.randint(1, 10)
  y = random.randint(1, 10)
  z = random.randint(1, 4)

  print("What is " + str(x) + "  "+ str(z)+ " " +str(y))

  u = askNum()

    if (z == 1):
      x * y  #product
      return 1
    else if (z == 2):
      x + y #sum
      return 1
    else if (z == 3):
      x / y #difference
      return 1
    else
      return 0

amount = 10
correct = 0
for i in range(amount):
  correct += askQuestion()

print("You got %d correct out of %d" % (correct, amount))

輸出

md35@isu:/u1/work/python/mathquiz> python3 mathquiz.py
  File "mathquiz.py", line 27
    if (z == 1):
    ^
IndentationError: unexpected indent
md35@isu:/u1/work/python/mathquiz>

在當前輸出的情況下,我仔細檢查了正確的Python格式,所有內容都是敏感的,仍然與運行輸出相同。 任何幫助將通過解釋得到更多的贊賞。 (我希望自從我聾了以后我的英語就可以理解)我從星期六開始,比預期的准時開會。

您的問題是python 3不允許混合空格和制表符用於縮進。 使用一種編輯器來顯示使用的空白(並手動修復),或者使用一種將制表符替換為空格的編輯器。 建議使用4個空格進行縮進-有關更多樣式提示,請閱讀PEP-0008


如果您使用'+','-','*','/'而不是1,2,3,4來映射您的操作,則可以ops = random.choice("+-*/")ops = random.choice("+-*/")作為字符串給您一個運算符。 您將其輸入calc(a,ops,b)函數,並從中返回正確的結果。

您也可以縮短askNum並提供要打印的文本。

這些可能看起來像這樣:

def askNum(text):
    """Retunrs an integer from input using 'text'. Loops until valid input given."""
    while True:
        try:
            return int(input(text))
        except ValueError:
            print("Incorrect Input!")

def calc(a,ops,b):
    """Returns integer operation result from using : 'a','ops','b'"""
    if   ops == "+": return a+b
    elif ops == "-": return a-b
    elif ops == "*": return a*b
    elif ops == "/": return a//b   # integer division
    else: raise ValueError("Unsupported math operation")

最后但並非最不重要的一點是,您需要修復除法部分-您只允許使用整數輸入,因此也只能給出使用整數答案可解決的除法問題。

程序:

import random

total = 10
correct = 0
nums = range(1,11)
for _ in range(total):
    ops = random.choice("+-*/")
    a,b = random.choices(nums,k=2)

    # you only allow integer input - your division therefore is
    # limited to results that are integers - make sure that this
    # is the case here by rerolling a,b until they match
    while ops == "/" and (a%b != 0 or a<=b):
        a,b = random.choices(nums,k=2)

    # make sure not to go below 0 for -
    while ops == "-" and a<b:
        a,b = random.choices(nums,k=2)

    # as a formatted text 
    result = askNum("What is {} {} {} = ".format(a,ops,b))

    # calculate correct result
    corr = calc(a,ops,b)
    if  result == corr:
        correct += 1
        print("Correct")
    else:
        print("Wrong. Correct solution is: {} {} {} = {}".format(a,ops,b,corr))

print("You have {} out of {} correct.".format(correct,total))

輸出:

What is 8 / 1 = 3
Wrong. Correct solution is: 8 / 1 = 8
What is 5 - 3 = 3
Wrong. Correct solution is: 5 - 3 = 2
What is 4 - 2 = 3
Wrong. Correct solution is: 4 - 2 = 2
What is 3 * 1 = 3
Correct
What is 8 - 5 = 3
Correct
What is 4 / 1 = 3
Wrong. Correct solution is: 4 / 1 = 4
What is 8 * 7 = 3
Wrong. Correct solution is: 8 * 7 = 56
What is 9 + 3 = 3
Wrong. Correct solution is: 9 + 3 = 12
What is 8 - 1 = 3
Wrong. Correct solution is: 8 - 1 = 7
What is 10 / 5 = 3
Wrong. Correct solution is: 10 / 5 = 2
You have 2 out of 10 correct.
def askQuestion():
  x = random.randint(1, 10)
  y = random.randint(1, 10)
  z = random.randint(1, 4)
  print("What is " + str(x) + "  "+ str(z)+ " " +str(y))
  u = askNum()
  if (z == 1):
    x * y  #product
    return 1
  elif (z == 2):
    x + y #sum
    return 1
  elif (z == 3):
    x / y #difference
    return 1
  else:
    return 0

像這樣將您的代碼塊寫成u = askNum(),然后將if循環放在同一垂直線上。

要生成n個隨機數,可以使用

random.sample(range(from, to),how_many_numbers)

用作參考以獲取有關隨機的更多信息

import random

low=0
high=4
n=2 #no of random numbers


rand = random.sample(range(low, high), n)

#List of Operators
arithmetic_operators = ["+", "-", "/", "*"];
operator = random.randint(0, 3)

x = rand[0];
y = rand[1];
result=0;
# print(x, operator, y)

if (operator == 0):
    result = x + y# sum

elif(operator == 1):
    result = x - y# difference

elif(operator == 2):
   result= x / y#division

else :
    result=x * y# product


print("What is {} {} {}? = ".format(x,arithmetic_operators[operator],y))

以下存儲一個隨機數(int)

operator = random.randint(0, 3)

將其與運營商列表進行比較。


示例:operator = 2

elif(operator == 2):
   result= x / y#division

將執行此代碼,並且因為operator = 2,將選擇list(/)中的第三個元素

輸出:

What is 3  / 2?

暫無
暫無

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

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