Recently I've been doing some experimenting with RPN and the shunting-yard algorithm, in order to test these systems more appropriately I planned on writing a tokenizer and then using these tokens to check validity and eventually get some output. I also think that I could use this to work with some primitive programming language, such as making a CHIP-8 assembler.
Function
The intention is for my tokenizer to separate the input string into a list of the following:
- Individual Symbols (
'(', ')', '*', etc...
) - Sequences of digits (
'1', '384', etc...
) - Sequences of characters (
'log', 'sin', 'x', etc...
)
Note that because of this sequences such as:
'3.14'
(parsed as'3', '.', '14'
)'6.02E23'
(parsed as'6', '.', '02', 'E', '23'
)
Will not come out as the numbers they represent but can be reconstructed later on.
But sequences such as '3x'
will come out as '3', 'x'
making it easier to account for multiplication of variables.
Questions
For the most part I'm quite happy with this code, a couple things that I'm interested in (alongside general review) are:
- How can I make the line
if l.isalpha() and buf.isdigit() or l.isdigit() and buf.isalpha():
more concise? - What about the
if buf: out += [buf]; buf = ''
lines? Would there be anything wrong with putting this inside a nested function intokenize
? Or wouldout, buf = out + [buf], ''
be more pythonic? - This technique makes it easier later on to identify function calls such as min, max or sin, but how would I differentiate the meanings of
'xy'
? (x*y
vs a variable actually calledxy
, also this question is less relevant in the context of programming languages which would parse'xy'
as a single token over the multiplication of 2)(This question is possibly out of scope for CR, if so this question can be removed)
The reasons for these questions specifically is that I like concise code, writing it on few lines without having any too long.
Code
def tokenize(s):
out = []
buf = ''
for l in s:
if not l.isalnum():
if buf:
out += [buf]
buf = ''
out += [l]
else:
if l.isalpha() and buf.isdigit() or l.isdigit() and buf.isalpha():
out += [buf]
buf = ''
buf += l
if buf:
out += [buf]
return out