[ale] Python: help me??--I think I got it!

David Jackson deepbsd.ale at gmail.com
Wed Jun 17 18:31:04 EDT 2015


So, when I first read the lesson and did the assignment, I was very sleep
deprived.  My tests and methods were pretty convoluted.  I cleaned up the
tests, and I think they're passing now.  I'm not sure why, but I moved the
tests for Composable(pwr) down to the test_exceptions section, the tests
passed.  And everything looked less "Sleep Deprived"!  :-)

But, any hints or tips?  I am wide open to improvement here.

Thanks!

*** composable.py ***
#!/usr/bin/env python3

"""
composable.py: defines a composable function class.
"""

import types

class Composable:
    def __init__(self, f):
        "Store reference to proxied function."
        self.func = f

    def __call__(self, *args, **kwargs):
        "Proxy the function, passing all arguments through."
        return self.func(*args, **kwargs)

    def __pow__(self, other):
        "Return the composition of x to the power of y"
        if other > 0:
            for i in range(other-1):
                self *= self
            return self
        else:
            raise ValueError("Needs to be positive integer.")


    def __mul__(self, other):
        "Return the composition of proxied and another function."
        if type(other) is Composable:
            def anon(x):
                return self.func(other.func(x))
            return Composable(anon)
        elif type(other) is types.FunctionType:
            def anon(x):
                return self.func(other(x))
            return Composable(anon)
        raise TypeError("Illegal operands for multiplication")

    def __repr__(self):
        return "<Composable function {0} at
0x{1:X}>".format(self.func.__name__, id(self))


*** snip: end of composable.py  ***


*** snip: beginning of test_composable.py  ***

#!/usr/bin/env python3

"""
test_composable.py: performs simple tests of composable functions.
"""

import unittest
from composable import Composable

def reverse(s):
    "Reverses a string using negative-stride sequencing."
    return s[::-1]

def square(x):
    "Multiplies a number by itself."
    return x*x

def pwr(x, y):
    "raise x to the power of y"
    return x**y


class ComposableTestCase(unittest.TestCase):

    def test_inverse(self):
        reverser = Composable(reverse)
        nulltran = reverser * reverser
        for s in "", "a", "0123456789", "abcdefghijklmnopqrstuvwxyz":
            self.assertEqual(nulltran(s), s)

    def test_pow(self):
        a = 0
        for a in (2,3,4,5,6):
            raizit = Composable(pwr)
            cuber = raizit(a, 3)
            b = a * a * a
            self.assertEqual(cuber, b)

    def test_square(self):
        squarer = Composable(square)
        po4 = squarer * squarer
        for v, r in ((1,1), (2, 16), (3, 81)):
            self.assertEqual(po4(v), r)

    def test_exceptions(self):
        fc = Composable(square)
        pc = Composable(pwr)
        with self.assertRaises(TypeError):
            fc = fc * 3
        with self.assertRaises(TypeError):
            fc = square * fc
        with self.assertRaises(ValueError):
            pc = pc ** -3
        with self.assertRaises(TypeError):
            pc = pc ** 'a'

if __name__ == "__main__":
    unittest.main()

*** snip: end of test_composable.py ***

Thanks for any help!!

Dave
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.ale.org/pipermail/ale/attachments/20150617/3bf09bae/attachment.html>


More information about the Ale mailing list