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.0.8.51 tracks/python/exercises/wordy/example.py
trackler-2.0.8.50 tracks/python/exercises/wordy/example.py
trackler-2.0.8.49 tracks/python/exercises/wordy/example.py
trackler-2.0.8.48 tracks/python/exercises/wordy/example.py
trackler-2.0.8.47 tracks/python/exercises/wordy/example.py
trackler-2.0.8.46 tracks/python/exercises/wordy/example.py
trackler-2.0.8.45 tracks/python/exercises/wordy/example.py
trackler-2.0.8.44 tracks/python/exercises/wordy/example.py
trackler-2.0.8.43 tracks/python/exercises/wordy/example.py
trackler-2.0.8.42 tracks/python/exercises/wordy/example.py
trackler-2.0.8.41 tracks/python/exercises/wordy/example.py
trackler-2.0.8.40 tracks/python/exercises/wordy/example.py
trackler-2.0.8.39 tracks/python/exercises/wordy/example.py
trackler-2.0.8.38 tracks/python/exercises/wordy/example.py
trackler-2.0.8.37 tracks/python/exercises/wordy/example.py
trackler-2.0.8.36 tracks/python/exercises/wordy/example.py
trackler-2.0.8.35 tracks/python/exercises/wordy/example.py
trackler-2.0.8.34 tracks/python/exercises/wordy/example.py
trackler-2.0.8.33 tracks/python/exercises/wordy/example.py
trackler-2.0.8.32 tracks/python/exercises/wordy/example.py