Solution 1

except NameError:
    from functools import reduce

def comma_code(a_list):
    return reduce(lambda x, y: x + ", " + y if y != a_list[len(a_list)-1] else x + " and " + y, a_list)

Comma Code

Write a function that takes a list value as an argument
and returns a string with all the items separated
by a comma and a space, with 'and' inserted before the last item.


comma_code(['apples', 'bananas', 'tofu', 'cats']) # 'apples, bananas, tofu and cats'
comma_code(['apples', 'bananas']) # 'apples and bananas'

This assignment is also designed to be resolved with a reduce function, but use your common sense to judge it.

Test Cases

test comma code two elements - Run Test

def test_comma_code_two_elements():
    assert comma_code(['apples', 'bananas']) == 'apples and bananas'

test comma code single element - Run Test

def test_comma_code_single_element():
    assert comma_code(['apples']) == 'apples'

test comma code sample list - Run Test

def test_comma_code_sample_list():
    assert comma_code(['apples', 'bananas', 'tofu', 'cats']) == 'apples, bananas, tofu and cats'
def comma_code(a_list): pass