Reputation: 31
So I have to create a program that rewrites a string backword and alternates vowels and consonants like in this example:
ex_1:
input -> 'abcdefi'
output -> 'ifedacb'
ex_2:
input -> 'vblsdeloai'
output ->'iladoselbv'
word = input('the word is: ')
b = word[::-1]
list_vowels = []
list_consonants = []
final_list = []
string = ''
vowels = ['a', 'e','i','o','u']
for i in str(b):
if i in vowels:
list_vowels.append(i)
elif i not in vowels:
list_consonants.append(i)
for j in list_vowels :
final_list.append(j)
for b in list_consonants :
final_list.append(b)
for q in e
string = string + e
print (string)
so I convert the string backwords than I use a for to iterate over every char and compare it to the vowel list. If it is in the vowel list then append to a new list list_vowels if not append it to a new list list_consonants. Now I'm stuck at the part where I have to create a list that is created by the two list list_vowels and list_consonats. I don't now how can I make the two for work simultaniously. The zip functions make the list a tuple and I don't think I can use that. I'm prety new and any help will be awsome. If you think I can aproach this problem differently feel free to tell me I am new to programing and I don't realy now how.
Upvotes: 2
Views: 1231
Reputation: 5959
from itertools import zip_longest
def split(s):
vowels = ['a', 'e', 'i', 'o', 'u']
return list(filter(lambda c: c in vowels, s)), \
list(filter(lambda c: c not in vowels, s))
def reverse_interleave(s):
vowels, consonants = list(map(reversed, split(s)))
return ''.join(
map(lambda x: ''.join(x),
zip_longest(vowels, consonants, fillvalue='')))
print(reverse_interleave('abcdefi'))
print(reverse_interleave('vblsdeloai'))
Split the characters into vowels and non-vowels.
Reverse them.
Interleave them using zip_longest()
in this case.
Upvotes: 1
Reputation: 36684
The line you're missing is turning your two list of 1) vowels and 2) consonants into a zipped string. You can do this with itertools.zip_longest()
.
This is the line you will need:
from itertools import zip_longest
''.join(''.join(x) for x in zip_longest(list_vowels, list_consonants, fillvalue=''))
In[1]: 'vblsdeloai'
Out[1]: 'iladoselbv'
Upvotes: 1
Reputation: 26037
You need itertools.zip_longest
to zip through two lists taking an empty string as fillvalue
:
''.join(map(lambda x: x[0] + x[1], zip_longest(list_vowels, list_consonants, fillvalue='')))
Code:
from itertools import zip_longest
word = input('the word is: ')
b = word[::-1]
list_vowels = []
list_consonants = []
final_list = []
string = ''
vowels = ['a', 'e','i','o','u']
for i in b:
if i in vowels:
list_vowels.append(i)
elif i not in vowels:
list_consonants.append(i)
print(''.join(map(lambda x: x[0] + x[1], zip_longest(list_vowels, list_consonants, fillvalue=''))))
Upvotes: 1