Skip to content

Commit 5fa8b96

Browse files
authored
Merge pull request AllAlgorithms#17 from beingadityak/master
4 String Algorithms in Python
2 parents 66bfe1b + d3d6613 commit 5fa8b96

File tree

4 files changed

+188
-0
lines changed

4 files changed

+188
-0
lines changed

strings/anagram_search.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#!/usr/bin/env python3
2+
3+
"""
4+
Pythonic Implementation of Anagram search
5+
"""
6+
7+
__author__ = "Aditya Krishnakumar"
8+
9+
import collections
10+
11+
# remove whitespaces
12+
def remove_whitespace(string):
13+
return ''.join(string.split())
14+
15+
"""
16+
Checks if two strings are anagrams of each other, ignoring any whitespace.
17+
18+
First remove any whitespace and lower all characters of both strings.
19+
Then create dictionaries of the counts of every character in each string.
20+
As well as keep a set of all characters used in both strings.
21+
Check to ensure every unique character are used in both strings the
22+
same number of times.
23+
"""
24+
25+
def is_anagram(string1, string2):
26+
charCount1 = collections.Counter(remove_whitespace(string1.lower()))
27+
charCount2 = collections.Counter(remove_whitespace(string2.lower()))
28+
29+
allChars = set(charCount1.keys())
30+
allChars = allChars.union(charCount2.keys())
31+
32+
for c in allChars:
33+
if (charCount1[c] != charCount2[c]):
34+
return False
35+
36+
return True
37+
38+
# Dry runs
39+
40+
assert is_anagram("anagram", "not a gram") == False
41+
assert is_anagram("anagram", "na a marg") == True
42+
assert is_anagram("William Shakespeare", "I am \t a weakish speller") == True
43+
assert is_anagram("Madam Curie", "Radium came") == True
44+
assert is_anagramg("notagram", "notaflam") == False

strings/morse_code.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#!/usr/bin/env python
2+
"""
3+
Pythonic Implementation of Morse Code encoding
4+
"""
5+
6+
__author__ = "Aditya Krishnakumar"
7+
8+
9+
# The alphabet dictionary for morse codes
10+
morseAlphabet = {
11+
"A": ".-",
12+
"B": "-...",
13+
"C": "-.-.",
14+
"D": "-..",
15+
"E": ".",
16+
"F": "..-.",
17+
"G": "--.",
18+
"H": "....",
19+
"I": "..",
20+
"J": ".---",
21+
"K": "-.-",
22+
"L": ".-..",
23+
"M": "--",
24+
"N": "-.",
25+
"O": "---",
26+
"P": ".--.",
27+
"Q": "--.-",
28+
"R": ".-.",
29+
"S": "...",
30+
"T": "-",
31+
"U": "..-",
32+
"V": "...-",
33+
"W": ".--",
34+
"X": "-..-",
35+
"Y": "-.--",
36+
"Z": "--..",
37+
"1": ".----",
38+
"2": "..---",
39+
"3": "...--",
40+
"4": "....-",
41+
"5": ".....",
42+
"6": "-....",
43+
"7": "--...",
44+
"8": "---..",
45+
"9": "----.",
46+
"0": "-----"
47+
}
48+
49+
# Lambda function for decoding the code to alphabet
50+
inverseAlphabet = reduce(lambda a, b: dict(a.items() + b.items()),
51+
[{
52+
morseAlphabet[k]: k
53+
} for k in morseAlphabet.keys()], {})
54+
55+
56+
def encode(_text):
57+
return ' '.join([morseAlphabet[_c.upper()] for _c in _text[:]])
58+
59+
60+
def decode(_text):
61+
return ''.join([inverseAlphabet[_c] for _c in _text.split(' ')])
62+
63+
# Dry runner
64+
def test():
65+
print decode(encode("TEST")) == "TEST"
66+
67+
68+
if __name__ == "__main__":
69+
test()

strings/password_checker.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#!/usr/bin/env python3
2+
3+
import re, pyperclip
4+
5+
password = pyperclip.paste()
6+
7+
eightLettersRegex = re.compile(r'\S{8,}')
8+
oneUppercaseRegex = re.compile(r'[A-Z]')
9+
oneNumberRegex = re.compile(r'\d')
10+
11+
check = {
12+
eightLettersRegex: 'Your password must be 8 letters',
13+
oneUppercaseRegex: 'Your password must have at least one uppercase Letter.',
14+
oneNumberRegex: 'Your password must have at least one number.'
15+
}
16+
17+
print('Analyzing your password.')
18+
19+
count = 1
20+
for regex, msg in check.items():
21+
mo = regex.search(password)
22+
if mo == None:
23+
print(msg)
24+
break
25+
if count == len(check):
26+
print('Good! Your password is strong enough!')
27+
count += 1
28+
29+
print('End.')

strings/rabin_karp.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#!/usr/local/bin/env python3
2+
3+
# Rabin Karp Algorithm in python using hash values
4+
# d is the number of characters in input alphabet
5+
d = 2560
6+
7+
8+
def search(pat, txt, q):
9+
M = len(pat)
10+
N = len(txt)
11+
i = 0
12+
j = 0
13+
14+
p = 0
15+
t = 0
16+
h = 1
17+
18+
for i in range(M - 1):
19+
h = (h * d) % q
20+
21+
for i in range(M):
22+
p = (d * p + ord(pat[i])) % q
23+
t = (d * t + ord(txt[i])) % q
24+
25+
for i in range(N - M + 1):
26+
if p == t:
27+
for j in range(M):
28+
if txt[i + j] != pat[j]:
29+
break
30+
31+
j += 1
32+
if j == M:
33+
print("Pattern found at index " + str(i))
34+
35+
if i < N - M:
36+
t = (d * (t - ord(txt[i]) * h) + ord(txt[i + M])) % q
37+
if t < 0:
38+
t = t + q
39+
40+
41+
# Driver program to test the above function
42+
txt = "ALL WORLDS IS A STAGE AND ALL OF US ARE A PART OF THE PLAY"
43+
pat = "ALL"
44+
45+
q = 101 # A prime number
46+
search(pat, txt, q)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy