[Tutor] taking support of strings in solving numerical problems
Alan Gauld
alan.gauld at yahoo.co.uk
Sat Oct 24 19:31:44 EDT 2020
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
More information about the Tutor
mailing list