Skip to content
Related Articles

Related Articles

Python Program to Subtract K from each digit

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 11 Jul, 2022
Improve Article
Save Article

Given a list, the task is to write a Python Program to subtract K from each digit, if the element gets below 0, retain 0.

Examples:

Input : test_list = [2345, 8786, 2478, 8664, 3568, 28], K = 4

Output : [1, 4342, 34, 4220, 124, 4]

Explanation : In 2345, 4 subtracted from 2 is -2, hence ceiled to 0. Hence just 5-4 = 1, is retained. and thus output.

Input : test_list = [2345, 8786, 2478, 8664, 3568, 28], K = 3

Output : [12, 5453, 145, 5331, 235, 5]

Explanation : In 2345, 3 subtracted from 2 is -1, hence ceiled to 0. Hence just 5-3 = 2 and 4-3 = 1, are retained. and thus output.

Method 1: Using str() + – operator

In this, we convert the integer to string and perform subtraction by converting each digit to integer, the result is joined again and type cast back to integer.

Python3




# Python3 code to demonstrate working of
# Subtract K from each digit
# Using str() and - operator
 
# initializing list
test_list = [2345, 8786, 2478, 8664, 3568, 28]
              
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 4
 
res = []
for ele in test_list:
    str_ele = str(ele)
     
    # getting maximum of 0 or negative value using max()
    # conversion of each digit to int
    new_ele = int(''.join([ str(max(0, int(el) - K)) for el in str_ele]))
    res.append(new_ele)
 
# printing result
print("Elements after subtracting K from each digit : " + str(res))


Output:

The original list is : [2345, 8786, 2478, 8664, 3568, 28]

Elements after subtracting K from each digit : [1, 4342, 34, 4220, 124, 4]

Time Complexity: O(n*m) where n is the number of elements in the list and m is the maximum number of digits in any element of the list.
Auxiliary Space: O(n*m)

Method 2: Using list comprehension

Similar to above method, just list comprehension is used for the task of providing a shorthand.

Python3




# Python3 code to demonstrate working of
# Subtract K from each digit
# Using list comprehension
 
# initializing list
test_list = [2345, 8786, 2478, 8664, 3568, 28]
              
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 4
 
# list comprehension providing shorthand
res = [int(''.join([ str(max(0, int(el) - K)) for el in str(ele)]))
       for ele in test_list]
 
# printing result
print("Elements after subtracting K from each digit : " + str(res))


Output:

The original list is : [2345, 8786, 2478, 8664, 3568, 28]

Elements after subtracting K from each digit : [1, 4342, 34, 4220, 124, 4]

Time Complexity: O(n*m) where n is the number of elements in the list and m is the maximum number of digits in any element of the list.
Auxiliary Space: O(n*m)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!