Middle three digits

From Rosetta Code
Revision as of 03:23, 2 February 2013 by rosettacode>Paddy3118 (New draft task and Python solution.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Middle three digits is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

The task is to

Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.

Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:

123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0

Show your output on this page.

Python

<lang python>>>> def missing_three_digits(i): s = str(abs(i)) length = len(s) assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits" mid = length // 2 return s[mid-1:mid+2]

>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] >>> failing = [1, 2, -1, -10, 2002, -2002, 0] >>> for x in passing + failing: try: answer = m3(x) except AssertionError as error: answer = error print("missing_three_digits(%s) returned: %r" % (x, answer))


missing_three_digits(123) returned: '123' missing_three_digits(12345) returned: '234' missing_three_digits(1234567) returned: '345' missing_three_digits(987654321) returned: '654' missing_three_digits(10001) returned: '000' missing_three_digits(-10001) returned: '000' missing_three_digits(-123) returned: '123' missing_three_digits(-100) returned: '100' missing_three_digits(100) returned: '100' missing_three_digits(-12345) returned: '234' missing_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',) missing_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',) missing_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',) missing_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',) missing_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',) missing_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',) missing_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',) >>> </lang>