What is a faster version of this code instead of the double for-loop (python)?

后端 未结 1 1652
礼貌的吻别
礼貌的吻别 2020-12-22 13:18

When I hand this code in on a site (from my university) that corrects it, it is too long for its standards. Here is the code:

def pangram(String):
    import         


        
相关标签:
1条回答
  • 2020-12-22 13:29

    Create a map {letter; int} and activecount counter.
    Make two indexes left and right, set them in 0.

    Move right index.
    If l=s[right] is letter, increment value for map key l.
    If value becomes non-zero - increment activecount.
    Continue until activecount reaches 26

    Now move left index.
    If l=s[left] is letter, decrement value for map key l.
    If value becomes zero - decrement activecount and stop.

    Start moving right index again and so on.

    Minimal difference between left and right while
    activecount==26 corresponds to the shortest pangram.

    Algorithm is linear.

    Example code for string containing only lower letters from alphabet 'abcd'. Returns length of the shortest substring that contains all letters from abcd. Does not check for valid chars, is not thoroughly tested.

    import string
    def findpangram(s):
        alfabet = list(string.ascii_lowercase)
        map = dict(zip(alfabet, [0]*len(alfabet)))
        left = 0
        right = 0
        ac = 0
        minlen = 100000
    
        while left < len(s):
    
            while right < len(s):
                l = s[right]
                c = map[l]
                map[l] = c + 1
                right += 1
                if c==0:
                    ac+=1
                    if ac == 4:
                        break
            if ac < 4:
                break
            if right - left < minlen:
                minlen = right - left
    
            while left < right:
                l = s[left]
                c = map[l]
                map[l] = c - 1
                left += 1
                if c==1:
                    ac-=1
                    break
    
            if right - left + 2 < minlen:
                minlen = right - left + 1
        return minlen
    
    print(findpangram("acacdbcca"))
    
    0 讨论(0)
提交回复
热议问题