यहाँ की एक सूची में शब्द लंबाई के अनुपात में स्वर गिना जा रहा है मेरी समारोह के लिए कोड है ।शब्द
क्या ऐसा करने का कोई बेहतर तरीका है?
संपादित करें:
import time
class vowelProportions(object):
"""
A series of methods that all calculate the vowel/word length ratio
in a list of words.
"""
WORDLIST_FILENAME = "words_short.txt"
def __init__(self):
self.wordList = self.buildWordList()
print "Original: " + str(self.calcMeanTime(10000, self.cvpOriginal, self.wordList))
print "Generator: " + str(self.calcMeanTime(10000, self.cvpGenerator, self.wordList))
print "Count: " + str(self.calcMeanTime(10000, self.cvpCount, self.wordList))
print "Translate: " + str(self.calcMeanTime(10000, self.cvpTranslate, self.wordList))
def buildWordList(self):
inFile = open(self.WORDLIST_FILENAME, 'r', 0)
wordList = []
for line in inFile:
wordList.append(line.strip().lower())
return wordList
def cvpOriginal(self, wordList):
""" My original, slow algorithm"""
VOWELS = 'aeiou'
ratios = []
for word in wordList:
numVowels = 0
for char in word:
if char in VOWELS:
numVowels += 1
ratios.append(numVowels/float(len(word)))
return ratios
def cvpGenerator(self, wordList):
""" Using a generator expression """
return [sum(char in 'aeiou' for char in word)/float(len(word)) for word in wordList]
def cvpCount(self, wordList):
""" Using str.count() """
return [sum(word.count(char) for char in 'aeiou')/float(len(word)) for word in wordList]
def cvpTranslate(self, wordList):
""" Using str.translate() """
return [len(word.translate(None, 'bcdfghjklmnpqrstxyz'))/float(len(word)) for word in wordList]
def timeFunc(self, func, *args):
start = time.clock()
func(*args)
return time.clock() - start
def calcMeanTime(self, numTrials, func, *args):
times = [self.timeFunc(func, *args) for x in range(numTrials)]
return sum(times)/len(times)
उत्पादन था (200 शब्दों की एक सूची के लिए):
Original: 0.0005613667
Generator: 0.0008402738
Count: 0.0012531976
Translate: 0.0003343548
हैरानी की बात है,
मैं एल्गोरिदम @ExP निम्नलिखित वर्ग के साथ प्रदान की जांच की जनरेटर और गणना मूल से भी धीमी थी (अगर मेरा कार्यान्वयन गलत था तो कृपया मुझे बताएं)।
मैं जॉन के समाधान का परीक्षण करना चाहता हूं, लेकिन पेड़ों के बारे में कुछ भी नहीं जानता।
मुझे लगता है कि यह ध्यान देने योग्य होना चाहिए कि आपको शब्द (low) ('aeiouAEIOU''' या '(2) शब्द के लिए पहले शब्द (lower() के लिए पहले बदलना चाहिए:' – ryrich
जब तक सूची में वे शब्द नहीं हैं जो लोअरकेस हैं – piokuc
@ryrich जिस सूची में मैं काम कर रहा हूं वह केवल लोअरकेस शब्द है, लेकिन धन्यवाद - मैं इसका उल्लेख करना भूल गया। – paulwithap