Skip to content
Advertisement

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

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement