Craft a Python function, get_kth_digit(x, k), that extracts the k-th digit from the left of a given number x. If k is not explicitly defined, default to returning the most significant digit (MSD).
This function should be a self-contained unit, taking two numbers as input and spitting out a single number as output.
Note that digit indexing starts from one, and if the k-th digit is out of bounds, return a sentinel value of -1. You can assume k is always greater than zero. This problem can be tackled using functional programming principles.
Here's an implementation that uses mathematical operations to extract the k-th digit:
def get_kth_digit(x, k=None):
"""
Extracts the k-th digit from the left of a given number x.
Args:
x (int): The input number.
k (int, optional): The digit index (1-indexed). Defaults to None, which returns the most significant digit (MSD).
Returns:
int: The k-th digit if it exists, otherwise -1.
"""
# If k is not provided, return the most significant digit (MSD)
if k is None:
return int(str(x)[0])
# Calculate the number of digits in x
num_digits = len(str(x))
# Check if k is within bounds
if k < 1 or k > num_digits:
return -1
# Calculate the k-th digit using mathematical operations
kth_digit = (x // 10 ** (num_digits - k)) % 10
return kth_digit
This implementation uses mathematical operations to extract the k-th digit. It calculates the number of digits in the input number and then uses the formula (x // 10 ** (num_digits - k)) % 10 to extract the k-th digit.
The constraint doesn't explicitly state that x is an integer, which is a major gotcha. A more elegant approach would be to refactor the function like this:
def get_kth_digit(x, k=1):
digits = [int(d) for d in str(x).replace('.', '')]
return digits[k-1] if k <= len(digits) else -1
print(get_kth_digit(7.5, 2)) # Output: 5
print(get_kth_digit(7.5)) # Output: 7
print(get_kth_digit(7.5, 10)) # Output: -1
I've used a list comprehension to create a list of digits from the input x, and then returned the k-th element of the list if it exists, or -1 otherwise.
Here's a Python implementation that utilizes a while loop to iteratively truncate the input integer x, effectively 'peeling away' its digits until the kth digit is revealed:
def extract_kth_digit(x, k=1):
"""
Extracts the kth digit from a given integer x.
Args:
x (int): The input integer.
k (int, optional): The digit position to extract. Defaults to 1.
Returns:
int: The kth digit if it exists, -1 otherwise.
"""
digit_count = 0
truncated_x = x
while truncated_x:
digit_count += 1
truncated_x //= 10
if k > digit_count:
return -1
return x // 10 ** (digit_count - k) % 10
In this implementation, we employ a technique called "digit truncation" to iteratively reduce the input integer x until we reach the desired digit position k. The // operator performs integer division, effectively truncating the digit, while the % operator extracts the remainder, which represents the kth digit.