Sha256: 778c5d9eb1bab3992d073dbbd52dac331083b89ad9cdfb9f38edf0b7b8e4085e

Contents?: true

Size: 1.11 KB

Versions: 125

Compression:

Stored size: 1.11 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")
    words = stmt[8:-1].strip().lower().split()
    if not words:
        raise ValueError("Ill-formed question")
    words.reverse()
    try:
        op1 = int(words.pop())
    except ValueError:
        raise ValueError("Ill-formed question")
    while words:
        oprt = [words.pop()]
        while words:
            try:
                next_tk = words.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

125 entries across 125 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/python/exercises/wordy/example.py
trackler-2.2.1.179 tracks/python/exercises/wordy/example.py
trackler-2.2.1.178 tracks/python/exercises/wordy/example.py
trackler-2.2.1.177 tracks/python/exercises/wordy/example.py
trackler-2.2.1.176 tracks/python/exercises/wordy/example.py
trackler-2.2.1.175 tracks/python/exercises/wordy/example.py
trackler-2.2.1.174 tracks/python/exercises/wordy/example.py
trackler-2.2.1.173 tracks/python/exercises/wordy/example.py
trackler-2.2.1.172 tracks/python/exercises/wordy/example.py
trackler-2.2.1.171 tracks/python/exercises/wordy/example.py
trackler-2.2.1.170 tracks/python/exercises/wordy/example.py
trackler-2.2.1.169 tracks/python/exercises/wordy/example.py
trackler-2.2.1.167 tracks/python/exercises/wordy/example.py
trackler-2.2.1.166 tracks/python/exercises/wordy/example.py
trackler-2.2.1.165 tracks/python/exercises/wordy/example.py
trackler-2.2.1.164 tracks/python/exercises/wordy/example.py
trackler-2.2.1.163 tracks/python/exercises/wordy/example.py
trackler-2.2.1.162 tracks/python/exercises/wordy/example.py
trackler-2.2.1.161 tracks/python/exercises/wordy/example.py
trackler-2.2.1.160 tracks/python/exercises/wordy/example.py