[Tutor] Python program to remove a specific digit from every element of list
Manprit Singh
manpritsinghece at gmail.com
Wed Apr 21 04:48:21 EDT 2021
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 ? why not in
numerical way
Regards
Manprit Singh
On Wed, Apr 21, 2021 at 1:16 PM Alan Gauld via Tutor <tutor at python.org>
wrote:
> 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
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list