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()”
This is not a solution but rather an explanation why a truly elegant solution does not look possible.
+concatenates sequences, but only sequences of same type.insert_at_endare ‘scalar’, so you have to convert them to the sequence type that the second argument has.tuple(1)does not work.strworks differently than other sequence types:tuple(["a"])is("a",),list(["a"])is["a"], butstr(["a"]))is"['a']"and not"a".This renders
+useless in this situation, even though you can easily construct a sequence of given type cleanly, withoutinstanceof, just by usingtype().You can’t use slice assignment, too, since only lists are mutable.
In this situation, the solution by @Hamish looks cleanest.