簡體   English   中英

編寫一個包含 3 個字符的程序,然后

[英]Write a program that takes 3 characters and then

我正在用 Python 學習,但我陷入了這個困境。

問題:編寫一個程序,用 3 個字符計算輔音和元音的個數,如下例所示。 輸入三個字符:> z H a 輔音個數為2,元音個數為1

這是我一直在嘗試的代碼

a,b,c = input("Input three characters:>").split()
a = str(a)
b = str(b)
c = str(c)
if a == 'a' or a == 'e' or a == 'i' or a == 'o' or a == 'u':
    print("The number of consonants is 2. The number of vowels is 1.")
    elif b == 'a' or b == 'e' or = b == 'i' or b == 'o' or b == 'u':
        print("The number of consonants is 2. The number of vowels is 1.")
        if c == 'a' or c == 'e' or = c == 'i' or c == 'o' or c == 'u':
            print("The number of consonants is 2. The number of vowels is      1.")

但如果我考慮元音是否為 2 個或更多,那就太長了。 我怎樣才能更容易地為這個編碼?

不要將字符放在不同的變量中,而是將它們放在一個列表中,然后遍歷該列表。

您可以只檢查連接的元音字符串中的成員船:

if your_word in 'aeiou':

如果您要處理更多長字符串的單詞,您可以在set容器中取出元音,該容器具有 O(1) 順序來檢查成員資格

您可以創建元音字典,然后測試輸入是否在該字典中:

vowels = {'Vowels':['a','e','i','o','u']}
a,b,c = input("Input three characters:>").split()
a = str.lower(a)
b = str.lower(b)
c = str.lower(c)
letters = [a,b,c]
voweltruth = [x in vowels['Vowels'] for x in letters]
print("The number of consonants is %i. The number of vowels is %i." % (3-sum(voweltruth),sum(voweltruth)))

暫無
暫無

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

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