我为此问题编写的一些代码有问题:
“编写一个名为calc的函数,该函数将计算一个简单的算术表达式。程序的输入将是以下形式的字符串: 操作数1操作数2 其中操作数1和操作数2是非负整数,而operator是单字符运算符,可以是+,-或*。您可以假设每个操作数和运算符之间都有一个空格。您可以进一步假设输入是有效的数学表达式,即您的程序不应对用户输入乱码的情况负责。 您的函数将返回一个整数,以使返回值等于通过将给定操作应用于给定操作数而产生的值。 示例执行:
calc("5 + 10") # 15
“ 您不得在解决方案中使用split或eval函数。 提示:这里最困难的部分是将输入字符串分成三个部分。您可以使用find和rfind函数查找第一个和最后一个空格的位置,然后使用slice运算符(即s [startindex:endindex])提取相关字符范围。使用slice运算符时,请小心避免出现一对一的错误。 提示:最好在工作时测试您的代码。第一步应该是将输入字符串分成三个部分。编写一个执行此操作的程序,让它在单独的行上打印出运算符和两个操作数,并对其进行测试,直到您确信它可以工作为止。然后,对其进行修改以执行所需的数学运算应该很简单。用几种不同的输入来测试您的程序,以确保它能按预期工作。”
这是我的代码:
def calc(exp):
operand1 = int(exp[:1])
operand2 = int(exp[4:6])
operator = exp[2:3]
if(operator == "+"):
addition = operand1+operand2
return addition
if(operator == "-"):
subtraction = operand1-operand2
return subtraction
if(operator == "*"):
multiplication = operand1*operand2
return multiplication
print(calc("5 + 10"))
print(calc("4 - 8"))
print(calc("4 * 3"))
我的代码不完全符合此问题的条件。它仅适用于一位数字。如何使我的代码适用于任何数量?
赞:
“504 + 507”
”5678 + 76890”
以此类推?
谢谢。任何帮助表示赞赏。
答案 0 :(得分:1)
您可以简单地获取字符串,并对字符串对象使用split方法,它将基于某些分隔符返回字符串列表。
例如:
=== Predictions on test data ===
inst#,actual,predicted,error,prediction
1,2:hard,2:hard,,1
2,3:none,3:none,,1
3,1:soft,1:soft,,0.8
1,2:hard,2:hard,,0.6
2,3:none,3:none,,1
3,1:soft,1:soft,,0.8
1,2:hard,3:none,+,1
2,3:none,3:none,,1
3,1:soft,1:soft,,0.8
1,2:hard,2:hard,,0.6
2,3:none,3:none,,1
3,1:soft,1:soft,,0.8
1,3:none,3:none,,1
2,3:none,2:hard,+,0.8
1,3:none,3:none,,1
2,3:none,3:none,,1
1,3:none,3:none,,1
2,3:none,3:none,,1
1,3:none,3:none,,1
2,3:none,3:none,,1
1,3:none,2:hard,+,0.8
2,3:none,1:soft,+,1
1,3:none,3:none,,1
2,1:soft,1:soft,,0.8
stringList现在将是一个列表,例如[“ 504”,“ +”,“ 507”],这是因为分隔符“”是一个空格。然后只需将stringList = "504 + 507".split(" ")
与条件一起使用即可解决问题。另外,您可以使用int(stringList [0])和int(stringList [2])将字符串转换为int对象。
编辑: 现在,我意识到您的问题是说使用find()而不是split()。只需使用上面的逻辑,而是使用find(“”)第一个空格即可。然后,您需要使用可用于find()的两个附加参数将第一个空格切开,从而找到第二个空格。
答案 1 :(得分:1)
答案在规范中:
您可以使用find和rfind函数查找第一个和最后一个空格的位置,然后使用slice运算符(即s [startindex:endindex])提取相关的字符范围。
find
和rfind
是字符串对象的方法。
答案 2 :(得分:1)
您可以使用以下代码将其分为三个部分:(注意:这不使用split或eval)
def splitExpression(e):
numbers = ["1","2","3","4","5","6","7","8","9","0"] # list of all numbers
operations = ["+","-","*","/"] # list of all operations
output = [] # output components
currentlyParsing = "number" # the component we're currently parsing
buildstring = "" # temporary variable
for c in e:
if c == " ":
continue # ignore whitespace
if currentlyParsing == "number": # we are currently parsing a number
if c in numbers:
buildstring += c # this is a number, continue
elif c in operations:
output.append(buildstring) # this component has reached it's end
buildstring = c
currentlyParsing = "operation" # we are expecting an operation now
else:
pass # unknown symbol!
elif currentlyParsing == "operation": # we are currently parsing an operation
if c in operations:
buildstring += c # this is an operation, continue
elif c in numbers:
output.append(buildstring) # this component has reached it's end
buildstring = c
currentlyParsing = "number" # we are expecting a number now
else:
pass # unknown symbol!
if buildstring: # anything left in the buffer?
output.append(buildstring)
buildstring = ""
return output
用法:splitExpression("281*14")
返回["281","*","14"]
此功能还接受数字和运算符之间的空格
答案 3 :(得分:1)
如提示所述,获取表达式的第一个和最后一个空格的位置,使用它来提取操作数和运算符,然后进行相应的计算。
def calc(exp):
#Get the position for first space with find
low_idx = exp.find(' ')
#Get the position for last space with rfind
high_idx = exp.rfind(' ')
#Extract operators and operand with slice, converting operands to int
operand1 = int(exp[0:low_idx])
operator = exp[low_idx+1:high_idx]
operand2 = int(exp[high_idx:])
result = 0
#Evaluate based on operator
if operator == '+':
result = operand1 + operand2
elif operator == '-':
result = operand1 - operand2
elif operator == '*':
result = operand1 * operand2
return result
print(calc("5 + 10"))
print(calc("4 - 8"))
print(calc("4 * 3"))
print(calc("504 + 507"))
print(calc("5678 + 76890"))
#15
#-4
#12
#1011
#82568
答案 4 :(得分:0)
您需要拆分字符串,而不是对索引位置进行硬编码。 在编码时,您想尝试使代码尽可能动态,这通常意味着不能硬编码可能是变量的东西,或者在这种情况下,不能从空格中获取
。此外,在if语句中,我将它们修改为elif,因为它都是一个包含的语句,因此应分组。
def calc(exp):
vals = exp.split(' ')
operand1 = int(vals[0])
operand2 = int(vals[2])
operator = vals[1]
if operator == '+':
return operand1+operand2
elif operator == '-':
return operand1-operand2
else:
return operand1*operand2