Sample Python Exam Problem Solutions

Sample Python Exam Problem Solutions
 Revision as of 03:11, December 16, 2011 (view source)Aprakash (Talk | contribs)← Older edit Revision as of 01:17, December 5, 2012 (view source)Aprakash (Talk | contribs) Newer edit → Line 10: Line 10: Some examples: Some examples: − mylist().append(4).append(3).last(): same as 3 + * mylist().append(4).append(3).last(): same as 3 − mylist().append(4).append(3).pop(): same as mylist().append(4) + * mylist().append(4).append(3).pop(): same as mylist().append(4) − mylist().append(4).isempty(): False + * mylist().append(4).isempty(): False − mylist().append(4).pop().isempty(): True + * mylist().append(4).pop().isempty(): True Given the above mylist type, implement the following functions only using the above interface to mylist. Given the above mylist type, implement the following functions only using the above interface to mylist.

Revision as of 01:17, December 5, 2012

Problem: You are given a special type of List called mylist that has only a subset of functionality of Python lists. It provides the following methods:

• mylist(): creates an empty mylist object
• L.append(item): returns a new mylist that contains all the elements of L followed by item. Note that L is not modified.
• L.pop(): returns a new mylist object containing all the elements of mylist L in the same order, except the last one. Note that L is not modified. L assumed to be non-empty.
• L.last(): returns the last element of L. L assumed to be non-empty.
• L[index1:index2]: returns a new mylist that contains elements from position index1 to index2-1 (inclusive). Indexing starts at 0.
• L.isempty(): returns True if L is empty object. Else it returns False.

Some examples:

• mylist().append(4).append(3).last(): same as 3
• mylist().append(4).append(3).pop(): same as mylist().append(4)
• mylist().append(4).isempty(): False
• mylist().append(4).pop().isempty(): True

Given the above mylist type, implement the following functions only using the above interface to mylist.

All the methods are non-destructive, in the sense that the parameter L need not be modified.