Reputation: 3
Newbie to Python. i have been asked to write a function sameVowels(s1, s2), that given 2 strings s1,s2, returns True if both strings have exactly the same vowels (kind and number). (Think how to use dictionaries..)
I tried this:
import string
def sameVowels( s1 , s2 ) :
d1 = {}
d2 = {}
vowels = [ 'a' , 'e' , 'i' , 'o' , 'u' ]
for v1 in s1 :
for k1 in vowels :
if v1 == k1 :
d1[k1] = v1
for v2 in s2 :
for k2 in vowels :
if v2 == k2 :
d2[k2] = v2
print d1
print d2
return d1 == d2
print sameVowels( 'aabcefiok' , 'xcexvcxaioa' )
print sameVowels( 'aabcefiok' , 'xcexvcxaioia' )
but what I get is:
{'a': 'a', 'i': 'i', 'e': 'e', 'o': 'o'}
{'a': 'a', 'i': 'i', 'e': 'e', 'o': 'o'}
True
{'a': 'a', 'i': 'i', 'e': 'e', 'o': 'o'}
{'a': 'a', 'i': 'i', 'e': 'e', 'o': 'o'}
True
the last pair should give False because the second string has an extra "i" I really dont know how to do it please help :)
Upvotes: 0
Views: 87
Reputation: 8401
A somewhat simpler though less performant version (since we're counting each letter):
def sameVowels(s1,s2):
vowels = [ 'a' , 'e' , 'i' , 'o' , 'u' ]
f1 = dict((letter, s1.count(letter)) for letter in vowels)
f2 = dict((letter, s2.count(letter)) for letter in vowels)
return f1==f2
Another option:
from collections import Counter
def sameVowels(s1,s2):
vowels = [ 'a' , 'e' , 'i' , 'o' , 'u' ]
filtered1 = filter(lambda x: x in vowels, s1)
filtered2 = filter(lambda x: x in vowels, s2)
f1 = Counter(filtered1)
f2 = Counter(filtered2)
return f1==f2
Upvotes: 0
Reputation: 34146
You may want to store pairs like {vowel : ocurrences}
, so try modifying the logic in your 2 for
statements:
for v1 in s1 : # Iterate over string1
if v1 in vowels: # Check if each letter is a vowel
if v1 in d1: # If the vowel is in dict1
d1[v1] += 1 # Add 1 to the actual value
else:
d1[v1] = 1 # Add the vowel to dict1
The same for the second for
:
for v2 in s2 :
if v2 in vowels:
if v2 in d2:
d2[v2] += 1
else:
d2[v2] = 1
Upvotes: 1