I'm learning a bit of python and I'm doing the python workbook exercises . Right now I'm stuck on one called Tokenizing a String . I'm sure you know what that means . In my case the string must be a math equation and my code must tokenize it . here is my code :
def tokenizer(x):
x=x.replace(" ","")
list = []
j=0
l=len(x)
temp=""
while j < len(x):
if x[j] == "*" or x[j] == "/" or x[j] == "+" or x[j] == "-" or x[j] == "^" or x[j] == "(" or x[j] == ")":
list.append(x[j])
j=j+1
while x[j]>="0" and x[j]<="9":
temp = temp + x[j]
while j<len(x):
j=j+1
if temp!="":
list.append(temp)
temp=""
return list
def main():
x=input("Enter math expression: ")
list=tokenizer(x)
print("the tokens are: ",list)
if __name__ == '__main__':
main()
So the problem is I can't find a solution where it is not running out of range . It all comes from that "while" loop . I tried the solution from the book , which was quite similar to my one , but it gives the same result . How can I avoid running out of range when I'm using while and adding to counter "j" in my case?
Thanks !!!