Home > database >  I need to subtract 1 from each digit in the list .is It any easy way?
I need to subtract 1 from each digit in the list .is It any easy way?

Time:11-23

This is the list I have :

list_input = [432567,876323,124356]

This is the Output I need :

List_output = [321456,765212,013245] 

like so,

for index, number in  enumerate(list_input):
           one_number = list_lnput(index)
           one_digit_list = list(one_number[0])

and I don't have Idea after this step

CodePudding user response:

This can be solved in a time complexity of O(1) since you're basically asking to subtract a number of 1's from an integer i, where the number is equal to the number of digits of that integer, which can be obtained by calculating int(math.log10(i)) 1, with which you can produce the same number of 1's with (10 ** (int(math.log10(i)) 1) - 1) // 9:

import math

def decrement_digits(i):
    return i - (10 ** (int(math.log10(i))   1) - 1) // 9

so that decrement_digits(432567), for example, would return:

321456

so you can then map the input list to the function for output:

List_output = list(map(decrement_digits, list_input))

CodePudding user response:

divmod can be used to isolate each digit in turn. Remember the decimal positions (1's, 10's, 100's, etc...) to add it back in correctly. This will be messy for zeroes. But we don't have any definition what should happen in that case, so I'm sticking with it.

Putting the logic into its own function makes it easier to write the process as a list comprehension. I think its also easier to read than trying to maintain an index.

def digit_subtract(num):
    result = 0
    base = 1
    while num:
        num, remain = divmod(num, 10)
        result  = (remain-1) * base
        base *= 10
    return result

list_input = [432567,876323,124356]
List_output = [321456,765212,13245]

test = [digit_subtract(num) for num in list_input]
print(test)
assert test == List_output

CodePudding user response:

The only way to get the output with leading zeros is to cast the intS to strS.

list_input = [432567,876323,124356]
list_output = [''.join(str(int(digit)-1) for digit in str(s)) 
               for s in list_input]

Note that this will result in a ValueError for input with negative numbers:

list_input = [-4306]
list_output = [''.join(str(int(digit)-1) for digit in str(s)) 
               for s in list_input]
print(list_output)

Traceback (most recent call last):
  File "/Users/michael.ruth/SO/solution.py", line 2, in <module>
    list_output = [''.join(str(int(digit)-1) for digit in str(s))
  File "/Users/michael.ruth/SO/solution.py", line 2, in <listcomp>
    list_output = [''.join(str(int(digit)-1) for digit in str(s))
  File "/Users/michael.ruth/SO/solution.py", line 2, in <genexpr>
    list_output = [''.join(str(int(digit)-1) for digit in str(s))
ValueError: invalid literal for int() with base 10: '-'
  • Related