zlacker

[return to "My Favorite Programming Problem to Teach: Digit Length"]
1. jepler+N3[view] [source] 2019-11-10 22:44:41
>>jstrie+(OP)
But the math.log10 solution is unfortunately "wrong" too, at least in my python3 implementation.

    import math

    def digitLengthCorrect(n):
        return len(str(n))

    def digitLengthClever2(n):
        return 1 if n == 0 else (math.floor(math.log10(n)) + 1)

    testcases = (
        [10 ** i for i in range(300)] +
        [(10 ** i) - 1 for i in range(300)]
    )

    for t in testcases:
        a = digitLengthCorrect(t)
        b = digitLengthClever2(t)
        assert a == b, (t, a, b)
◧◩
2. FabHK+vI[view] [source] 2019-11-11 09:08:10
>>jepler+N3
Yes, the so-called "naive" solution is the best one, in my view, insofar as it is correct. Of course, choose the "clever" solution if speed is more important than correctness (in other words, if the approximate number of digits is acceptable, eg. if a +1 safety buffer is used) - though then benchmark to show that it is actually faster, for the distribution of numbers you actually encounter.

So, the discussion of this problem can be extended further into a discussion of specs, tradeoffs, benchmarking, etc.

[go to top]