Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a generalized function for both strings and lists in python

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()"

like image 673
Drew Verlee Avatar asked Jan 19 '12 19:01

Drew Verlee


2 Answers

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.

like image 132
Hamish Avatar answered Oct 05 '22 03:10

Hamish


I'd say that the example isn't symetric, meaning that it asks the reader handle two different cases:

  • int, list
  • str, str

In my opinion, the exercise should ask to implement this:

  • list, list: insert_at_end([5], [1, 3, 4, 6])
  • str, str: insert_at_end('x', 'abc')

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.

like image 26
jcollado Avatar answered Oct 05 '22 02:10

jcollado