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.2.1.53 tracks/python/exercises/wordy/example.py
trackler-2.2.1.52 tracks/python/exercises/wordy/example.py
trackler-2.2.1.51 tracks/python/exercises/wordy/example.py
trackler-2.2.1.50 tracks/python/exercises/wordy/example.py
trackler-2.2.1.49 tracks/python/exercises/wordy/example.py
trackler-2.2.1.48 tracks/python/exercises/wordy/example.py
trackler-2.2.1.47 tracks/python/exercises/wordy/example.py
trackler-2.2.1.46 tracks/python/exercises/wordy/example.py
trackler-2.2.1.45 tracks/python/exercises/wordy/example.py
trackler-2.2.1.44 tracks/python/exercises/wordy/example.py
trackler-2.2.1.43 tracks/python/exercises/wordy/example.py
trackler-2.2.1.42 tracks/python/exercises/wordy/example.py
trackler-2.2.1.41 tracks/python/exercises/wordy/example.py
trackler-2.2.1.40 tracks/python/exercises/wordy/example.py
trackler-2.2.1.39 tracks/python/exercises/wordy/example.py
trackler-2.2.1.38 tracks/python/exercises/wordy/example.py
trackler-2.2.1.37 tracks/python/exercises/wordy/example.py
trackler-2.2.1.36 tracks/python/exercises/wordy/example.py
trackler-2.2.1.35 tracks/python/exercises/wordy/example.py
trackler-2.2.1.34 tracks/python/exercises/wordy/example.py