如何检查辅音元音模式的完整字符串并返回布尔值



我有一个项目,要求我检查一个编码的PIN,它必须具有以下模式:辅音,元音。例如,3464140是博梅莱拉。

我以前试过这个:

def checkString(st):
    if st == '':
        return False
    elif st[0] in consonants and st[1] in vowels:
        return True
    else:
        return False

但是字符串长度可能会有所不同,所以我不确定如何检查整个字符串。

此函数应返回布尔值。我想我很接近,但我不确定如何返回真或假,因为我的 if 语句以 i + 1 结尾。

到目前为止,我有这个:

consonants = "bcdfghjklmnpqrstvwyz"
vowels = "aeiou"
def checkString(st):
  for i in range(len(st)):
    if i % 2 == 0:
      if st[i] in consonants:
         i + 1
    elif i % 2 != 0:
      if st[1] in vowels:
         i + 1

提前感谢,对于任何格式问题,这是我的第一篇文章。

这个简单的更改可以为您解决问题:

consonants = "bcdfghjklmnpqrstvwyz"
vowels = "aeiou"

def checkString(st):
    for i in range(len(st)):
        if i % 2 == 0:
            if st[i] not in consonants:
                return False
        else:
            if st[i] not in vowels:
                return False
    return True

我们可以在特定位置检查辅音或元音中的特定字符串,并在当前迭代中的条件计算结果为 true 时继续下一次迭代。

如果任何条件在任何迭代中失败,它将返回 false。如果条件在所有迭代的计算结果为 True,则最终函数将返回 True。

consonants = "bcdfghjklmnpqrstvwyz"
vowels = "aeiou"
def checkString(st):
    for i in range(len(st)):
        if i % 2 == 0 and st[i] in consonants:
            continue
        elif i % 2 != 0 and st[i] in vowels:
            continue
        else: 
            return False 
    return True
def checkString(teststring):
    '''To check for pattern: Consonant:Vowel and return true if pattern exists'''
    const = "bcdfghjklmnpqrstvwyz"
    vowels = "aeiou"
    t_odd = teststring[::2].lower()
    t_even = teststring[1::2].lower()
    outcome = ["True" if x in const else "False" for x in t_odd ] + ["True" if y in vowels else "False" for y in t_even]
    return all(item == "True" for item in outcome)
#Test
checkString("Bolelaaa")
checkString("bomelela")

在这个函数中,我使用列表理解来分别针对辅音和元音列表测试奇数和偶数字母。如果所有比较都成立,则该函数返回 true。

最新更新