Conciseness vs Readability

#1

I am enjoying the book very much. So a big thank you!
In my opinion some of the solutions are very concise/elegant at the expanse of readability.

For example the solution to 6.1:

def string_to_int(s):
    return functools.reduce(lambda running_sum,
                            c: running_sum * 10 + string.digits.index(c),
                            s[s[0] == '-':],
                            0) * (-1 if s[0] == '-' else 1)

Personally I found it somewhat hard to read. For example in day to day job, I would test s[0] == ‘-’ and save it to clearly named variable. Is that a way to demonstrate ability to the interviewer/ save whiteboard space?

Maybe it’s just my inexperience with Python…

0 Likes

#2

Hi @inoam,

First of all, thanks for your good words. I am sorry that here I think the solution is a little bit showing off since we really want to purse the most pythonic way to solve this problem. As you might read in this book, we sometimes provide pythonic solutions as a way to let readers know that it is something can be done in Python.

I think in this problem, you always can choose the way you like to implement, and there is no need to view this as golden standard in my opinion.

0 Likes

#3

Why is the initializer=0 was used?

For example, if we have -324, we just need to have (310+2)10+4 * (-1) = ( 310**2 + 210 + 4 ) * (-1), but where does the 0 needed? (I observed “TypeError: must be str, not int”, though)

Maybe, does this put running_sum=0, c=0, initially, to make it (0*10+index(0)) … as the running_sum cannot be str, if so I get the initializer does the job of setting all the argument of lambda: function as initializer.

If so, the explanation of the Python official doc is somewhat misleading that “If the optional initializer is present, it is placed before the items of the sequence in the calculation, and [serves as a default when the sequence is empty]. If initializer is not given and sequence contains only one item, the first item is returned. (bracket is added by me for emphasis)”

Actually, it should be stated as ‘serves as a default to be run before the lambda reads the given sequence.’ This vagueness somewhat brought me confusion understanding the code. However, I learned many things out of this code. Thanks.

0 Likes