zlacker

[return to "My Favorite Programming Problem to Teach: Digit Length"]
1. _paste+Id[view] [source] 2019-11-11 00:48:19
>>jstrie+(OP)
Why not:

  def digit_len(n): 
    return len(str(n))
◧◩
2. gnuvin+fe[view] [source] 2019-11-11 00:56:07
>>_paste+Id
For people who, like me, thought that this would be slower than repeated division: my crappy benchmark indicates that allocating a new string and taking its length is faster by a factor of 2–2.5x.

Edit: In C, the version that loops is 15 times faster than the version that allocates a new string. Python is weird.

◧◩◪
3. kragen+Af[view] [source] 2019-11-11 01:23:14
>>gnuvin+fe
It's a common feature of interpreters that they impose a large slowdown on whatever is done in interpreted code; Python's is about 40×, although better interpreters like GhostScript and Lua are more like 10×. It's surprising the difference isn't bigger in this case, but I can mostly confirm your results, getting 3× except for small numbers:

    In [1]: dl = lambda n: 1 if n < 10 else 1 + dl(n // 10)

    In [3]: map(dl, [0, 1, 9, 10, 99, 1000, 15432, 32, 801])
    Out[3]: [1, 1, 1, 2, 2, 4, 5, 2, 3]

    In [4]: %timeit dl(15322)
    100000 loops, best of 3: 4.64 µs per loop

    In [5]: %timeit len(str(15322))
    1000000 loops, best of 3: 1.41 µs per loop

    In [6]: %timeit dl(0)
    1000000 loops, best of 3: 721 ns per loop

    In [7]: %timeit len(str(0))
    1000000 loops, best of 3: 1.24 µs per loop
[go to top]