【发布时间】:2019-05-24 18:36:15
【问题描述】:
我正在解决这个编码问题“计算每个 Z 行中每个 Y 个单词的元音超过 X 个的单词和行数”
基本上输入字符串有多行,我需要计算其中包含 X 或更多元音的单词。但限制是我只需要考虑备用第 Z 行以及这些第 Z 行中的备用 Yth 单词。例如假设我需要计算每第三行有 2 个或更多元音的第三个单词。所以这里是X=2、Y=3、Z=3。检查以下输入字符串:
"1.When I first brought my cat home.
2.It cost a lot to adopt her.
3.I paid forty dollars for it.
4.And then I had to buy litter, a litterbox.
5.Also bought food, and dishes for her to eat out of.
6.There's a **leash** law for cats in Fort **Collins**.
7.If they're not in your yard they have to be on a leash.
8.Anyway, my cat is my best friend.
9.I'm glad I got her.
10.She sleeps under the covers with me when it's cold."
输出:字数:2,行数:1
因此基于Z=3 的标准,即每第三行计数一次,因此要考虑的行是line number 3, 6, 9。同样在这些行中,我们需要计算Y=3 i.e. every 3rd word。所以要考虑的词是"forty, it" from line 3、"leash, cats, Collins" from line 6 和"I" from line 9。鉴于此标准,只有在第 6 行中才能找到具有 2 个或更多元音的匹配词,其中包含词 "leash" 和 "Collins",因此输出为 WordCount = 2 和 LineCount = 1。
这是我第一次用 Python 写东西,所以写了下面的基本代码:
class StringCount: #Count the number of words & lines that have more than X vowels for every Y words in every Z line.
lines = list();
totalMatchedLines = 0;
totalMatchedWords = 0;
matchedChars = 0;
def __init__(self, inputString, vowelCount, skipWords, skipLines, wordDelimiter, lineDelimiter):
self.inputString = inputString;
self.vowelCount = vowelCount;
self.skipWords = skipWords;
self.skipLines = skipLines;
self.wordDelimiter = wordDelimiter;
def splitLines(self):
if self.inputString.strip() == "":
print ("Please enter a valid string!");
return False;
self.lines = self.inputString.splitlines();
def splitWords(self):
self.matchedWords = 0;
self.matchedLines = 0;
self.linesLength = len(self.lines);
if self.linesLength < self.skipLines:
print ("Input string should be greater than {0}" .format(self.skipLines));
return False;
lineCount = self.skipLines - 1;
wordCount = self.skipWords - 1;
lineInUse = "";
words = list();
while (lineCount < self.linesLength):
self.matchedWords = 0;
self.matchedLines = 0;
self.words = self.lines[lineCount].split();
self.wordsLength = len(self.words);
wordCount = self.skipWords - 1;
while (wordCount < self.wordsLength):
self.matchedChars = 0;
for i in self.words[wordCount].lower():
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u'):
self.matchedChars += 1;
if self.matchedChars >= self.vowelCount:
self.matchedWords += 1;
wordCount += self.skipWords;
if self.matchedWords > 0:
self.matchedLines += 1;
self.totalMatchedWords += self.matchedWords;
self.totalMatchedLines += self.matchedLines;
lineCount += self.skipLines;
print ("WordCount = %s" % (self.totalMatchedWords));
print ("LineCount = %s" % (self.totalMatchedLines));
由于这是我的第一个 Python 代码,我想检查如何在性能和线路优化方面优化此代码。有没有什么技巧可以缩短多个 while 循环和一个 for 循环?
感谢任何帮助!
【问题讨论】:
-
如果可行,请在 codereview 上发布
-
代码运行良好。
-
发布在 codereview 上,所以不是为了代码优化
-
我投票决定将此问题作为题外话结束,因为代码有效,而提问者只想优化代码。它可能应该去 codereview.SE
-
感谢 Ralf,我在 codereview 中发布了代码。
标签: python string optimization split substring