Reputation: 31
I would like to make a function which will decode a word in following way: the first vowel exchanges with the last one, the second with second to last etc. The same I would like to do with consonants. In the end it will return decoded word.
This is the beginning of my code with vowels:
def decode(w):
for i in range(len(w)):
for j in range(len(w[::-1])):
if (i[0] in 'aeiouy' and j[0] in 'aeiouy'):
s[i],s[j]=s[j],s[i]
return w
The problem is that I don't know how to exchange this letters.
For example: I'm given a word: 'saturday' And my function give me 'dyratsua' back
Upvotes: 2
Views: 1726
Reputation: 37259
Here is one way you could achieve what you want with vowels (although it is a bit convoluted - somebody else will have a better way). What it does is first create a list from your word (w
), the reason being that a list is mutable and can therefore be modified during our iteration. The vowels
list holds the index position of all of the vowels. The cutoff
is the weird piece - we are going to zip
the vowel
list with the reverse of itself, which will look something like this:
In [28]: zip(vowels, vowels[::-1])
Out[28]: [(1, 7), (3, 6), (6, 3), (7, 1)]
So we have the index positions of what we want to switch, but as you can see after the middle tuple we would just swap the letters right back. Therefore we have to indicate that we don't want to use the entire zip
ped list, so we cut it off at the middle (since an odd number of vowels will just mean that the middle vowel replaces itself with itself). From there, you do just as you were doing before - swap the letters, but this time you are working with a mutable list. At the end, join everything together into a string.
In [29]: word = 'saturday'
In [30]: vowels = [index for index, c in enumerate(word) if c in 'aeiouy']
In [31]: w = [c for c in word]
In [32]: cutoff = int(round(len(vowels)/2.0))
In [33]: for i1, i2 in zip(vowels, vowels[::-1])[:cutoff]:
....: w[i1], w[i2] = w[i2], w[i1]
....:
....:
In [34]: ''.join(w)
Out[34]: 'sytardua'
Upvotes: 1
Reputation: 2257
word = 'aerodynamic'
vowels = 'aeiouy'
is_vowel = [x in vowels for x in word]
word_vowels = [x for x in word if x in vowels]
word_consonants = [x for x in word if x not in vowels]
word_vowels.reverse()
word_consonants.reverse()
new_word = [word_vowels.pop(0) if x else word_consonants.pop(0) for x in is_vowel]
Upvotes: 5