Module 8: Read the Library from a File

This commit is contained in:
David Doblas Jiménez 2021-07-16 19:17:37 +02:00
parent 1b22df33e0
commit 1b7f7e7d32
2 changed files with 99 additions and 8 deletions

61
a.c
View File

@ -7,6 +7,55 @@ using namespace std;
// For compiling C++ code
// g++ a.c -o a
class Library {
public:
void ComputeStats() {
assert(counts.empty());
counts.resize(18);
for (string s : words) {
int len = s.length();
if (len < 18) {
counts[len]++;
}
}
}
void PrintStats() const {
cout << "Here are the counts of each word length:\n";
for (int i=1; i<counts.size(); i++) {
cout << "[" << i << "] " << counts[i] << "\n";
}
}
string GetWord(int i) const {
assert(i >= 0 && i < words.size());
return words[i];
}
void ReadFromFile(string filename) {
ifstream f;
f.open(filename);
while (!f.eof())
{
string line;
getline(f, line);
// cout << line << "\n";
if (!line.empty())
{
int len = line.length();
if (line[len-1] == '\r') {
line = line.substr(0, len-1);
}
words.push_back(line);
}
}
cout << "Read " << words.size() << " words from file '"
<< filename << "'\n";
}
private:
vector<string> words;
vector<int> counts;
};
struct Grid
{
Grid(string n)
@ -63,9 +112,13 @@ struct Grid
int main()
{
Grid grid("MY GRID");
Library lib;
lib.ReadFromFile("top_12000.txt");
lib.ComputeStats();
lib.PrintStats();
grid.LoadFromFile("test");
grid.Check();
grid.Print();
//Grid grid("MY GRID");
//grid.LoadFromFile("test");
//grid.Check();
//grid.Print();
}

46
a.py
View File

@ -1,3 +1,37 @@
class Library:
def __init__(self):
# master vector of word
self.words = []
self.counts = {}
def ComputeStats(self):
# assert self.counts == {}
for i in range(18):
self.counts[i] = []
for s in self.words:
_len = len(s)
if _len <= 18:
self.counts[_len-1].append(_len)
def PrintStats(self):
print("Here are the counts of each word length")
for k,v in self.counts.items():
# print(v)
if k != 0:
print(f"[{k}] {len(v)}")
def GetWord(self, i):
assert (i >= 0 and i < len(self.words))
return self.words[i]
def ReadFromFile(self, filename):
with open(filename, 'r') as f:
for line in f:
self.words.append(line)
print(f"Read {len(self.words)} words from file '{filename}'")
class Grid:
def __init__(self, n):
@ -32,8 +66,12 @@ class Grid:
print(f" {''.join(s)}")
if __name__ == "__main__":
grid = Grid("MY GRID")
lib = Library()
lib.ReadFromFile("top_12000.txt")
lib.ComputeStats()
lib.PrintStats()
grid.LoadFromFile("test")
grid.Check()
grid.Print()
# grid = Grid("MY GRID")
# grid.LoadFromFile("test")
# grid.Check()
# grid.Print()