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
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"))