Python Forum
[split] simple calculator
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[split] simple calculator
#8
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')
FelixLarry and rob101 like this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
[split] simple calculator - by FelixLarry - Aug-18-2022, 02:24 PM
RE: [split] simple calculator - by rob101 - Aug-18-2022, 03:38 PM
RE: [split] simple calculator - by FelixLarry - Aug-18-2022, 04:07 PM
RE: [split] simple calculator - by rob101 - Aug-18-2022, 04:42 PM
RE: [split] simple calculator - by FelixLarry - Aug-19-2022, 12:41 AM
RE: [split] simple calculator - by menator01 - Aug-19-2022, 06:29 AM
RE: [split] simple calculator - by rob101 - Aug-19-2022, 10:07 AM
RE: [split] simple calculator - by FelixLarry - Aug-19-2022, 11:15 PM
RE: [split] simple calculator - by perfringo - Aug-19-2022, 10:46 AM
RE: [split] simple calculator - by FelixLarry - Aug-20-2022, 11:34 AM
RE: [split] simple calculator - by Yoriz - Aug-19-2022, 01:22 PM
RE: [split] simple calculator - by rob101 - Aug-20-2022, 12:15 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  a simple calculator Solstice 17 8,938 Mar-10-2019, 09:15 AM
Last Post: Ablazesphere

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020