Skip to content

Commit 94a175d

Browse files
committed
adding python code samples
1 parent f31c922 commit 94a175d

6 files changed

+364
-0
lines changed

17-wordle-wiz.c

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#include <stdio.h>
2+
#include <string.h>
3+
#include <stdlib.h>
4+
5+
/* We will limit this Trie to only 5 letter words because it's focused on the
6+
* Wordle game.
7+
*/
8+
#define WORD_SIZE 6
9+
#define ALPHABET_SIZE 26
10+
11+
struct TrieNode {
12+
char prefix [WORD_SIZE];
13+
int isword;
14+
struct TrieNode* children [ALPHABET_SIZE];
15+
};
16+
17+
struct TrieNode* createnode(void){
18+
struct TrieNode* t = malloc(sizeof(struct TrieNode));
19+
20+
if(!t) exit(1);
21+
t->prefix[0] = '\0';
22+
t->isword = 0;
23+
for(int i = 0; i < ALPHABET_SIZE; i++){
24+
t->children[i] = NULL;
25+
}
26+
return t;
27+
}

python/01-word-search-tmp.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
def setup(words):
2+
for w in words:
3+
1
4+
5+
def find_words(search_str, words):
6+
fwords = list()
7+
return fwords
8+
9+
words = ['apple', 'ape', 'bar', 'barn', 'bark']
10+
setup(words)
11+
print("Search 'pear', expect [] : result {}".format(find_words("pear", words)))
12+
print("Search 'ap*', expect ['ape'] : result {}".format(find_words("ap*", words)))
13+
print("Search 'bar*', expect ['barn', 'bark'] : result {}".format(find_words("bar*", words)))

python/01-word-search.py

+116
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
# A Program to Implement a word search with wildcards
2+
# This version uses a single Trie structure to search for words
3+
4+
# Node Class
5+
# value - each node has a value which is a single character
6+
# children - each node has a dictionary of child nodes. the key is the
7+
# character represented by the child node
8+
# is_word - a boolean value indicating if this node is the end of
9+
# a "word path".
10+
class Node:
11+
def __init__(self, value, is_word):
12+
self.value = value
13+
self.children = {}
14+
self.is_word = is_word
15+
16+
def add_to_trie(word, root):
17+
# recursion base case
18+
if len(word) == 0:
19+
root.is_word = True
20+
return
21+
22+
# split off the first character of the current word
23+
first_char = word[0:1]
24+
sufx = word[1:]
25+
26+
# recursive step
27+
if first_char in root.children:
28+
add_to_trie(sufx, root.children[first_char])
29+
else:
30+
new_node = Node(first_char, False)
31+
root.children[first_char] = new_node
32+
add_to_trie(sufx, new_node)
33+
34+
def setup(words, root):
35+
for w in words:
36+
add_to_trie(w.strip(), root)
37+
38+
# convenience function to initiate recursion
39+
def find_words(word, node, num_visits):
40+
fwords = list()
41+
return find_words_r(word, node, fwords, num_visits)
42+
43+
# recursive search
44+
def find_words_r(word, node, fwords, num_visits, path=""):
45+
num_visits[0] +=1
46+
47+
# recursion base case
48+
if len(word) == 0:
49+
if node.is_word:
50+
fwords.append(path)
51+
return fwords
52+
53+
# split the first character off the curent word
54+
first_char = word[0:1]
55+
sufx = word[1:]
56+
57+
# recursive step
58+
if first_char in node.children:
59+
return find_words_r(sufx, node.children[first_char], fwords, num_visits, path + first_char)
60+
elif first_char == '.':
61+
for k in node.children.keys():
62+
find_words_r(sufx, node.children[k], fwords, num_visits, path + k)
63+
return fwords
64+
else:
65+
return fwords
66+
67+
68+
# Main Program
69+
words = list()
70+
root = Node("", False)
71+
72+
with open("16-words_alpha.txt") as f:
73+
74+
# Read the dictionary file into a list
75+
words = list(f)
76+
setup(words, root)
77+
print("Loaded {} words.".format(len(words)))
78+
79+
# Do the search
80+
num_visits = [0]
81+
fwords = find_words(".one", root, num_visits)
82+
83+
# Print the results
84+
print("Found words: {}. Visited: {}".format(len(fwords), num_visits[0]))
85+
print(fwords)
86+
87+
88+
# WORDLE SOLVER
89+
# The next lines are extra work to further filter the list of found words
90+
# by excluding words with certain characters or requiring that the words
91+
# contain certain characters. There is also an option to prohibit characters
92+
# in specific positions which is used to override the list of included characters
93+
# by specifying that they cannot exist in certain positions.
94+
exclude = ['i', 'l', 'c', 'r']
95+
include = ['d', 'e', 'a']
96+
anti_positions = {'1':'d', '2':'e'}
97+
98+
candidates = []
99+
for w in fwords:
100+
candidate = True
101+
for c in exclude:
102+
if c in w:
103+
candidate = False
104+
for c in include:
105+
if c not in w:
106+
candidate = False
107+
for k, v in anti_positions.items():
108+
if w[int(k)] == v:
109+
candidate = False
110+
if candidate:
111+
candidates.append(w)
112+
113+
# print("Found words: {}. Visited: {}".format(len(candidates), num_visits[0]))
114+
# print(candidates)
115+
116+

