Why can't I use max with Python to find maximum one-digit integer in array?

Viewed 1452

I had an interview recently and was asked to solve the following problem using Python:

Write a function:

def solution(A):

such that, given an array A consisting of N integers, it returns the maximum among all one-digit integers.

For example, given array A as follows:

[-6, -91, 1011, -100, 84, -22, 0, 1, 473]

the function should return 1.

Assume that:

  • N is an integer within the range [1...1,000]
  • Each element of array A is an integer within the range [-10,000..10,000].
  • There is at least one element in array A which satisfies the condition in the task statement.

I came up with the following solution which I thought was elegant, but the score I got was only 55%:

def solution(A):
    return max([i for i in A if len(str(i))==1])

Why is this solution incorrect?

2 Answers

Not the most elegant. This assumes that e.g. -3 is single digit.

This algorithm will play by the rules set. Considering the constraints:

  • The number is -10,000 to 10,000
  • There is at least one element which satisfies the condition

Then we can just guard all numbers beyond 9 to be the lowest -10,001 so that they are not considered to be max. We don't need to care for numbers lower than -9 as we are sure there is at least 1 element (that is a single digit whether positive or negative, either way greater than those numbers lower than -9) that will satisfy the condition.

print(
    max(
        [-6, -91, 1011, -100, 84, -22, 0, 1, 473, 5, 4, 67, 7, 3, 56],
        key=lambda num: -10001 if num > 9 else num
    )
)
print(
    max(
        [-6, -91, 1011, -100, 84, -22, 10, -5, -8, 67],
        key=lambda num: -10001 if num > 9 else num
    )
)

Output:

7
-5

Here is a solution that ticks more points in my book.

def solution(integers):
    """Return max single digit integer in sequence `integers`"""
    try:
        return max(i for i in integers if -9 <= i <= 9)
    except ValueError:
        return ValueError("Could not find single digit integer in list")

print(solution([-6, -91, 1011, -100, 84, -22, 0, 1, 473]))

It uses a descriptive parameter name, has a comment, does a simple comparison for digit size and uses a generator with the built in function max instead of the needless list. It also reraises the most expected fault with a more topical error message. This function is easier to maintain and use.

Related