I tried to make a Python program that removes specific digit from a number, example a = 12025 k = 2 result is 105, however none of the guides helped me do that, can anybody help me with that?
Asked
Active
Viewed 47 times
1
-
2You forgot to show us all the things you tried :) – Mathias R. Jessen Oct 05 '22 at 13:50
-
https://stackoverflow.com/questions/817122/delete-digits-in-python-regex – Renat Oct 05 '22 at 13:51
4 Answers
1
Conversion to string does not seem elegant. As pseudo-code:
number without digit (number, digit)
if number == digit
0
else if number < 10
number
else if number % 10 == digit
number without digit (number / 10, digit)
else
number without digit (number / 10, digit) * 10 + (number % 10)
Where /
is integer division, truncating the remainder, and %
is the modulo, remainder.
So it is a matter of recursion.

Joop Eggen
- 107,315
- 7
- 83
- 138
0
You have to convert into str
type, then remove the occurrencies, and go back to int
int(str(a).replace(str(k),''))

imburningbabe
- 742
- 1
- 2
- 13
0
If you want to use math rather than converting to and from string you can do
a = 12025
k = 2
result = 0
exp = 0
while a:
a, remainder = divmod(a, 10)
if remainder != k:
result = result + 10**exp * remainder
exp += 1

Steven Rumbalski
- 44,786
- 9
- 89
- 119