दक्षता में सुधार करने के लिए, जब किसी सूची में एक sublist के लिए खोज
कोड (credits)
def match(pattern, list):
matches = []
m = len(list)
n = len(pattern)
rightMostIndexes = preprocessForBadCharacterShift(pattern)
alignedAt = 0
while alignedAt + (n - 1) < m:
for indexInPattern in xrange(n-1, -1, -1):
indexInlist = alignedAt + indexInPattern
x = list[indexInlist]
y = pattern[indexInPattern]
if indexInlist >= m:
break
if x != y:
r = rightMostIndexes.get(x)
if x not in rightMostIndexes:
alignedAt = indexInlist + 1
else:
shift = indexInlist - (alignedAt + r)
alignedAt += (shift > 0 and shift or alignedAt + 1)
break
elif indexInPattern == 0:
matches.append(alignedAt)
alignedAt += 1
return matches
def preprocessForBadCharacterShift(pattern):
map = { }
for i in xrange(len(pattern)-1, -1, -1):
c = pattern[i]
if c not in map:
map[c] = i
return map
if __name__ == "__main__":
matches = match("ana", "bananas")
for integer in matches:
print "Match at:", integer
print (matches == [1, 3] and "OK" or "Failed")
matches = match([1, 2, 3], [0, 1, 2,3 , 4, 5, 6])
for integer in matches:
print "list Match at:", integer
print (matches)
'मैं के लिए रेंज में (लेन (एल)): 'i में रेंज के लिए छोटा किया जा सकता है (लेन (एल) - लेन (ए)):' – eumiro
निश्चित रूप से, लेकिन मैं स्मृति में सूची बनाने के तरीके के साथ और सोच रहा था प्रत्येक प्रतिस्थापन के लिए, लेकिन केवल अंत में। या शायद एक सी कार्यान्वयन भी। – Maarten
डेटा ऑब्जेक्ट हमेशा 'int' होगा, मुझे लगता है? – moooeeeep