diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2021-12-13 16:28:00 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-12-13 16:28:00 +0000 |
| commit | 3f102edbf082ea633a4f832969809eb693cf738a (patch) | |
| tree | 8f094295e5420d4ba21a45198396b649e1aebf93 /challenge-143/paulo-custodio/python/ch-1.py | |
| parent | 495113ce801fcfa3b0a8cdd8d276ae2f8c02612e (diff) | |
| parent | f0cb20786217f904bc70da6ccf9521ad50d95f31 (diff) | |
| download | perlweeklychallenge-club-3f102edbf082ea633a4f832969809eb693cf738a.tar.gz perlweeklychallenge-club-3f102edbf082ea633a4f832969809eb693cf738a.tar.bz2 perlweeklychallenge-club-3f102edbf082ea633a4f832969809eb693cf738a.zip | |
Merge pull request #5369 from pauloscustodio/devel
Add Perl and Python solution to challenge 143
Diffstat (limited to 'challenge-143/paulo-custodio/python/ch-1.py')
| -rw-r--r-- | challenge-143/paulo-custodio/python/ch-1.py | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/challenge-143/paulo-custodio/python/ch-1.py b/challenge-143/paulo-custodio/python/ch-1.py new file mode 100644 index 0000000000..a81c52fd0e --- /dev/null +++ b/challenge-143/paulo-custodio/python/ch-1.py @@ -0,0 +1,72 @@ +#!/usr/bin/python3 + +# TASK #1 > Calculator +# Submitted by: Mohammad S Anwar +# You are given a string, $s, containing mathematical expression. +# +# Write a script to print the result of the mathematical expression. To keep +# it simple, please only accept + - * (). +# +# Example 1: +# Input: $s = "10 + 20 - 5" +# Output: 25 +# Example 2: +# Input: $s = "(10 + 20 - 5) * 2" +# Output: 50 + +import sys +import re + +def expr(input): + input, value = factor(input) + while True: + input = input.strip()+" " + if input[0]=='*': + input = input[1:] + input, b = factor(input) + value *= b + elif input[0]=='/': + input = input[1:] + input, b = factor(input) + value /= b + else: + return input, value + +def factor(input): + input, value = term(input) + while True: + input = input.strip()+" " + if input[0]=='+': + input = input[1:] + input, b = term(input) + value += b + elif input[0]=='-': + input = input[1:] + input, b = term(input) + value -= b + else: + return input, value + +def term(input): + input = input.strip()+" " + match = re.match(r"[-+]?\d+", input) + if match: + value = int(match.group(0)) + input = input[match.end(0):] + return input, value + elif input[0]=='(': + input = input[1:] + input, value = expr(input) + input = input.strip()+" " + if input[0]!=')': + print("expected )") + sys.exit(1) + input = input[1:] + return input, value + else: + print("expected ( or number") + sys.exit(1) + +input = " ".join(sys.argv[1:]) +input, value = expr(input) +print(value) |
