[英]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,元音之間的輔音,例如 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.