python/02-word-search.py

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# A Program to Implement a word search with wildcards
2+
# This version breaks the search space into partitions by word length
3+
# and creates a unique Trie for all unique word lengths in the dictionary
4+
5+
class Node:
6+
def __init__(self, value, is_word):
7+
self.value = value
8+
self.children = {}
9+
self.is_word = is_word
10+
11+
def add_to_trie(word, root):
12+
if len(word) == 0:
13+
root.is_word = True
14+
return
15+
16+
first_char = word[0:1]
17+
sufx = word[1:]
18+
19+
if first_char in root.children:
20+
add_to_trie(sufx, root.children[first_char])
21+
else:
22+
new_node = Node(first_char, False)
23+
root.children[first_char] = new_node
24+
add_to_trie(sufx, new_node)
25+
26+
def setup(words, roots):
27+
for w in words:
28+
if len(w.strip()) in roots:
29+
add_to_trie(w.strip(), roots[len(w.strip())])
30+
else:
31+
roots[len(w.strip())] = Node("", False)
32+
add_to_trie(w.strip(), roots[len(w.strip())])
33+
34+
def find_words(word, node, num_visits):
35+
fwords = list()
36+
return find_words_r(word, node, fwords, num_visits)
37+
38+
def find_words_r(word, node, fwords, num_visits, path=""):
39+
num_visits[0] +=1
40+
if len(word) == 0:
41+
if node.is_word:
42+
fwords.append(path)
43+
return fwords
44+
45+
first_char = word[0:1]
46+
sufx = word[1:]
47+
48+
if first_char in node.children:
49+
return find_words_r(sufx, node.children[first_char], fwords, num_visits, path + first_char)
50+
elif first_char == '.':
51+
for k in node.children.keys():
52+
find_words_r(sufx, node.children[k], fwords, num_visits, path + k)
53+
return fwords
54+
else:
55+
return fwords
56+
57+
words = list()
58+
roots = dict()
59+
60+
with open("16-words_alpha.txt") as f:
61+
words = list(f)
62+
setup(words, roots)
63+
print("Loaded {} words.".format(len(words)))
64+
65+
# Do the search
66+
num_visits = [0]
67+
word_to_find = "..."
68+
if(len(word_to_find) in roots):
69+
fwords = find_words(word_to_find, roots[len(word_to_find)], num_visits)
70+
print("Found words: {}. Visited: {}".format(len(fwords), num_visits[0]))
71+
print(fwords)
72+
else:
73+
print("Found words: {}. Visited: {}".format(0, num_visits[0]))
74+

