Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python3 Program to Rotate digits of a given number by K
Next article icon

Python Program to Subtract K from each digit

Last Updated : 22 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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)

Method 3: Here is another approach to solve this problem using map and lambda functions:

Python3




# Python3 code to demonstrate working of
# Subtract K from each digit
# Using map and lambda function
  
# 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
  
# subtracting K from each digit using map and lambda
res = list(map(lambda ele: int(''.join([str(max(0, int(el) - K)) for el in str(ele)])), 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(nm) 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(nm)

Method 4 : Using a loop and modulo operator

Step-by-step approach:

Initialize the input list of numbers.
Initialize the value of K.
Create an empty list to store the results.
Loop through each number in the input list.
Convert the number to a string and create an empty string to store the new digits.
Loop through each digit in the string.
Subtract K from the digit using the modulo operator and append the result to the new digits string.
Convert the new digits string back to an integer and append it to the results list.
Return the results list.

Python3




# Python3 code to demonstrate working of
# Subtract K from each digit
# Using a loop and modulo 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
 
# Using a loop and modulo operator
res = []
for ele in test_list:
    new_digits = ''
    for digit in str(ele):
        new_digit = int(digit) - K
        new_digits += str(max(new_digit, 0))
    res.append(int(new_digits))
 
# 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 * k), where n is the number of elements in the list and k is the number of digits in each element.

Auxiliary space: O(n), where n is the number of elements in the list, for storing the results list.



Next Article
Python3 Program to Rotate digits of a given number by K
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python Program to Subtract Two Binary Numbers
    We are given two binary numbers, num1 and num2 and we have to subtract these two binary numbers and return the result. In this article, we will see how we can subtract two binary numbers in Python. Examples: Input: a = "1110" , b = "0110"Output: "1000"Explanation: We can see that when "1110" is subt
    3 min read
  • Python Program to print digit pattern
    The program must accept an integer N as the input. The program must print the desired pattern as shown in the example input/ output. Examples: Input : 41325 Output : |**** |* |*** |** |***** Explanation: for a given integer print the number of *'s that are equivalent to each digit in the integer. He
    3 min read
  • Python - Extract Rear K digits from Numbers
    Given an Integer list, extract rear K digits from it. Input : test_list = [5645, 23567, 34543, 87652, 2342], K = 2 Output : [45, 67, 43, 52, 42] Explanation : Last 2 digits extracted. Input : test_list = [5645, 23567, 34543, 87652, 2342], K = 4 Output : [5645, 3567, 4543, 7652, 2342] Explanation : L
    5 min read
  • Python Program to Find Sum of First and Last Digit
    Given a positive integer N(at least contain two digits). The task is to write a Python program to add the first and last digits of the given number N. Examples: Input: N = 1247 Output: 8 Explanation: First digit is 1 and Last digit is 7. So, addition of these two (1 + 7) is equal to 8.Input: N = 73
    5 min read
  • Python3 Program to Rotate digits of a given number by K
    INTRODUCTION:One important point to consider when working with the algorithm to rotate the digits of a given number by k positions is the time complexity. If we were to implement this algorithm using the approach shown in the previous example, the time complexity would be O(n), where n is the number
    4 min read
  • Python - Extract digits from given string
    We need to extract the digit from the given string. For example we are given a string s=""abc123def456gh789" we need to extract all the numbers from the string so the output for the given string will become "123456789" In this article we will show different ways to extract digits from a string in Py
    2 min read
  • Python - Subtract K from tuples list
    Sometimes, while working with data, we can have a problem in which we need to perform update operation on tuples. This can have application across many domains such as web development. Let’s discuss certain ways in which subtraction of K can be performed. Method #1 : Using list comprehension This is
    4 min read
  • Python program to replace first 'K' elements by 'N'
    Given a List, replace first K elements by N. Input : test_list = [3, 4, 6, 8, 4, 2, 6, 9], K = 4, N = 3 Output : [3, 3, 3, 3, 4, 2, 6, 9] Explanation : First 4 elements are replaced by 3. Input : test_list = [3, 4, 6, 8, 4, 2, 6, 9], K = 2, N = 10 Output : [10, 10, 6, 8, 4, 2, 6, 9] Explanation : Fi
    4 min read
  • Subtract Two Numbers in Python
    Subtracting two numbers in Python can be done in multiple ways. The most common methods include using the minus operator (-), defining a function, using a lambda function, or applying bitwise operations. Each method has its use cases depending on simplicity, readability and performance needs. Using
    2 min read
  • Python - Test if all digits starts from % K digit
    Sometimes we may face a problem in which we need to find for a list if it contains numbers which are % K. This particular utility has an application in day-day programming. Let’s discuss certain ways in which this task can be achieved. Method #1 : Using list comprehension + map() We can approach thi
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences