对编程和Python有些陌生。我正在编写一个程序来接受用户输入的字符串,将字符串放入一个列表中,程序将对列表进行检查,以查看表达式是否有效。如果有效,程序将使用eval字符串并输出答案。你知道吗
问题是,我不知道如何编码两个值之间缺少的算术运算符的检查。你知道吗
我的想法是,在函数中,我需要一个for循环来遍历列表,将列表中的当前值与列表中的下一个值进行比较,如果两者都与包含运算符的运算符列表不匹配,这意味着我缺少一个运算符。你知道吗
所以我想我必须在for循环中写一个if语句来实现这一点。我还需要if语句来忽略列表中的括号(如果有的话)。但是,我不知道如何编写if语句。你知道吗
我做这件事的方法是正确的还是有更简单更好的方法?你知道吗
我在下面提供了一个代码的简化示例。谢谢。你知道吗
def missingCheck(myList, operatorList):
for currentToken in myList:
if #not able to figure out this part
count = myList.index(currentToken)
strLeft = " ".join(myList[0:count])
strRight = " ".join(myList[count:])
print("Missing operator between {} and {}".format(strLeft, strRight))
return
def main():
myList = []
operatorList = ["+", "-", "/", "//", "*"]
strInput = str("( 33 ) ( 1 )") #hardcoded for checking, values differentiated with space
myList = strInput.split(" ")
missingCheck(myList, operatorList)
#simplifed program for testing, there will be a eval(strInput) later to parse the string if the input is correct
#Program would actually ask user for input.
#strInput = str("3 4") <--- other sample input
#strInput = str(1 2 + 3) <--- other sample input
main()
目前没有回答
相关问题 更多 >
编程相关推荐