这段代码似乎应该可行。它总结了"条纹" (letter-consonant-letter-etc.)然后返回总和。但是,当我使用print (striped("My name is ...") )
对其进行测试时,它只计算my
和is
并给我一个2而不是3 ...为什么name
会丢失?
VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"
def striped(text):
my_sum = 0
text = text.replace(".", " ").replace(",", " ").split()
vowels = VOWELS.lower()
consonants = CONSONANTS.lower()
for word in text:
word = word.lower()
if ((word[::2] in vowels and word[1::2] in consonants)\
or (word[::2] in consonants and word[1::2] in vowels))\
and len(word) > 1:
print (word)
my_sum += 1
return my_sum
答案 0 :(得分:1)
您应该使用set.issubset()
代替。
VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"
def striped(text):
my_sum = 0
text = text.replace(".", " ").replace(",", " ").split()
vowels = set(c for c in VOWELS.lower())
consonants = set(c for c in CONSONANTS.lower())
for word in text:
word = word.lower()
if ((set(word[::2]).issubset(vowels) and set(word[1::2]).issubset(consonants))\
or (set(word[::2]).issubset(consonants) and set(word[1::2]).issubset(vowels)))\
and len(word) > 1:
print (word)
my_sum += 1
return my_sum
striped('My name is...')
它适用于my
和is
的原因是它们是两个字符,因此您要检查m
是否在常量字符串中,以及{{1}在元音串中,它起作用。对于y
之类的较长字词,显然name
不在sonsonants字符串中,因此失败。
相反,你应该使用集合。基本上,您想要查找nm
是否是辅音集的子集。
答案 1 :(得分:1)
这是一个包含列表的解决方案。您的代码存在的问题是,当您使用[::2]
而不是单个字符时,超过两个字符的字会返回子字符串,而不会测试它们是否包含在vowels
/ constants
中。
通过首先将其转换为列表,您可以检查列表中的每个项目是否包含在相应的字符集中。
VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"
def striped(text):
my_sum = 0
text = text.replace(".", " ").replace(",", " ").split()
vowels = VOWELS.lower()
consonants = CONSONANTS.lower()
for word in text:
word = word.lower()
if ((all(c in vowels for c in list(word[::2]))\
and all(c in consonants for c in list(word[1::2])))\
or (all(c in consonants for c in list(word[::2]))\
and all(c in vowels for c in list(word[1::2]))))\
and len(word) > 1:
print (word)
my_sum += 1
return my_sum
print striped("My name is")