Q: "...Learning with Python" ...a property that addition and multiplication have...

Dan Sommers me at privacy.net
Wed May 25 23:25:52 EDT 2005


On 25 May 2005 17:23:45 -0700,
jeffbernstein at yahoo.com wrote:

> I'm reading "How to think like a computer scientist: Learning with
> Python" and there's a question regarding string operations. The
> question is, "Can you think of a property that addition and
> multiplication have that string concatenation and repetition do not?"

> I thought it was the commutative property but "<string>"*3 is
> equivalent to 3*"<string>". Any ideas?

Thinking like an old embedded systems programmer, for many types of
numbers (ints and floats, but not longs), multiplication and addition
are constant time, constant space operations.  String concatenation and
repetition are not.

As already mentioned, there are no inverses.  Similarly, there aren't
even inverse operations (e.g., it makes little sense to divide a string
by a number, let alone a number by a string).

For floating point numbers (and integers that can overflow),
multiplication and addition are not necessarily exact.  Unless your
strings get too big for the memory manager, concatenation and
replication are exact.

And now that I reread the question, "a property that addition and
multiplication have" is "the distributive property," but the
distributive property of multiplcation over addition does not translate
to a distributive property of repetition over concatenation:

    2 * ( 3 + 4 ) == 14
    2 * 3 + 2 * 4 == 14

but

    2 * ( "ABC" + "DEFG" ) == "ABCDEFGABCDEFG"
    2 * "ABC" + 2 * "DEFG" == "ABCABCDEFGDEFG"

Regards,
Dan

-- 
Dan Sommers
<http://www.tombstonezero.net/dan/>



More information about the Python-list mailing list