如何修复 codesignal python 上 classifyStrings 代码的所有测试用例?

How to fix all test cases for classifyStrings code on codesignal python?

所以我得到了这个问题:你将字符串分为三种类型:好、坏或混合。如果一个字符串有 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, 元音之间的辅音 e.g. aba,辅音之间的元音,例如宝宝

注意:经过一夜的思考,我又定义了几个测试用例,结果需要进一步修改解决方案。如下所示: 这是一种似乎可以正确解决所有情况的方法:

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
import re
def classifyStrings(s):
    if re.findall('(([aeiou]{3})|[^aeiou?]{5})',s):
        return 'bad'
    if '?' in s:
        a = classifyStrings(s.replace('?','a',1))
        b = classifyStrings(s.replace('?','n',1))
        return a if a == b else 'mixed'
    return 'good'