Print the list of integers from through as a string without spaces
Python Program to Convert a list of multiple integers into a single integerGiven a list of integers, write a Python program to convert the given list into a single integer. Examples: Input : [1, 2, 3] Output : 123 Input : [55, 32, 890] Output : 5532890There are multiple approaches possible to convert the given list into a single integer. Lets see each one by one. Approach #1 : Naive Method
Output: 121517
Use the join() method of Python. First convert the list of integer into a list of strings( as join() works with strings only). Then, simply join them using join() method. It takes a time complexity of O(n).
Output: 123
Another approach to convert a list of multiple integers into a single integer is to use map() function of Python with str function to convert the Integer list to string list. After this, join them on the empty string and then cast back to integer.
Output: 123
A more mathematical way, which does not require to convert the integer list to string list is, to multiply each integer element with its corresponding power of 10, and then summing it up. It takes a time complexity of O(n).
Output: 123A small variation to this program leads to less computation in calculation of sum, i.e. using reduce(). This makes use of Horners rule, which factors the polynomial representing the number to reduce the number of multiplications.
Article Tags :
Python
Python list-programs python-list Practice Tags :
python-list
Read Full Article
|