PPA-7
Question
In a throwback to CT days, write the definition of the following five functions, all of which accept a list L as argument.
is_empty
: returnTrue
if the list is empty, andFalse
otherwise.first
: return the first element if the list is non-empty, returnNone
otherwise.last
: return the last element if the list is non-empty, returnNone
otherwise.init
: return the first \(n - 1\) elements if the list is non-empty and has size \(n\), returnNone
otherwise. Note that ifL
has just one element,init(L)
should return the empty list.rest
: return the last \(n - 1\) elements if the list is non-empty and has size \(n\), returnNone
otherwise. Note that ifL
has just one element,rest(L)
should return the empty list.
You do not have to accept input from the user or print output to the console. You just have to write the definition of all the five functions. Each test case corresponds to one function call.
Hint
We will go one function at a time:
is_empty
: We are going to write three different solutions for this:
Solution-1
Solution-2
Solution-3
Are all three solutions correct? Which one do you think is better?
first
: there are again three solutions that we will look at:
Solution-1
Solution-2
Solution-3
Here, we are assuming that is_empty
is available to us.
Again, look at these three solutions and try to identify which one is better.
last
Is the following solution correct? If not, what do you think is wrong with it?
init
def init(L):
if L == [ ]:
return None
out = [ ]
n = len(L)
for x in range(n - 1):
out.append(x)
return out
Is there a simpler solution that doesn’t require the explicit creation of a new list out
?
rest
This is similar to the previous function. We just need to leave out the first element and include the rest.