Skip to content
Related Articles

Related Articles

Improve Article

Python Program to Subtract K from each digit

  • Last Updated : 06 Jun, 2021

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]



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]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :