[Tutor] taking support of strings in solving numerical problems

Alan Gauld alan.gauld at yahoo.co.uk
Sun Oct 25 03:59:47 EDT 2020


On 25/10/2020 02:52, Manprit Singh wrote:

> 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.

The logic on yield is good, but if the loop is not entered
the user gets None returned(the default value) not 0.
These are different values.

You really should put a return 0 in an if test for that scenario.

if lim == 0: return 0

Programming conventions suggest that should in fact be the first
line of the function because its good practice to check  for
invalid or edge case input before handling the normal case.

However a better solution, rather than handing back a number
with special meaning would be to throw an exception - ValueError
being the obvious choice. So the first line of the function
could be:

if lim <= 0: raise ValueError("lim must be greater than zero")

You might like to check that x is an int too.... Or try
converting it to an int.

> Need your humble suggestions on this example using generator functions .

It's a  reasonable use case for a generator since lim could potentially
be a large value.

-- 
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