Python 3 - My code gets timed out for higher conditions can anyone help me optimise it
#!/bin/python3 import math import os import random import re import sys mat = [] a = 0 c =0 # Complete the cipher function below. def cipher(n,k, s): global a global c global mat mat.append(s[0]) for i in range(1,n): if i < k: a = 0 for j in range (i): a += int(mat[j],2) e = bin(a) b = e[-1] if s[i] == b: mat.append("0") else: mat.append("1") else: c = 0 q = i-k+1 for q in range(i-k+1,i): c += (int(mat[q],2)) f = bin(c) d = f[-1] if s[i]== d: mat.append("0") else: mat.append("1") return "".join(mat) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nk = input().split() n = int(nk[0]) k = int(nk[1]) s = input() result = cipher(n,k, s) fptr.write(result + '\n') fptr.close()