University of Arizona, Department of Computer Science

CSc 120: Assert: Evens and Odds 2

Expected Behavior

This programming problem involves identifying and checking invariants.

The following function takes a list arglist and returns a pair of lists, evens and odds, such that evens consists of the elements at even-numbered positions of arglist, i.e., arglist[0], arglist[2], etc.; and odds consists of the elements at odd-numbered positions of arglist, i.e., arglist[1], arglist[3], etc.

def odds_and_evens(arglist):
    evens = []
    odds = []
    for i in range(len(arglist)):
        ith_element = arglist[i]

        if i % 2 == 0:
            evens.append(ith_element)
        else:
            odds.append(ith_element)

        assert list_lengths_ok_after_iter_i(arglist, i, evens, odds)

    return (evens,odds)

Write a function list_lengths_ok_after_iter_i(arglist, i, evens, odds) that will be called by the assert at the end of each iteration of the loop shown above. The purpose of this function is to check that, at the end of the ith iteration, the lengths of the two lists evens and odds are the right values.

Your function list_lengths_ok_after_iter_i(arglist, i, evens, odds) should behave as follows. Given:

returns:

Programming Requirements

The function specified above should be implemented without using an if statement. You can use the Boolean operators and, or, and not if necessary.

Note that solutions that "accidentally" pass test cases will not get credit.

Useful Python Tips

Python has an integer division operator that yields the integer portion of the result of dividing one integer by another.

Examples

In the examples below, arglist = ['aa','bb','cc','dd','ee','ff','gg','hh','ii'].

  1. Call: list_lengths_ok_after_iter_i(arglist, 0, ['aa'], [])
    Return value: True

  2. Call: list_lengths_ok_after_iter_i(arglist, 0, ['qqq'], [])
    Return value: True

  3. Call: list_lengths_ok_after_iter_i(arglist, 0, ['aa'], ['bb'])
    Return value: False

  4. Call: list_lengths_ok_after_iter_i(arglist, 1, ['xx'], ['yy'])
    Return value: True

  5. Call: list_lengths_ok_after_iter_i(arglist, 3, ['aa', 'bb'], ['aa','bb'])
    Return value: True

  6. Call: list_lengths_ok_after_iter_i(arglist, 3, ['aa', 'bb', 'cc'], ['aa','bb'])
    Return value: False

  7. Call: list_lengths_ok_after_iter_i(arglist, 5, ['aa','cc','ee'], ['ff','gg'])
    Return value: False

  8. Call: list_lengths_ok_after_iter_i(arglist, 5, ['aa','cc','dd'], ['ff', 'ee','qq'])
    Return value: True