5 Best Ways to Check if the First and Last Digit of the Smallest Number Forms a Prime in Python

πŸ’‘ Problem Formulation: You need to determine whether the smallest number in a given set has a first and last digit that, when combined together, form a prime number. If you’re given an array [143, 235, 19], the smallest number is 19, and the first and last digits 1 and 9 form the number 19, which is prime. Hence, the desired output, in this case, is True.

Method 1: Converting to String

This method involves converting the smallest number to a string, extracting the first and last characters, combining them to form a new number, and then checking if this new number is prime. The function is_prime() is used to verify the primeness of the formed number.

Here’s an example:

def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return False
    return True

def first_last_prime(arr):
    smallest_num = str(min(arr))
    first_last = int(smallest_num[0] + smallest_num[-1])
    return is_prime(first_last)

# Example Usage
print(first_last_prime([143, 235, 19]))

Output:

True

This snippet defines a utility function is_prime() that efficiently checks for prime numbers and another function first_last_prime() which finds the smallest number in an array, concatenates its first and last digits, and determines if this new number is prime.

Method 2: Without String Conversion

In this method, we employ mathematical operations to find the first and last digits of the smallest number without converting it to a string. This avoids overhead caused by type conversions and string manipulations.

Here’s an example:

def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return False
    return True

def first_last_prime(arr):
    smallest_num = min(arr)
    last_digit = smallest_num % 10
    while smallest_num >= 10:
        smallest_num //= 10
    first_digit = smallest_num
    first_last = first_digit * 10 + last_digit
    return is_prime(first_last)

# Example Usage
print(first_last_prime([143, 235, 19]))

Output:

True

The function first_last_prime() calculates the first and last digits using division and modulus operators and then checks if the new number formed by these digits is prime.

Method 3: Using List Comprehension and Lambdas

This method takes advantage of the concise syntax provided by list comprehension and lambda functions to achieve the same result in a more compact code.

Here’s an example:

is_prime = lambda num: num > 1 and all(num % i for i in range(2, int(num ** 0.5) + 1))

def first_last_prime(arr):
    smallest_str = str(min(arr))
    return is_prime(int(smallest_str[0] + smallest_str[-1]))

# Example Usage
print(first_last_prime([143, 235, 19]))

Output:

True

The lambda function is_prime succinctly checks for a prime number, and the smallest number’s first and last digits are concatenated and checked for primeness in the first_last_prime() function.

Method 4: Using Regular Expressions

Regular expressions can be employed to directly extract the first and last digits from the smallest number converted to a string. This approach can make the code more readable for those familiar with regex patterns.

Here’s an example:

import re

def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return False
    return True

def first_last_prime(arr):
    smallest_str = str(min(arr))
    first_last = int(re.search(r'^(.).*(.)$', smallest_str).groups()[0] + 
                     re.search(r'^(.).*(.)$', smallest_str).groups()[1])
    return is_prime(first_last)

# Example Usage
print(first_last_prime([143, 235, 19]))

Output:

True

A regular expression pattern is used in the first_last_prime() function to capture the first and last digits and check the combined number for primeness via the is_prime() function.

Bonus One-Liner Method 5: List Comprehension with Math and Lambda

Combining list comprehension with mathematical operations allows us to employ a one-liner Python expression that effectively solves the problem by finding the first and last digits and then checking their combination for primeness.

Here’s an example:

print((lambda x: x > 1 and all(x % i for i in range(2, int(x ** 0.5) + 1)))
      (int(str(min([143, 235, 19]))[0] + str(min([143, 235, 19]))[-1])))

Output:

True

This Python one-liner combines list comprehension and lambda functions to find the first and last digits of the smallest number and checks if their combination is prime using an inline is_prime() check.

Summary/Discussion

  • Method 1: String Conversion. Easy to follow. Potentially less efficient due to string operations.
  • Method 2: No String Conversion. More efficient for large numbers. Slightly more complex due to mathematical operations.
  • Method 3: List Comprehension with Lambdas. Compact and elegant. May be less readable for those unfamiliar with lambdas.
  • Method 4: Regular Expressions. Good readability for regex-savvy users. Slower due to regex overhead.
  • Bonus Method 5: One-Liner. Very concise. Can be difficult to understand and debug.