Is there a way to subtract 3 from every digit of a number?

Peter J. Holzer hjp-python at hjp.at
Mon Feb 22 07:25:03 EST 2021


On 2021-02-20 13:51:56 -0500, Terry Reedy wrote:
> On 2/20/2021 12:02 PM, jak wrote:
> >  >>> sn = ''
> >  >>> for x in str(n):
> >        sn += num[(int(x) - 3) % 10]
> 
> 
> This works, but suggesting to beginners that they build strings with += is
> an O(n*n) trap. Try it with a string of millions of digits.

The problem with trying is that it might just work.

CPython has a nice optimization for the common case (the variable at the
left side is the only reference to the str) which makes that O(n).

Other Python implementations may not have that optimization (PyPy
doesn't, I would assume that Jypthon or IronPython don't either because
their method of garbage collection would make it hard).

So for a beginner, the question is: Do you care about performance on
Python implementations you don't use? For a use-case you currently don't
have? 

        hp


-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20210222/7876ded1/attachment.sig>


More information about the Python-list mailing list