Note that there are some explanatory texts on larger screens.

plurals
  1. POWriting a generalized function for both strings and lists in python
    primarykey
    data
    text
    <p>So i'm green as grass and learning programming from <a href="http://openbookproject.net/thinkcs/python/english3e/lists.html" rel="nofollow">How to think like a computer scientist: Learn python 3</a>. I'm able to answer the question (see below) but fear i'm missing the lesson. </p> <p>Write a function (called insert_at_end) that will pass (return the bold given the two arguments before) for all three:</p> <pre><code>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)**) </code></pre> <p>The book gives this hint:"These exercises illustrate nicely that the sequence abstraction is general, (<strong>because slicing, indexing, and concatenation</strong> are so general), so it is possible to write general functions that work over all sequence types.".</p> <p>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:</p> <pre><code>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) </code></pre> <p>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()" </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload