# Surprising results of time taken for executing code

I recently solved problem CSUB from the ‘Easy’ category.
The problem is:

Given a string S consisting of only 1s and 0s , find the number of substrings which start and end both in 1 .
In this problem, a substring is defined as a sequence of continuous characters Si, Si+1, …, Sj where 1 ≤ i ≤ j ≤ N .

When I submitted my solution as this code:

`````` testcases = int(input())                     # number of testcases
for o in range(testcases):
n = int(input())                         # length of string, useless for this logic
sstr = input()                           # given string
no1 = 0                                  # number of '1's in string
for x in range(len(sstr)):               #  \
if sstr[x] == "1":                   #   | - finding number of 1's in string
no1 += 1                          #  /
print(int(no1*(no1-1)/2 + no1))
``````

it required 0.06 sec to be executed.

But when this code was submitted:

`````` testcases = int(input())                     # number of testcases
for o in range(testcases):
n = int(input())                         # length of string, useless for this logic
sstr = int(input())                      # given string
no1 = 0                                  # number of '1's in string
for x in str(sstr):
if x == "1":
no1 = no1 + 1
print(int(no1*(no1-1)/2 + no1))
``````

it required 0.20 sec to be executed!!

Why is there so much of a difference?

This is because you are converting string to int. Note that you again converted the int to string. This adds some overhead. This is why there is so much difference in execution times.

Ohh…okay…
Thanks🙂

So, is it safe to assume that most of the times, the functions str() and int() must be avoided?

No. What I am saying is, both programs are not the same. They are not performing the same tasks. So, it is not fair to compare their times. They both are intended to do the same, but the way they are doing it is not the same.