Skip to content

Instantly share code, notes, and snippets.

@libswan
Last active December 16, 2015 02:19
Show Gist options
  • Select an option

  • Save libswan/5361813 to your computer and use it in GitHub Desktop.

Select an option

Save libswan/5361813 to your computer and use it in GitHub Desktop.
V2. Attempt at converting into Classes. L12 Problem 7 - "present an angle of the data (words.txt) that you find interesting".
import random
import string
import pylab
WORDLIST_FILENAME = "words.txt"
def loadWords():
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = string.split(line)
print " ", len(wordlist), "words loaded."
return wordlist
wordList = loadWords()
class countLengths(object):
def __init__(self):
self.maxLen = 0
self.minLen = 0
def maxLength(self, wordList):
for i in wordList:
if len(i) > self.maxLen:
self.maxLen = len(i)
return self.maxLen
def minLength(self, wordList):
self.minLen = self.maxLen
for i in wordList:
if len(i) < self.minLen:
self.minLen = len(i)
return self.minLen
def makeLenList(self, maxLen, minLen):
self.thisLenList = []
self.countIt = 0
self.thisLen = self.minLen
while self.thisLen >= self.minLen and self.thisLen <= self.maxLen:
for i in wordList:
if len(i) == self.thisLen:
self.countIt += 1
self.thisLenList.append(self.thisLen)
self.thisLen += 1
return self.thisLenList
def makeCountList(self, maxLen, minLen):
self.countItList = []
self.countIt = 0
self.thisLen = self.minLen
while self.thisLen >= self.minLen and self.thisLen <= self.maxLen:
for i in wordList:
if len(i) == self.thisLen:
self.countIt += 1
self.countItList.append(self.countIt)
self.thisLen += 1
self.countIt = 0
return self.countItList
def checkSum(self, wordList):
self.sum = 0
for j in range(0, len(self.countItList)):
self.sum += self.countItList[j]
if self.sum != len(wordList):
return "Not matching up!"
else:
return "All good!"
def plotThis(self):
pylab.figure(1)
pylab.plot(self.thisLenList, self.countItList)
pylab.title('Number of Words by Word Length in the words.txt File')
pylab.xlabel('Length of Words')
pylab.ylabel('Count')
pylab.show()
#pylab.savefig('L12_P7_graph')
# Testing
c = countLengths()
maxLen = c.maxLength(wordList)
print maxLen
minLen = c.minLength(wordList)
print minLen
makeLenList = c.makeLenList(maxLen, minLen)
print makeLenList
makeCountList = c.makeCountList(maxLen, minLen)
print makeCountList
checkSum = c.checkSum(wordList)
print checkSum
plotThis = c.plotThis()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment