Module 15: Get Strings from the Grid (Python code)
This commit is contained in:
parent
c82251732a
commit
ee92bef817
43
a.py
43
a.py
@ -23,7 +23,14 @@ class Spans:
|
||||
def __init__(self, p, l, v):
|
||||
self.point = p
|
||||
self.len = l
|
||||
self.vert = v
|
||||
self.vert = v
|
||||
|
||||
def GetPoint(self, i):
|
||||
assert(i >= 0 and i < self.len)
|
||||
if self.vert:
|
||||
return Point(self.point.row + i, self.point.col)
|
||||
else:
|
||||
return Point(self.point.row, self.point.col + i)
|
||||
|
||||
def __str__(self):
|
||||
return f'[{self.point} len={self.len} vert={self.vert}]'
|
||||
@ -90,12 +97,14 @@ class Library:
|
||||
# print(f' {"".join(tmp)}')
|
||||
self.word_map_[w].append("".join(tmp))
|
||||
|
||||
def ReadFromFile(self, filename):
|
||||
def ReadFromFile(self, filename, max_size):
|
||||
with open(filename, 'r') as f:
|
||||
for line in f:
|
||||
line = ToUpper(line.rstrip())
|
||||
self.words_.word.append(line)
|
||||
self.CreatePatternHash(line)
|
||||
len_w = len(line)
|
||||
if len_w < max_size:
|
||||
self.words_.word.append(line)
|
||||
self.CreatePatternHash(line)
|
||||
print(f"Read {len(self.words_.word)} words from file '{filename}'")
|
||||
|
||||
def DebugBuckets(self):
|
||||
@ -118,6 +127,9 @@ class Grid:
|
||||
return 0
|
||||
else:
|
||||
return len(self.lines[0])
|
||||
|
||||
def max_size(self):
|
||||
return max(self.rows(), self.cols())
|
||||
|
||||
# Returns character value of the box at point 'p'
|
||||
# 'p' must be in bounds
|
||||
@ -140,6 +152,15 @@ class Grid:
|
||||
def in_bounds(self, p):
|
||||
return p.row >= 0 and p.row < self.rows() and p.col >= 0 and p.col < self.cols()
|
||||
|
||||
# Fills in attributes of the string
|
||||
def GetString(self, sp):
|
||||
len_ = sp.len
|
||||
temp = []
|
||||
for i in range(len_):
|
||||
p = sp.GetPoint(i)
|
||||
temp.append(self.box(p))
|
||||
return ''.join(temp)
|
||||
|
||||
# Next increments the point across the grid, one box at a time
|
||||
# Returns True if point is still in bounds
|
||||
def Next(self, p, vert):
|
||||
@ -190,22 +211,24 @@ class Grid:
|
||||
def Print(self):
|
||||
print(f"Grid: {self.name} "
|
||||
f"(rows={self.rows()},"
|
||||
f" cols={self.cols()})")
|
||||
f" cols={self.cols()},"
|
||||
f" max_size={self.max_size()})")
|
||||
for s in self.lines:
|
||||
print(f" {''.join(s)}")
|
||||
|
||||
def PrintSpans(self):
|
||||
print(f"Spans:")
|
||||
for span in self.sp:
|
||||
print(f" {span}")
|
||||
print(f" {span} {self.GetString(span)}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
lib = Library()
|
||||
lib.ReadFromFile("top_12000.txt")
|
||||
|
||||
grid = Grid("MY GRID")
|
||||
grid.LoadFromFile("test")
|
||||
grid.Check()
|
||||
grid.Print()
|
||||
grid.FillSpans()
|
||||
grid.PrintSpans()
|
||||
grid.PrintSpans()
|
||||
|
||||
lib = Library()
|
||||
lib.ReadFromFile("top_12000.txt", grid.max_size())
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user