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.36 tracks/python/exercises/wordy/example.py
trackler-2.1.0.34 tracks/python/exercises/wordy/example.py
trackler-2.1.0.33 tracks/python/exercises/wordy/example.py
trackler-2.1.0.32 tracks/python/exercises/wordy/example.py
trackler-2.1.0.31 tracks/python/exercises/wordy/example.py
trackler-2.1.0.30 tracks/python/exercises/wordy/example.py
trackler-2.1.0.29 tracks/python/exercises/wordy/example.py
trackler-2.1.0.28 tracks/python/exercises/wordy/example.py
trackler-2.1.0.27 tracks/python/exercises/wordy/example.py
trackler-2.1.0.26 tracks/python/exercises/wordy/example.py
trackler-2.1.0.25 tracks/python/exercises/wordy/example.py
trackler-2.1.0.24 tracks/python/exercises/wordy/example.py
trackler-2.1.0.23 tracks/python/exercises/wordy/example.py
trackler-2.1.0.22 tracks/python/exercises/wordy/example.py
trackler-2.1.0.21 tracks/python/exercises/wordy/example.py
trackler-2.1.0.20 tracks/python/exercises/wordy/example.py
trackler-2.1.0.19 tracks/python/exercises/wordy/example.py
trackler-2.1.0.18 tracks/python/exercises/wordy/example.py
trackler-2.1.0.17 tracks/python/exercises/wordy/example.py
trackler-2.1.0.16 tracks/python/exercises/wordy/example.py