Avatar of bkhl

bkhl's solution

to List Ops in the Python Track

Published at Jan 05 2019 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution was written.

Implement basic list operations.

In functional languages list operations like length, map, and reduce are very common. Implement a series of basic list operations, without using existing functions.

Exception messages

Sometimes it is necessary to raise an exception. When you do this, you should include a meaningful error message to indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. Not every exercise will require you to raise an exception, but for those that do, the tests will only pass if you include a message.

To raise a message with an exception, just write it as an argument to the exception type. For example, instead of raise Exception, you should write:

raise Exception("Meaningful message indicating the source of the error")

Running the tests

To run the tests, run the appropriate command below (why they are different):

  • Python 2.7: py.test list_ops_test.py
  • Python 3.4+: pytest list_ops_test.py

Alternatively, you can tell Python to run the pytest module (allowing the same command to be used regardless of Python version): python -m pytest list_ops_test.py

Common pytest options

  • -v : enable verbose output
  • -x : stop running tests on first failure
  • --ff : run failures from previous test before running other test cases

For other options, see python -m pytest -h

Submitting Exercises

Note that, when trying to submit an exercise, make sure the solution is in the $EXERCISM_WORKSPACE/python/list-ops directory.

You can find your Exercism workspace by running exercism debug and looking for the line that starts with Workspace.

For more detailed information about running tests, code style and linting, please see Running the Tests.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

list_ops_test.py

import unittest
import operator

import list_ops


# Tests adapted from problem-specifications//canonical-data.json @ v2.2.0

class ListOpsTest(unittest.TestCase):

    # test for append
    def test_append_empty_lists(self):
        self.assertEqual(list_ops.append([], []), [])

    def test_append_empty_list_to_list(self):
        self.assertEqual(list_ops.append([], [1, 2, 3, 4]), [1, 2, 3, 4])

    def test_append_nonempty_lists(self):
        self.assertEqual(list_ops.append([1, 2], [2, 3, 4, 5]),
                         [1, 2, 2, 3, 4, 5])

    # tests for concat
    def test_concat_empty_list(self):
        self.assertEqual(list_ops.concat([]), [])

    def test_concat_list_of_lists(self):
        self.assertEqual(list_ops.concat([[1, 2], [3], [], [4, 5, 6]]),
                         [1, 2, 3, 4, 5, 6])

    # tests for filter_clone
    def test_filter_empty_list(self):
        self.assertEqual(list_ops.filter_clone(lambda x: x % 2 == 1, []), [])

    def test_filter_nonempty_list(self):
        self.assertEqual(
            list_ops.filter_clone(lambda x: x % 2 == 1, [1, 2, 3, 4, 5]),
            [1, 3, 5])

    # tests for length
    def test_length_empty_list(self):
        self.assertEqual(list_ops.length([]), 0)

    def test_length_nonempty_list(self):
        self.assertEqual(list_ops.length([1, 2, 3, 4]), 4)

    # tests for map_clone
    def test_map_empty_list(self):
        self.assertEqual(list_ops.map_clone(lambda x: x + 1, []), [])

    def test_map_nonempty_list(self):
        self.assertEqual(list_ops.map_clone(lambda x: x + 1, [1, 3, 5, 7]),
                         [2, 4, 6, 8])

    # tests for foldl
    def test_foldl_empty_list(self):
        self.assertEqual(list_ops.foldl(operator.mul, [], 2), 2)

    def test_foldl_nonempty_list_addition(self):
        self.assertEqual(list_ops.foldl(operator.add, [1, 2, 3, 4], 5), 15)

    def test_foldl_nonempty_list_floordiv(self):
        self.assertEqual(list_ops.foldl(operator.floordiv, [2, 5], 5), 0)

    # tests for foldr
    def test_foldr_empty_list(self):
        self.assertEqual(list_ops.foldr(operator.mul, [], 2), 2)

    def test_foldr_nonempty_list_addition(self):
        self.assertEqual(list_ops.foldr(operator.add, [1, 2, 3, 4], 5), 15)

    def test_foldr_nonempty_list_floordiv(self):
        self.assertEqual(list_ops.foldr(operator.floordiv, [2, 5], 5), 2)

    # additional test for foldr
    def test_foldr_add_str(self):
        self.assertEqual(
            list_ops.foldr(operator.add,
                           ["e", "x", "e", "r", "c", "i", "s", "m"], "!"),
            "exercism!")

    # tests for reverse
    def test_reverse_empty_list(self):
        self.assertEqual(list_ops.reverse([]), [])

    def test_reverse_nonempty_list(self):
        self.assertEqual(list_ops.reverse([1, 3, 5, 7]), [7, 5, 3, 1])

    # additional test for reverse
    def test_reverse_mixed_types(self):
        self.assertEqual(
            list_ops.reverse(["xyz", 4.0, "cat", 1]), [1, "cat", 4.0, "xyz"])


if __name__ == '__main__':
    unittest.main()
def append(xs, ys):
    return concat((xs, ys))


def concat(lists):
    return [x for l in lists for x in l]


def filter_clone(function, xs):
    return [x for x in xs if function(x)]


def length(xs):
    return foldl(lambda acc, _: acc + 1, xs, 0)


def map_clone(function, xs):
    return [function(x) for x in xs]


def foldl(function, xs, acc):
    if xs:
        return foldl(function, xs[1:], function(acc, xs[0]))
    else:
        return acc


def foldr(function, xs, acc):
    if xs:
        return foldr(function, xs[:-1], function(xs[-1], acc))
    else:
        return acc


def reverse(xs):
    if xs:
        return append([xs[-1]], reverse(xs[:-1]))
    else:
        return xs

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?