Hamming Distance Discussions | Algorithms | HackerRank
  • + 0 comments

    How to make this code run within time limit?

    def change(string, l, r, ch):
        l1 = list(string)
        first = "".join(l1[:l-1])
        for i in range(l-1, r):
            l1[i] = ch
        str1 = "".join(l1[l-1:r])
        last = "".join(l1[r:])
        rtnStr = first+str1+last
        return rtnStr
    
    
    def swap(string, l1, r1, l2, r2):
        l = list(string)
        first = "".join(l[:l1-1])
        str1 = "".join(l[l1-1:r1])
        str3 = "".join(l[r1:l2-1])
        str2 = "".join(l[l2-1:r2])
        last = "".join(l[r2:])
        rtnStr = first+str2+str3+str1+last
        # print(rtnStr)
        return rtnStr
    
    
    def reverse(string, l, r):
        l1 = list(string)
        first = "".join(l1[:l-1])
        nstr = "".join(l1[l-1:r])
        rstr = nstr[::-1]
        last = "".join(l1[r:])
    
        rtnStr = first+rstr+last
        # print(rtnStr)
        return rtnStr
    
    
    def hamming(string, l1, l2, r):
        str1 = string[l1-1:l1+r-1]
        str2 = string[l2-1:l2+r-1]
        count = 0
        for i in range(0, r):
            if str1[i] != str2[i]:
                count += 1
        print(count)
    
    
    def solveQuery(givenString, *a):
        if a[0] == 'C':
            givenString = change(givenString, int(a[1]), int(a[2]), a[3])
        elif a[0] == 'S':
            givenString = swap(givenString, int(
                a[1]), int(a[2]), int(a[3]), int(a[4]))
        elif a[0] == 'R':
            givenString = reverse(givenString, int(a[1]), int(a[2]))
        elif a[0] == 'W':
            print(givenString[int(a[1]) - 1:int(a[2])])
        else:
            hamming(givenString, int(a[1]), int(a[2]), int(a[3]))
        return givenString
    
    
    def callFunction(l, n, s):
        for i in range(0, n):
            prams = l[i].split(" ")
            s = solveQuery(s, *prams)
    
    
    if __name__ == "__main__":
        l = int(input())
        s = input()
        n = int(input())
        querys = []
        for i in range(0, n):
            querys.append(input())
        callFunction(querys, n, s)