NZEC error in python for WSTRING

I got NZEC error in my submission. It works on my computer and I,ve got no idea what the problem is.
Here is my code:

t=input();
while(t):
    s=raw_input()
    l=len(s)
    m=[0,0,0,0]
    j=0
    k=0
    ans=0
    while(j<l):
        d={}
        while(j<l and s[j]!='#'):
            if s[j] not in d.keys():
                d[s[j]]=1
            else:
                d[s[j]]+=1
            j+=1
        j+=1
        for n in range(0,3):
            m[n]=m[n+1]
        m[3]=max(d.values())
        k+=1
        an=m[0]+m[1]+m[2]+m[3]
        ans=max(an,ans)
    if k<4:
        print 0
    else:
        print ans+3
    t-=1

Iā€™d appreciate any help.Thanks.

The submitted code can be seen here.
http://www.codechef.com/viewsolution/2277945

max(d.values()) makes no sense when d is empty.

it happens when there is a ā€˜##ā€™ in the input string.