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. Stream+lQ[view] [source] 2019-11-11 10:42:43
>>gnuvin+fe
Yes but performance was not part of the question. Any correct solution would do. I see this a lot that people go an extra mile trying to optimize the solution and introducing bugs along the way instead having a simple certainly correct solution and optimize it later if necessary. It is funny that the string version is faster in Python.
[go to top]