簡體   English   中英

如何檢查完整字符串的輔音元音模式並返回布爾值?

[英]How to check full string for consonant-vowel pattern and return boolean value?

我有一個項目,要求我檢查必須具有以下模式的編碼PIN:輔音,元音。 例如3464140是bomelela。

我以前嘗試過:

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結尾,我不確定如何返回true或false。

到目前為止,我有這個:

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")

在此功能中,我使用列表推導功能分別針對輔音和元音列表測試奇數和偶數字母。 如果所有比較都為真,則該函數返回真。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM