Middle three digits: Difference between revisions

→‎{{header|Python}}: Added an illustration of an option type in Python
No edit summary
(→‎{{header|Python}}: Added an illustration of an option type in Python)
Line 3,848:
middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)
>>> </lang>
 
 
Or, using an option type:
{{Trans|Haskell}}
<lang python>from functools import (reduce)
from itertools import (chain)
 
 
# mid3digits :: Either String String
def mid3digits(n):
def go(s):
return Right(
s[(len(s) - 3) // 2:][0:3]
)
m = abs(n)
s = str(m)
return Left('Less than 3 digits') if (100 > m) else (
Left('Even digit count') if even(len(s)) else go(s)
)
 
 
# TEST ----------------------------------------------------
def main():
xs = [
123, 12345, 1234567, 987654321, 10001, -10001, -123,
-100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0
]
mx = len(str(maximumBy(lambda x: len(str(x)))(xs)))
print (
'\n'.join([
(
justifyRight(mx)(' ')(str(n)) + ' -> ' + (
either(str)(str)(mid3digits(n))
)
) for n in xs
]),
)</lang>
<pre> 123 -> 123
12345 -> 234
1234567 -> 345
987654321 -> 654
10001 -> 000
-10001 -> 000
-123 -> 123
-100 -> 100
100 -> 100
-12345 -> 234
1 -> Less than 3 digits
2 -> Less than 3 digits
-1 -> Less than 3 digits
-10 -> Less than 3 digits
2002 -> Even digit count
-2002 -> Even digit count
0 -> Less than 3 digits</pre>
 
=={{header|Racket}}==
9,659

edits