So i'm green as grass and learning programming from How to think like a computer scientist: Learn python 3. I'm able to answer the question (see below) but fear i'm missing the lesson.
Write a function (called insert_at_end) that will pass (return the bold given the two arguments before) for all three:
test(insert_at_end(5, [1, 3, 4, 6]), **[1, 3, 4, 6, 5]**)
test(insert_at_end('x', 'abc'), **'abcx'**)
test(insert_at_end(5, (1, 3, 4, 6)), **(1, 3, 4, 6, 5)**)
The book gives this hint:"These exercises illustrate nicely that the sequence abstraction is general, (because slicing, indexing, and concatenation are so general), so it is possible to write general functions that work over all sequence types.".
This version doesn't have solutions on-line (that i could find) but in I found someone's answers to a previous version of the text (for python 2.7) and they did it this way:
def encapsulate(val, seq):
if type(seq) == type(""):
return str(val)
if type(seq) == type([]):
return [val]
return (val,)
def insert_at_end(val, seq):
return seq + encapsulate(val, seq)
Which seems to be solving the question by distinguishing between lists and strings... going against the hint. So how about it Is there a way to answer the question (and about 10 more similar ones) without distinguishing? i.e not using "type()"
My best effort:
def insert_at_end(val, seq):
t = type(seq)
try:
return seq + t(val)
except TypeError:
return seq + t([val])
This will attempt to create the sequence of type(seq)
and if val
is not iterable produces a list and concatenates.
I'd say that the example isn't symetric, meaning that it asks the reader handle two different cases:
In my opinion, the exercise should ask to implement this:
In this case, the reader has to work only with two parameters that use the same sequence type and the hint would make much more sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With