Issue
I'm trying to create a "math interpreter" just for fun. So first step should probably be converting user input into a format I can easily work with. Now, I got it working, it's splitting everything as expected, but I have a feeling that there's a much much much more simple way of doing it. Here's what I have:
Main function:
def main():
userInput:str = input("What problem would you like solved?\nProblem: ")
str_build:str = ""
problem_list:list = []
index:int = 0
while(index < len(userInput)):
curr_char:str = userInput[index]
if checkForSign(curr_char) == False:
str_build += curr_char
else:
if str_build != "":
problem_list.append(str_build)
problem_list.append(curr_char)
str_build = ""
index += 1
print(problem_list)
return 0
And the one that checks for operands:
def checkForSign(character: str) -> bool:
match character:
case "+":
return True
case "-":
return True
case "/":
return True
case "*":
return True
case _:
return False
So lets say the user inputs
10+2*5-534/2
Then the preferred output should be
['10', '+', '2', '*', '5', '-', '534', '/', '2']
So far I've tried regex (not much success there, but I was curios about it). Code works, I do get a nicer arrangement of the inputs, but there has to be a shorter, maybe more efficient way of doing it.
Edit: Atm it can't really do anything when it's presented with a negative number, so preferably I'd like to be able to work with those too.
Solution
If your input is solely concerned with positive integers then:
ui = input("What problem would you like solved? ")
result = [""]
for c in ui:
if c.isdecimal():
result[-1] += c
elif c in "+-*/":
result.extend([c, ""])
else:
print("Invalid formula")
break
else:
print(result)
For an input of 10+2*5-534/2 this will output:
['10', '+', '2', '*', '5', '-', '534', '/', '2']
Answered By - CtrlZ
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.