Find if a part of the integer from another integer is divisible by 7? The question states: 


  Given an integer A, and two indices Li, Ri. Find if the number from A which is bounded by the two indices is divisible by 7?
  
  For example if A = 357753
  indices Li = 3, Ri = 4, then the number is 77, which is divisible.


My program give a time limit exceeded when executed for larger numbers. Are there any other performance improvement can be done in my code. Or the whole method is wrong for the solution. Any help would be appreciated. "q" is the number of indices that will be provided as input.

First code (not optimized):

inp = raw_input()

q = input()



temp = ""

for i in range(q):

    l, r = map(int, raw_input().split())

    temp =  int(inp[l - 1:r])

    if temp % 7 == 0:

        print "YES"
    else:

        print "NO"


My second program is:

inp = input()

q = input()

temp = 0
length = len(str(inp)) - 1
for i in range(q):

    left, right = map(int, raw_input().split())

    temp = inp
    end = length - right + 1
    temp = temp / (10 ** end)
    mul = 1
    final = 0

    while right &gt;= left:

        cur = temp % 10
        temp = temp / 10
        right -= 1
        #print cur
        final += (cur * mul)
        mul = mul * 10


    if final % 7 == 0:

        print "YES"
    else:

        print "NO"
I'm not sure why you think the second one is "optimized"; the former at least looks faster to me.

Don't name variables temp - it tells you nothing about the actual job of the variable. q is also a bad name'; num_iters is clearer, and i is not used so just use an underscore instead.

Don't pre-initialize values, in this case temp. Assign to it only when you need to.

Don't use input - always use raw_input and explicit conversions.

Then you have

inp = raw_input()
num_iters = int(raw_input())

for _ in range(num_iters):
    l, r = map(int, raw_input().split())
    temp = int(inp[l - 1:r])

    if temp % 7 == 0:
        print "YES"
    else:
        print "NO"


which is simple enough to basically be ideal. A more advanced programmer might want to handle errors or put code into functions, but the advantages of those only really apply to larger programs.