python - 如何修复codesignal python上classifyStrings代码的所有测试用例?
问题描述
所以给了我这个问题:你把字符串分为三种类型:好的、坏的或混合的。如果一个字符串有 3 个连续的元音或 5 个连续的辅音,或者两者都有,那么它被归类为坏。否则,它被归类为好。英文字母表中的元音是[“a”、“e”、“i”、“o”、“u”],所有其他字母都是辅音。
字符串还可以包含字符 ?,可以用元音或辅音代替。这意味着字符串 "?aa" 如果 ? 是元音,如果是辅音,则为好音。这种字符串被归类为混合。
这是我到目前为止创建的代码:
def classifyStrings(s):
l = list(s)
numberofvowels = 0
numberofconsonants = 0
punctuationpresent = False
for i in l:
if i == "a" or "e" or "i" or "o" or "u":
numberofvowels += 1
else:
numberofconsonants += 1
if numberofvowels >= 3 or numberofconsonants >=5 and i != '?':
return "bad"
else:
return "good"
if i in l == "?":
punctuationpresent = True
return "mixed"
到目前为止,我已经成功通过了 5/17 个测试用例。我不确定如何改进此代码以通过所有测试用例。我必须解决的主要问题是:元音之间或辅音之间的问号,例如 a?a,元音之间的辅音,例如 aba,辅音之间的元音,例如 bab
解决方案
注意:在考虑了一夜之后,我定义了更多的测试用例,因此需要进一步更改解决方案。如下所示:这是一种似乎可以正确解决所有情况的方法:
def classifyStrings(s):
vowels = 'aeiou'
max_vowels = 3
max_consonants = 5
vowel_count = 0
consonant_count = 0
punctuation_present = False
for i in range(len(s)):
if s[i] == '?':
punctuation_present = True
elif s[i].lower() in vowels:
if punctuation_present and i> 0 and vowel_count == 0 and s[i-1] != '?':
punctuation_present = False
vowel_count += 1
consonant_count = 0
else:
if punctuation_present and i> 0 and consonant_count == 0 and s[i-1] != '?':
punctuation_present = False
consonant_count += 1
vowel_count = 0
if vowel_count == max_vowels or consonant_count == max_consonants:
return 'bad'
else:
if punctuation_present and (vowel_count == max_vowels -1 or consonant_count == max_consonants-1):
return 'mixed'
return 'good'
给定一系列测试用例:
test_cases = {"good": ['aabbccee', 'bbbbaaddd', 'eeffffeffffiig', 'a?bbdu', 'a?deffff', 'f?ekkii'],
'bad':['ooobbbddbee','eeebb', 'eedgfkjii', 'kelyzzccbb', 'a?deffffg','f?ekkiii'],
'mixed':['iipp?hhoo', 'hjkie?drte', 'o?aekee']}
跑步:
for k, sl in test_cases.items():
print(f'Testing {k} cases')
for s in sl:
print(f'\tResults: {classifyStrings(s)}')
产量:
Testing good cases
Results: good
Results: good
Results: good
Results: good
Results: good
Results: good
Testing bad cases
Results: bad
Results: bad
Results: bad
Results: bad
Results: bad
Results: bad
Testing mixed cases
Results: mixed
Results: mixed
Results: mixed
推荐阅读
- spring - 为什么我的项目中的库版本与它的父 pom 声明不同?
- python - 需要在我的 lambda 函数中应用过滤器,但获取错误函数是不可迭代的
- flutter - 在 Flutter 中下拉到 REFRESH
- python - Python请求SSL错误:主机名不匹配
- node.js - 为什么我收到错误为 ER_PARSE_ERROR:您的 SQL 语法有错误;
- c# - 通过邮件将录音发送给 twilio 语音通话中的收件人
- php - ccavenue 支付网关请求处理程序未重定向到 ccavenue-payment-gateway
- ios - 验证uitableview单元格中多个uitextfields的下一个按钮上的非空
- ruby - 在批处理文件中通过它运行命令后如何退出'git-cmd.exe'?
- node.js - 连接到 AWS Postgres SequelizeConnectionError:密码身份验证失败