[Tutor] taking support of strings in solving numerical problems
Manprit Singh
manpritsinghece at gmail.com
Sat Oct 24 22:52:13 EDT 2020
Dear Sir,
I again got to learn something through this mail of yours . many many
thanks .
Actually i usually do not prefer to involve list while my final result is
to find the sum, So i have implemented your idea in the form of generator
function as written below:
def genfx_ser(x, lim):
sum_no = x
for i in range(lim):
yield sum_no
sum_no = (sum_no*10) + x
This feels more good to me . Now reason of putting yield inside for loop
is, let's say if someone tries to find the sum of series upto 0 terms by
writing
sum(genfx_series(9, 0)), He or she will get 0 as sum as there will be no
data in the iterator returned by generator function at that time.
I tested it for finding sum of series of 4 terms - 9 + 99 +999 + 9999 =
11106 by writing sum(genfx_series(9, 4)) and got the same output = 11106.
Need your humble suggestions on this example using generator functions .
Regards
Manprit Singh
On Sun, Oct 25, 2020 at 5:02 AM Alan Gauld via Tutor <tutor at python.org>
wrote:
> On 24/10/2020 20:22, Manprit Singh wrote:
>
> > Consider a problem a problem to find sum of series of the form :
> > a + aa + aaa + aaa
>
> > def sum_ser(x, lim): # definition
> > sum_no = 0
> > for i in range(lim):
> > sum_no = sum_no + int(str(x) * (i + 1))
> > return sum_no
>
> > I have seen in various scenarios, where using strings in a numerical
> > problem reduces the size of the program
> >
> > Using strings to solve numerical problems in such a way is a valid use
> case
> > ? should this practise be followed in production ?
>
> It is valid in the few cases where it is helpful but usually
> using math works better.
>
> For example in your case the algorithm is simple
>
> N2 = N1*10+x
>
> Where N1 is the previous total and x is the number.
> As a function:
>
> def generate_nums(x,n):
> nums = [x]
> for i in range(1,n):
> nums.append(nums[-1]*10 +x)
> return nums
>
> And the sum is just a case of applying sum():
>
> >>> sum(generate_nums(9,4))
> 11106
>
> And remember that string operations are quite slow compared
> to math - in addition to the two way conversions you have
> to create memory space, then expand that memory space.
> All relatively slow operations.
>
> Pure math will normally be faster.
>
> --
> 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