Aug-20-2022, 11:34 AM
(Aug-19-2022, 10:46 AM)perfringo Wrote: There is built-in operator module what can be used to map operations to specific characters:
import operator operations = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv, '**': operator.pow, '%': operator.mod, } # usage print(operations['+'](2, 3)) print(operations['-'](7, 2))For parsing input itertools.groupby can be used. We need keyfunc that keeps together digits and '.':
from itertools import groupby inputs = ('1+2', '1.22+1', '4 + 2') def keyfunc(symbol): return symbol.isdigit() or symbol == '.' for item in inputs: stream = groupby(item, key=keyfunc) parsed = (''.join(item[1]).strip() for item in stream) print(*parsed, sep='\n')
Thank you for your significant recommendations. I appreciate it.