Skip to content

Implementations of z array and algorithm for string matching #467

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
14 changes: 9 additions & 5 deletions pydatastructs/miscellaneous_data_structures/tests/test_stack.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from pydatastructs.utils.raises_util import raises
from pydatastructs.utils.misc_util import _check_type


def test_Stack():
s = Stack(implementation='array')
s1 = Stack()
Expand All @@ -12,6 +13,7 @@ def test_Stack():
assert _check_type(s2, LinkedListStack) is True
assert raises(NotImplementedError, lambda: Stack(implementation=''))


def test_ArrayStack():
s = Stack(implementation='array')
s.push(1)
Expand All @@ -23,11 +25,12 @@ def test_ArrayStack():
assert s.pop() == 2
assert s.pop() == 1
assert s.is_empty is True
assert raises(IndexError, lambda : s.pop())
assert raises(IndexError, lambda: s.pop())
_s = Stack(items=[1, 2, 3])
assert str(_s) == '[1, 2, 3]'
assert len(_s) == 3


def test_LinkedListStack():
s = Stack(implementation='linked_list')
s.push(1)
Expand All @@ -39,16 +42,17 @@ def test_LinkedListStack():
assert s.pop().key == 2
assert s.pop().key == 1
assert s.is_empty is True
assert raises(IndexError, lambda : s.pop())
assert raises(IndexError, lambda: s.pop())
assert str(s) == '[]'
_s = Stack(implementation='linked_list',items=[1, 2, 3])
_s = Stack(implementation='linked_list', items=[1, 2, 3])
assert str(_s) == "['(1, None)', '(2, None)', '(3, None)']"
assert len(_s) == 3

s = Stack(implementation='linked_list',items=['a',None,type,{}])
s = Stack(implementation='linked_list', items=['a', None, type, {}])
assert len(s) == 4
assert s.size == 4

peek = s.peek
assert peek.key == s.pop().key
assert raises(TypeError, lambda: Stack(implementation='linked_list', items={0, 1}))
assert raises(TypeError, lambda: Stack(
implementation='linked_list', items={0, 1}))
93 changes: 93 additions & 0 deletions pydatastructs/strings/Z_function.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@

# from pydatastructs.utils.misc_util import (
# Backend, raise_if_backend_is_not_python)


"""Suppose we are given a string s of length n. The Z-function for this string is an array
of length n where the i-th element is equal to the greatest number of characters starting
from the position i that coincide with the first characters of s.

In other words, z[i] is the length of the longest string that is, at the same time, a
prefix of s and a prefix of the suffix of s starting at i."""


def search(text, pattern):

# Create concatenated string "P$T"
concat = pattern + "$" + text
l = len(concat)

# Construct Z array
z = [0] * l
Z_Array(concat, z)

# now looping through Z array for matching condition
for i in range(l):

# if Z[i] (matched region) is equal to pattern
# length we got the pattern
if z[i] == len(pattern):
return i - len(pattern) - 1


def Z_Array(string, z):
n = len(string)

# [L,R] make a window which matches
# with prefix of s
l, r, k = 0, 0, 0
for i in range(1, n):

# if i>R nothing matches so we will calculate.
# Z[i] using naive way.
if i > r:
l, r = i, i

# R-L = 0 in starting, so it will start
# checking from 0'th index. For example,
# for "ababab" and i = 1, the value of R
# remains 0 and Z[i] becomes 0. For string
# "aaaaaa" and i = 1, Z[i] and R become 5
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
else:

# k = i-L so k corresponds to number which
# matches in [L,R] interval.
k = i - l

# if Z[k] is less than remaining interval
# then Z[i] will be equal to Z[k].
# For example, str = "ababab", i = 3, R = 5
# and L = 2
if z[k] < r - i + 1:
z[i] = z[k]

# For example str = "aaaaaa" and i = 2,
# R is 5, L is 0
else:

# else start from R and check manually
l = i
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1


"""If the programmer only needs the values of Z array for other appllications of this algorithm
such as String compression
"""


def Z_function(pattern, text):
concat = pattern + "$" + text

l = len(concat)

# Construct Z array
z = [0] * l
Z_Array(concat, z)
return z