Sha256: 10c2de147df4f4766ed653f2efb49e632607651ac3e196bc5a1d16b8927cf47d

Contents?: true

Size: 1.08 KB

Versions: 271

Compression:

Stored size: 1.08 KB

Contents

import sys
from operator import add, mul, sub

if sys.version_info[0] == 2:
    from operator import div
else:
    from operator import floordiv as div


VALID_OPERATIONS = {"plus": add, "minus": sub,
                    "multiplied by": mul, "divided by": div}


def calculate(stmt):
    if not (stmt.startswith("What is ") and stmt.endswith("?")):
        raise ValueError("Ill-formed question")
    l = stmt[8:-1].strip().lower().split()
    if not l:
        raise ValueError("Ill-formed question")
    l.reverse()
    try:
        op1 = int(l.pop())
    except ValueError:
        raise ValueError("Ill-formed question")
    while l:
        oprt = [l.pop()]
        while l:
            try:
                next_tk = l.pop()
                op2 = int(next_tk)
                break
            except ValueError:
                oprt.append(next_tk)
        else:
            raise ValueError("Ill-formed question")
        oprt = " ".join(oprt)
        try:
            op1 = VALID_OPERATIONS[oprt](op1, op2)
        except KeyError:
            raise ValueError("Ill-formed question")
    return op1

Version data entries

271 entries across 271 versions & 1 rubygems

Version Path
trackler-2.1.0.15 tracks/python/exercises/wordy/example.py
trackler-2.1.0.14 tracks/python/exercises/wordy/example.py
trackler-2.1.0.13 tracks/python/exercises/wordy/example.py
trackler-2.1.0.12 tracks/python/exercises/wordy/example.py
trackler-2.1.0.11 tracks/python/exercises/wordy/example.py
trackler-2.1.0.10 tracks/python/exercises/wordy/example.py
trackler-2.1.0.9 tracks/python/exercises/wordy/example.py
trackler-2.1.0.8 tracks/python/exercises/wordy/example.py
trackler-2.1.0.7 tracks/python/exercises/wordy/example.py
trackler-2.1.0.6 tracks/python/exercises/wordy/example.py
trackler-2.1.0.5 tracks/python/exercises/wordy/example.py
trackler-2.1.0.4 tracks/python/exercises/wordy/example.py
trackler-2.1.0.3 tracks/python/exercises/wordy/example.py
trackler-2.1.0.2 tracks/python/exercises/wordy/example.py
trackler-2.1.0.1 tracks/python/exercises/wordy/example.py
trackler-2.1.0.0 tracks/python/exercises/wordy/example.py
trackler-2.0.8.55 tracks/python/exercises/wordy/example.py
trackler-2.0.8.54 tracks/python/exercises/wordy/example.py
trackler-2.0.8.53 tracks/python/exercises/wordy/example.py
trackler-2.0.8.52 tracks/python/exercises/wordy/example.py