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. ben-sc+Lf[view] [source] 2019-11-11 01:25:41
>>gnuvin+fe
Having done a fair amount of python, this is exactly the result I'd expect. `len`, `str` are essentially implemented in C, thus avoiding the massive interpreter overhead compared to a simple loop in python.
[go to top]