[Tutor] Python program to remove a specific digit from every element of list
Alan Gauld
alan.gauld at yahoo.co.uk
Wed Apr 21 05:08:51 EDT 2021
On 21/04/2021 09:48, Manprit Singh wrote:
> Dear sir,
> So let me tell you why I have asked this question, actually this problem is
> purely a numerical problem, why to solve this using strings ?
Clearly it is not "purely a numerical problem" since it can be solved
using strings. It just depends on how you look at it. Is it about
removing a particular character or a particular number?
Why use strings rather than numbers? Look at the length of the code
for the two options. Look at the numbers of computations (each
computation is a potential error).
Which one is actually faster would require profiling and testing but
I doubt there is much difference, especially for small data sets.
For large datasets the string version will consume more memory.
>>> def remove_digit(x, n):
>>> """Function that removes digit n from a number x """
>>> ans, i = 0, 0
>>> while x != 0:
>>> x, rem = divmod(x, 10)
>>> if rem != n:
>>> ans = ans + (rem * 10**i)
>>> i = i + 1
>>> return ans
>>>
>>> lst = [333, 435, 479, 293, 536]
>>> ans = [remove_digit(ele, 3) for ele in lst if remove_digit(ele, 3)]
>>
>> Better? You decide. Shorter yes.
>>
>>>>> lst = [333, 435, 479, 293, 536]
>>>>> res = [str(n).replace('3','') for n in lst]
>>>>> res2 = [int(s) for s in res if s]
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list