python/03-count-islands-tmp.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Count the Islands in a 2D Matrix
2+
#
3+
# You are given a 2D binary matrix as an input. You want to
4+
# return the number of islands in the binary matrix. You can
5+
# think of the 0's as the ocean and the 1's as land. An island
6+
# is surrounded by water and is formed by connecting adjacent
7+
# lands horizontally or vertically. You goal is to return the
8+
# correct number of islands.
9+
10+
def count_islands(matrix):
11+
return 0
12+
13+
# Clean Sample Matrix
14+
matrix1 = [
15+
[1,1,0,0,0],
16+
[0,1,0,0,1],
17+
[1,0,0,1,1],
18+
[1,0,1,0,1]
19+
]
20+
21+
print("Matrix has {} islands (expect 4)".format(count_islands(matrix1)))

python/03-count-islands.py

+113
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
def print_matrix(matrix):
2+
if matrix == None:
3+
return
4+
for i in range(len(matrix)):
5+
print(" ", end="")
6+
for j in range(len(matrix[i])):
7+
print(matrix[i][j], end="")
8+
print("")
9+
10+
def count_islands(matrix):
11+
# check input
12+
if matrix == None \
13+
or (not isinstance(matrix,list)) \
14+
or (not all(isinstance(ele, list) for ele in matrix)):
15+
return 0
16+
17+
# create new matrix to keep track of visits
18+
visited = [[False for _ in range(len(matrix[0]))] for _ in range(len(matrix))]
19+
20+
num_islands = 0
21+
22+
for i in range(len(matrix)):
23+
for j in range(len(matrix[i])):
24+
if matrix[i][j] == 1 and not visited[i][j]:
25+
dfs(i, j, matrix, visited)
26+
num_islands += 1
27+
28+
return num_islands
29+
30+
def dfs(i, j, matrix, visited):
31+
if i in range(len(matrix)) and j in range(len(matrix[i])) \
32+
and matrix[i][j] == 1 \
33+
and visited[i][j] == False:
34+
35+
visited[i][j] = True
36+
dfs(i-1, j, matrix, visited) # visit north
37+
dfs(i+1, j, matrix, visited) # visit south
38+
dfs(i, j+1, matrix, visited) # visit east
39+
dfs(i, j-1, matrix, visited) # visit west
40+
41+
42+
# Clean Sample Matrix
43+
matrix1 = [
44+
[1,1,0,0,0],
45+
[0,1,0,0,1],
46+
[1,0,0,1,1],
47+
[1,0,1,0,1]
48+
]
49+
50+
print_matrix(matrix1)
51+
print("Matrix has: {} islands (expect 4)".format(count_islands(matrix1)))
52+
53+
# PR Example Matrix
54+
matrix2 = [
55+
[1,1,0,0,0],
56+
[0,1,0,0,1],
57+
[1,0,0,1,1],
58+
[0,0,0,0,0],
59+
[1,0,1,0,1]
60+
]
61+
62+
print_matrix(matrix2)
63+
print("Matrix has: {} islands (expect 6)".format(count_islands(matrix2)))
64+
65+
# Empty Column
66+
matrix3 = [
67+
[],
68+
[],
69+
[],
70+
[],
71+
[]
72+
]
73+
74+
print_matrix(matrix3)
75+
print("Matrix has: {} islands (expect 0)".format(count_islands(matrix3)))
76+
77+
# single column
78+
matrix4 = [
79+
[1],
80+
[1],
81+
[0],
82+
[1],
83+
[1]
84+
]
85+
86+
print_matrix(matrix4)
87+
print("Matrix has: {} islands (expect 2)".format(count_islands(matrix4)))
88+
89+
# Single Row
90+
matrix5 = [
91+
[1, 0, 1, 1, 0, 1]
92+
]
93+
94+
print_matrix(matrix5)
95+
print("Matrix has: {} islands (expect 3)".format(count_islands(matrix5)))
96+
97+
# Null matrix
98+
matrix6 = None
99+
100+
print_matrix(matrix6)
101+
print("Matrix has: {} islands (expect 0)".format(count_islands(matrix6)))
102+
103+
# Malformed Matrix
104+
matrix7 = [
105+
[1,1,0,0,0],
106+
[0,1],
107+
[1,0,0,1,1],
108+
[0,0,1],
109+
[1,0,1,0,1]
110+
]
111+
112+
print_matrix(matrix7)
113+
print("Matrix has: {} islands (expect 6)".format(count_islands(matrix7)))

0 commit comments

Comments
 (0)