元音程序中什么也没打印

时间:2018-10-28 14:56:38

标签: python python-3.x

我正在创建一个元音程序,该程序检查包含所有元音的字符串。元音也应该只出现一次。 我创建的程序如下

n=input()
d=0
c=0
j=0
for i in range(0,len(n)):
    if(n[i]=="a" or n[i]=="e" or n[i]=="i" or n[i]=="o" or n[i]=="u"):
        c=c+1
        for j in range(i+1,len(n)):
            if(n[i]==n[j]):
                d=d+1
if(c==5):
    if(d==0):
        print("The number is a vowelgram")
else:
    print("The number isnt a vowelgram")

不幸的是,该程序什么都不打印。我似乎无法在代码中找到错误。感谢帮助。谢谢

3 个答案:

答案 0 :(得分:0)

您可以使用all来检查所有元音是否都在字符串中并且恰好是一次:

n = input('Enter string: ')
n = n.lower()

if all(x in n and n.count(x) == 1 for x in {'a', 'e', 'i', 'o', 'u'}):
    print('It is a vowelgram.')
else:
    print('It is not a vowelgram.')

答案 1 :(得分:0)

使用(计数器)[https://docs.python.org/3.7/library/collections.html#collections.Counter]类对字母进行计数。然后检查每个元音计数countdict['a']<=1是否小于或等于零。

答案 2 :(得分:0)

如果没有打印任何内容,对于某些输入,您必须以内部else if分支为结尾:

if(c==5):
    if(d==0):
        print("The number is a vowelgram")
    # c==5, but d!=0
    # here , you will get no output!
else:  # this else applies only to the outer if: c!=5
    print("The number isnt a vowelgram")

您可以对此进行补救,例如通过使用以下涵盖所有( other )情况的构造:

if c==5 and d==0:
    print("The number is a vowelgram")
else:
    print("The number isnt a vowelgram")

但是,通常,嵌套循环并不是最佳的性能。您可以使用collections.Counter来获得线性时间的结果:

from collections import Counter

c = Counter(x for x in n if x in 'aeiou')
if len(c) == 5 and all(v==1 for v in c.values()):
    print('vowelgram')
else:
    print('not vowelgram')
相关问题