zlacker

[return to "My favorite programming problem to teach: Digit length (2019)"]
1. jcynix+Bo3[view] [source] 2024-06-06 08:01:57
>>equili+(OP)
Hmm, my solution would be to convert the number to a string and return its length. Easily done in Perl:

  perl -e 'print length 987654'
  6
Similarly easy in Lisp with either of write-to-string, prin1-to-string, and princ-to-string. I expect python to have some such built-in function too.
◧◩
2. quirin+up3[view] [source] 2024-06-06 08:14:17
>>jcynix+Bo3
It is mentioned at the end of the article. In Python it's as simple as len(str(x)).
◧◩◪
3. lelant+3q3[view] [source] 2024-06-06 08:19:51
>>quirin+up3
> In Python it's as simple as len(str(x)).

I consider that to be wrong - leading zeros are not part of the number and should be ignored. Using `len(str(x))` results in `2` for the input `"01"`.

◧◩◪◨
4. Doxin+Qr3[view] [source] 2024-06-06 08:38:14
>>lelant+3q3
It's assumed the input is an int. If not you can do len(str(int(x))) to make sure it is which strips leading zeroes off in the process.
◧◩◪◨⬒
5. lelant+os3[view] [source] 2024-06-06 08:43:44
>>Doxin+Qr3
That's really my beef with languages like Python - typing is an afterthought. I literally get more safety from C than I do from Python:

    def numDigits(num):
        return len(str(num))
    
    print (numDigits(1))      # Returns the correct answer
    print (numDigits("1"))    # Returns the correct answer
    print (numDigits("01"))   # Returns the incorrect answer
The "returns the wrong answer" is the problem. If the input is the wrong type, I expect there to be an error raised, not silently give me wrong answers.
[go to top]