我正在尝试编写一个Python函数,该函数将两个字符串作为参数,并返回它们是否具有相同的元音(数量无关紧要)。
因此("deed"、"ed")应返回true,但("deet"、"rate")应返false。
我被这个相当可怕的尝试卡住了。。。
def vocalizer(string_a,string_b):
vowels = ['a', 'e', 'i', 'o', 'u']
result = ''
result_2 = ''
for character in string_a:
if character in vowels:
result = result + character
for item in string_b:
if item in vowels:
result_2 = result_2 + item
for vowel in result:
if vowel not in list(result_2):
return False
else:
if vowel in list(result_2):
return True
简短而富有表现力:
def keep_only_vowels(s):
vowels = ('a', 'e', 'i', 'o', 'u')
return (c for c in s.lower() if c in vowels)
def vocalizer(s1, s2):
return set(keep_only_vowels(s1)) == set(keep_only_vowels(s2))
我会使用集合交集从每个字符串中提取元音。像这样:
all_vowels = set('aeiou')
def vowel_set(s):
return all_vowels.intersection(s.lower())
def same_vowels(s1, s2):
return vowel_set(s1) == vowel_set(s2)
print same_vowels('deed', 'bed')
print same_vowels('indeed', 'irate')
print same_vowels('DEAD', 'earnest')
print same_vowels('blue', 'ICE')
输出
True
False
True
False
您自己的代码可以很容易地改进,因为您的总体策略是正确的:
def vocalizer(string_a,string_b):
vowels = ['a', 'e', 'i', 'o', 'u']
result = ''
result_2 = ''
for character in string_a:
if character in vowels:
result += character
for item in string_b:
if item in vowels:
result_2 += item
result = set(list(result))
result_2 = set(list(result_2))
#print("result= {}".format(result))
#print("result_2= {}".format(result_2))
if result == result_2:
return True
else:
return False
当你去掉单词的辅音时,你可以简单地用字符串创建一个列表,然后通过将它们转换为集合来删除重复的元素。最后,你可以比较这些集合,看看它们是否相等。例如:
>>> vocalizer ('indeed','irate')
result= {'i', 'e'}
result_2= {'i', 'e', 'a'}
False
>>> vocalizer ('indeed','ie')
result= {'i', 'e'}
result_2= {'i', 'e'}
True
>>>
通过重新模块。
>>> def checkvow(x, y):
return set(i.lower() for i in re.findall(r'(?i)[aeiou]', x)) == set(i.lower() for i in re.findall(r'(?i)[aeiou]', y))
>>> print(checkvow('deed', 'bed'))
True
>>> print(checkvow('indeed', 'irate'))
False
>>> print(checkvow('DEAD', 'earnest'))
True
>>> print(checkvow('blue', 'ICE'))
False