Python - Extract Rear K digits from Numbers
Last Updated :
09 Apr, 2023
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 : Last 4 digits extracted.
Method #1 : Using list comprehension + % operator
In this technique, we modulo each number with 10^K to get the desired last K digits of each number.
Python3
# Python3 code to demonstrate working of
# Extract Rear K digits from Numbers
# Using list comprehension + % operator
# initializing list
test_list = [5645, 23567, 34543, 87652, 2342]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# Getting remainder for each element
res = [ele % (10 ** K) for ele in test_list]
# printing result
print("Rear K digits of elements ? : " + str(res))
OutputThe original list is : [5645, 23567, 34543, 87652, 2342]
Rear K digits of elements ? : [645, 567, 543, 652, 342]
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2 : Using str() + slicing
In this, we perform task of getting rear elements using list slicing, and str() is used to convert each element to string.
Python3
# Python3 code to demonstrate working of
# Extract Rear K digits from Numbers
# Using str() + slicing
# initializing list
test_list = [5645, 23567, 34543, 87652, 2342]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# getting integer using int() after slicing string
res = [int(str(idx)[-K:]) for idx in test_list]
# printing result
print("Rear K digits of elements ? : " + str(res))
OutputThe original list is : [5645, 23567, 34543, 87652, 2342]
Rear K digits of elements ? : [645, 567, 543, 652, 342]
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #3 : Using map() function and lambda expression:
Algorithm:
1.Initialize a list, test_list, with some integers.
2.Initialize an integer, K, representing the number of digits to extract from the rear of each element in the list.
3.Apply the modulo operator to each element in the test_list with K.
4.Store the result of the above operation in a new list, res.
5.Return the res list.
Python3
# initializing list
test_list = [5645, 23567, 34543, 87652, 2342]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# using map() function and lambda expression to extract last K digits
res = list(map(lambda x: x % (10 ** K), test_list))
# printing result
print("Rear K digits of elements ? : " + str(res))
#This code is contributed by Jyothi pinjala
OutputThe original list is : [5645, 23567, 34543, 87652, 2342]
Rear K digits of elements ? : [645, 567, 543, 652, 342]
Time complexity: O(n), where n is the length of the test_list. The map function operates on each element in the test_list in O(1) time, and the list function takes O(n) time to create the final list.
Auxiliary Space: O(n), where n is the length of the test_list. The space required for the res list is O(n) and the space required for the test_list is O(n).
Method #4: Using a for loop and integer division and modulo operator
Step-by-step approach:
- Initialize an empty list to store the result.
- Loop through each element in the original list.
- Use integer division (//) and modulo (%) operator to extract the last K digits of each element.
- Append the extracted digits to the result list.
- Return the result list.
Below is the implementation of the above approach:
Python3
# initializing list
test_list = [5645, 23567, 34543, 87652, 2342]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# using for loop and integer division and modulo operator to extract last K digits
res = []
for num in test_list:
last_K_digits = num % (10 ** K)
res.append(last_K_digits)
# printing result
print("Rear K digits of elements ? : " + str(res))
OutputThe original list is : [5645, 23567, 34543, 87652, 2342]
Rear K digits of elements ? : [645, 567, 543, 652, 342]
Time complexity: O(n), where n is the length of the original list, since we're looping through each element once.
Auxiliary space: O(n), since we're creating a new list to store the result.
Method #5: Using list comprehension and string slicing
- Initialize the input list test_list with the given integers.
- Print the original list to confirm the input.
- Initialize the value of K to the given integer value.
- Use list comprehension to iterate over each number in test_list.
- Convert each number to a string using the str() function.
- Use string slicing to extract the last K characters from each string using the [-K:] syntax.
- Convert the resulting substring back to an integer using the int() function.
- Store the resulting integers in a list using the list comprehension syntax.
- Print the resulting list of integers to confirm the output.
Python3
# initializing list
test_list = [5645, 23567, 34543, 87652, 2342]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# using list comprehension and string slicing to extract last K digits
res = [int(str(num)[-K:]) for num in test_list]
# printing result
print("Rear K digits of elements ? : " + str(res))
OutputThe original list is : [5645, 23567, 34543, 87652, 2342]
Rear K digits of elements ? : [645, 567, 543, 652, 342]
time complexity of this method is O(n*K) where n is the length of the list and K is the number of digits to be extracted.
Auxiliary space complexity is O(n) because the result is stored in a list of size n.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read