[Tutor] Python program to remove a specific digit from every element of list
Alan Gauld
alan.gauld at yahoo.co.uk
Wed Apr 21 03:45:22 EDT 2021
On 21/04/2021 08:09, Manprit Singh wrote:
> 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)]
> Is there any better implementation for this problem ? assignment
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]
>>> res2
[45, 479, 29, 56]
>>>
--
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