Python Forum
[split] simple calculator
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[split] simple calculator
#11
(Aug-19-2022, 11:15 PM)FelixLarry Wrote: Thank you so much. You have made me understood concepts I have struggled so hard to understand. I will continue to stay in touch. Once again, thank you. I really appreciate.

You are most welcome and thank you for taking the time to come back and say that.

I did hesitate in posting this code as it can offend coders if their 'baby' is altered in a major way, but as you had some fundamental errors that needed correcting, a rewrite together with a full explainer, seemed to be the better option.

Continue to code and learn, applying what you've already learned.

Be safe.
FelixLarry likes this post
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#12
(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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  a simple calculator Solstice 17 8,765 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