[Tutor] taking support of strings in solving numerical problems

Manprit Singh manpritsinghece at gmail.com
Sat Oct 24 15:22:27 EDT 2020


Dear sir ,

Consider a problem a problem to find sum of series of the form :
a + aa + aaa + aaa
like
9 + 99 + 999 + 9999 that equals 11106

I have solved this using strings as given  below :

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

sum_ser(9, 4)                             # call to find sum of series 9 +
99 + 999 + 9999

which gives the correct answer = 11106
Here in the for loop inside function definition, you can see i have first
converted
the integer x to string then multiplied this string by (i+1) and then again
converted this string to integer .
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 ?

Regards
Manprit Singh

Regards
Manprit Singh


More information about the Tutor mailing list