4 / 6
Nov 2015

When i submit this code it gives a time limit exceeded error. Please help me.

def charpat(l, c) : 
      for i in range(1, l+1 ) : 
          line = ""
          for j in range(1, c+1) : 
               if (i+j)%2 == 0: 
                  line = line + "*"
               else:
                   line = line + "."
          print(line) 

memory : 1060mb
time limit : 0.25s
  • created

    Nov '15
  • last reply

    Nov '15
  • 5

    replies

  • 1.2k

    views

  • 4

    users

Your algorithm is O(l * c). You could do this in O(c + l).

You should post your whole submission so that we can help you verify that there isn't some other issue as well.

The code above is just the definition of a function. If you submit it, the function will never be called, no output generated, resulting in TLE.

You have to add some code to process the input and to call your function with correct parameters.

E.g.

def main():
    number_of_cases = int(input())
    for dummy in range(number_of_cases):
        data = input().split()
        lines, columns = map(int, data)
        charpat(lines, columns)
        print()
if __name__ == "__main__": 
    main()

With this you can get accepted, although the algorithm can be optimized, as Leppy explained.