我正在制作一個可以加減乘除代數項的計算器。我已經做了一個可以“制作”代數項的類,現在我希望計算機向我詢問代數運算式,閱讀它,然后將其注冊為一個。(我真的不確定正確的措辭,請原諒我,我是編碼新手。)
# Make a calculator that adds, subtracts, multiplies, and divides algebraic expressions.
# An algebraic expression has: a coefficient, a variable, and a power
# Class that makes the algebraic expression
class ExpressionMaker:
# Defines the coefficient, variable, and power of the algebraic term.
def __init__(self, coefficient, variable, power):
self.coefficient = coefficient
self.variable = variable
self.power = power
# Types down/returns/defines? the whole algebraic expression as one term.
def term(self):
return "{}{}^{}".format(self.coefficient, self.variable, self.power)
# Examples of algebraic terms of varying coefficients, variables, and powers.
expression_1 = ExpressionMaker(7, "x", 1)
expression_2 = ExpressionMaker(4, "y", 1)
expression_3 = ExpressionMaker(-3, "a", 2)
# Make the program understand what the user inputs and convert it into an algebraic expression.
# Make the program add the algebraic expressions from the user.
# An algebraic term has: a coefficient, a variable, and a power.
# Let the program check if the input has those 3 and if they are in the right order.
expression_holder1 = input("What is your first algebraic expression?: ")
print("You first algebraic expression is: " expression_holder1)
我真的不知道在這之后該怎么辦。我能想到的最多的是使用“If 陳述句”來檢查是否expression_holders有整數(用于系數)、字串(用于變數),我不知道要檢查什么來檢查冪。我也不知道如何檢查訂單是否正確。例如,正確的輸入應該是7x^3,但如果他們改為鍵入x7^3. 如果輸入錯誤,我如何讓用戶知道并讓他們再次輸入?
uj5u.com熱心網友回復:
該解決方案使用正則運算式將系數和變數分開。使用磁區檢索功率。如果給定輸入的格式不正確,它會列印錯誤。
import re #adds regular expression module
#Code for class can go here
while True:
try:
expression_holder1 = input("What is your first algebraic expression?: ")
expression = expression_holder1.partition("^") #Paritions the expression using the ^, the power if stored in the 2nd index
coefficient_variable = expression[0] #THe coefficient and varible is stored in the first index
res = re.split('(\d )', coefficient_variable) #Uses regular expression to split the character and number
power = expression[2] # Stores the value of given power
coefficient = res[1] # store the value of coefficient
variable = res[2] # Stores the varible given
if power.isdigit() == False or coefficient.isdigit() == False or variable.isalpha() == False:
print("Wrong input") #prints error if the incorrect format is given
else:
break
except IndexError: #prints error if a coefficient, variable or power is missing
print("Index Error -> Wrong input")
expression1 = ExpressionMaker(coefficient, variable, power)
print(expression1.term())
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/431632.html
標籤:Python python-3.x 数学 计算器 代数
