Python - Kth digit Sum


Finding the kth digit sum means we must find the sum of all the digits at the kth index of a list of numbers. This is an important programming concept, and we use this in data validation, financial analysis, etc. In this article, we will explore how to find the kth digit sum with the help of several custom methods like loops, list comprehensions, lambda, map functions, etc. We will also use libraries like Numpy and Functool to achieve the same.

Understanding The Problem Statement

Suppose we have the following inputs:

list:  [12,73,64]

k=0

Now we need to find the kth digit sum. At the index k=0 the digits present are: 1 (from 12), 7 (from 73), 6 (from 64). So the summation of the numbers = 1+7+6 = 14. Our desired output should be 14.

Output: 14

Using The Loops

One of the simplest ways we can adapt to find the summation of the kth digits of the elements of a list is to adopt the brute force approach. The brute force approach is the method that we employ without thinking much about optimization.

We can adopt the following approach:

  • Iterate over the list of numbers.

  • Under each iteration, convert the numbers into String and find the kth character.

  • Now reconvert the character into integers using type casting.

  • Add this to an initialized variable under each iteration.

Example

In the following code, we used the brute force method to find the kth sum. We created the function called kth_digit_sum, which takes the number and the value 'k'. Under the function, we initialized a variable named sum to 0. Next, we iterated over the list of numbers. Under each iteration, we first converted the elements into a string, took the kth character out of it, and converted it into an integer. We added the digits to our initialized variable. Finally, we returned it.

def kth_digit_sum_math(num, k):
    sum=0
    for n in num:
        sum=sum+int(str(n)[k])
    return sum
test_list = [4154,1175,1754,7451,7642]
k = 0
total_sum=kth_digit_sum_math(test_list, k)
print(f"The kth digit sum of the list of numbers is: {total_sum}")

Output

The kth digit sum of the list of numbers is: 20

Using List Comprehension

List comprehension is a popular method in Python to create list elements. It allows us to combine multiple expressions and statements into a single line of code to create list elements. However, this method is unsuitable when the conditional statement is too big.

Example

In the following example, we have created the function called kth_digit_sum_math. It takes the list of numbers and the value 'k'. Under this function, we have used the while loop to iterate over the list of numbers. After converting the number into a String data type, we have taken the kth digit for each iteration. We used the 'int' method to convert it back into an integer and the sum method to get the summation of all the elements generated.

def kth_digit_sum_math(num_list, k):
    return sum(int(str(n)[k]) for n in num_list)
test_list = [7845,4521,56452,58896,7842,57456]
k = 1
total_sum=kth_digit_sum_math(test_list, k)
print(f"The kth digit sum of the list of numbers is: {total_sum}")

Output

The kth digit sum of the list of numbers is: 42

Using Lambda And Map Function

A lambda function is an important concept in Python. They are those functions that do not have any name and are used to perform small functions. If the logic we need to put into a function is small enough and we are sure we won't use the same piece of code elsewhere in the code, it is often best practice to use the lambda function.

On the other hand, the map method is very helpful when we want to apply some method to all the elements of any iterable object.

Syntax

map(function, iterable)

Here the function is the function's name which we need to apply to all the elements of the iterable object. The 'iterable' is the object's name on which we must apply the function.

Example

In the following example, we created the kth_digit_sum_math function, which takes the list of numbers and the value 'k' as the parameters. Under this function, we first used the map method to convert all the numbers into list data types. Next, we used the map method to remove only the kth characters from the elements. Again we used the lambda method to convert them into integers and finally used the sum method to get the sum of the numbers.

def kth_digit_sum_math(num_list, k):
    str_list = map(str, num_list)
    characters_list = map(lambda x: x[k:k+1], str_list)
    digit_list = map(int, characters_list)
    return sum(digit_list)
test_list = [7845,4521,56452,58896,7842,57456]
k = 3
total_sum=kth_digit_sum_math(test_list, k)
print(f"The kth digit sum of the list of numbers is: {total_sum}")

Output

The kth digit sum of the list of numbers is: 27

Using The Numpy Library

Numpy is a very popular library in Python for Numerical computations. Numpy library deals with an array − a specialized data structure that looks like a list but can hold only homogenous data. The NumPy library provides several methods which we can utilize to perform several tasks. To find the kth digit sum, we must first convert the list of numbers into an array using the 'array' method. Next, we can use the list comprehension and the “np.sum” method to find the summation of the desired digits.

Example

We first imported the Numpy library in our code in the following example. Under the function kth_digit_sum_numpy, we used the method 'array' of Numpy to convert the list into Numpy arrays. Next, we used list comprehension to get only the kth digit and convert it into an array using the 'array' method. Finally, we used the 'np.sum' method to get the summation of all the array elements.

import numpy as np

def kth_digit_sum_numpy(num_list, k):
    str_list = np.array([str(num) for num in num_list])
    digit_array = np.array([int(num_str[k]) for num_str in str_list])
    return np.sum(digit_array)

test_list = [7845, 4521, 56452, 58896, 7842, 57456]
k = 1

total_sum = kth_digit_sum_numpy(test_list, k)
print(f"The kth digit sum of the list of numbers is: {total_sum}")

Output

The kth digit sum of the list of numbers is: 42

Using Functool Library

The functions module is a built−in module that provides higher−order functions and operations for working with functions in Python. It provides several higher−order functions. Higher−order functions are those functions that return other functions. The methods available are handy when we want to make our code more reusable.

Example

In the following example, first, we have imported the Functools library of Python. Next, we used the function kth_digit_sum, which takes the list of numbers and returns the kth sum. Under this function, we created extract_kth_digit, which takes a number and returns the kth digit. Next, we used the map method to apply this function to all the list elements. We used the reduce method of the Functool library to find the summation of the numbers.

import functools

def kth_digit_sum(test_list, k):
  def extract_kth_digit(number):
    num_str = str(number)
    return int(num_str[k])
  kth_digits = list(map(extract_kth_digit, test_list))
  return functools.reduce(lambda x, y: x + y, kth_digits)


test_list = [12345, 67890, 34567]
k = 4
total_sum = kth_digit_sum(test_list, k)
print(f"The kth digit sum of the list of numbers is: {total_sum}")

Output

The kth digit sum of the list of numbers is: 12

Conclusion

In this article, we understood how to find the kth digit sum from a list of numbers in Python. Python is a versatile programming language that offers us various methods. We can either build our custom logic or use libraries available in Python to do so. Lambda functions, map method, etc., are convenient choices to make the code more concise. On the other hand, for better performance, we may use the Numpy library.

Updated on: 18-Jul-2023

65 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements