forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Z_Algorithm.py
83 lines (59 loc) · 2.31 KB
/
Z_Algorithm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Z ALgorithm Function
def Z__Algo(text, pattern):
List = []
substring = ""
""" Iterating upto the index where the substring can occur """
for text_index in range(0, len(text) - len(pattern)+1):
""" Extracting the --substring of the same length as pattern-- from the text """
substring = text[text_index:text_index + len(pattern)]
""" Loop for comparing the substring and pattern """
count = 0
for substring_index in range(0, len(pattern)):
""" If the charecters of substring and pattern matches , increment count by 1 """
if substring[substring_index] == pattern[substring_index]:
count += 1
""" If all the charecters of substring and pattern matches , add position to list """
if count == len(pattern):
List.append(text_index)
""" Return the list that contains all the positions the substring is present at """
return List
# Searching Process Driver Code
if __name__ == '__main__':
text = input("Enter Text : ")
pattern = input("Enter pattern : ")
"""Calling Z__Algo to seacrh the substring positions"""
positions = Z__Algo(text, pattern)
"""If returned list from Z__Algo is not empty , print positions , else prompt -- pattern not found"""
if len(positions) != 0:
for position in positions:
print("The pattern is present at : " + str(position))
else:
print("Pattern Not Found !!!")
"""
Input description:
Line 1 -- Text
Line 2 -- Pattern
Output Description :
The pattern is present at : position_index
...
...
Input 1:
aaaabbabbababaabbabaaaa
aa
Ouput 1:
The pattern is present at : 0
The pattern is present at : 1
The pattern is present at : 2
The pattern is present at : 13
The pattern is present at : 19
The pattern is present at : 20
The pattern is present at : 21
Input 2:
bbbabbabbaccdcbshdddhh
bb
Output 2:
The pattern is present at : 0
The pattern is present at : 1
The pattern is present at : 4
The pattern is present at : 7
"""