String replace printing too many instances of character 'e' - python

I am trying to write a function that takes a string as input and returns a string with all vowels repeated 4 times.
eg: apple becomes aaaappleeee
It works for every vowel, except for e, in which it repeats e an egregious amount of times.
Python 3. I have tried playing with the replace function, changing the replacement value to i+i+i+i, i*4, i(4), (i+i)*2, but nothing seems to help.
def exclamation(string):
for i in string:
if i in 'aeiou':
string = string.replace(i, i*4)
return string + '!'
exclamation('excellent') should return eeeexceeeelleeeent!
however, it returns:
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeexceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeelleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeent!
As stated, the function works fine for all other vowels, except e.
Thank you!

You shall never modify something you're iterating over, store the modified word in a new variable. Modifing your code it would be something like
def exclamation(string):
new = ''
for i in string:
if i in 'aeiou':
new += i*4
else:
new += i
return new + '!'

For every vowel you’re iterating through, the loop checks the condition, replaces the content in the same string and then iterates by 1 which now is the same string but instead of the next new letter, it now has to deal with 3 more of the same vowel. For example:
Let’s talk about the string ‘excellent’. For the first vowel ‘e’, it is replaced with ‘eeee’ resulting in the string being ‘eeeexcellent’, now when the second loop begins it starts at index(1) which is still an ‘e’ and this keeps going on. Never modify the iterable you’re iterating over.

It's not that e is being treated differently, but rather that you're replacing each e with eeee for as many es as there are in the word. If you try other words with multiples of the same vowel, you would see the same behavior there.
Instead of replacing for each vowel in the string, you should be doing each replacement once, which will effect every instance of that vowel in the string:
def exclamation(s):
for vowel in 'aeiou':
s = s.replace(vowel, vowel*4)
return s + '!'
print(exclamation('excellent'))
# 'eeeexceeeelleeeent!'
Note that this only works if the word is already lowercase (though that would be easy to fix, add capital vowels to the loop).
Another way of doing this would be to define a translation table to do all of the replacements at once:
trans = str.maketrans({vowel: vowel*4 for vowel in 'aeiou'})
def exclamation(s):
return s.translate(trans)

def exclamation(string):
result = ''
for i in string:
if i in 'aeiou':
vowel = i * 4
else:
vowel = i
result += vowel
return result + '!'
The reason why replace didnt work for excellent is because we have 3 'e' in which means for each of the 'e' in the loop, replace will multiply by 4 which will definitely give you 12 'e's per one 'e' in excellent

It is happening because your loop will consider the replaced 'e's as the element of the string as well.
Here is what I am saying:
String is excellent
Iterate through the string and check if the letter is vowel
If the letter is vowel, write that vowel 4 times.
By following the above steps, we will find this result as the first iteration.
First iteration will work on the first letter which is 'e' and will replace it with 'eeee'. So at the end of the first iteration, our final string will be: 'eeeexcellent'
Now for the second iteration, it will consider the final string we got after the first iteration. And for second iteration, the word to be consider will be 'e' only. So as you can see, you need to maintain the string as it is after each iteration, and save the replaced result to a new string. (it will always be a new string after all as string is not mutable)
def exclamation(string):
tmp = '' #taking temporary variable to store the current data
for i in string:
if i in 'aeiou':
tmp += i*4 # i*4 only if i is vowel
else:
tmp += i # keeping i as it is if it's not vowel
return tmp + '!'
You can also try list list comprehension which is easy to read and understand as well:
def exclamation(string):
newstr = [ i*4 if i in 'aeiou' else i for i in string]
return ''.join(newstr)+'!'

Related

Counting words containing certain letter

The task was to write a function with name count_letter that takes a list of words and certain letter and returns amount of words where this letter is found at least once. And, we have to use a for loop.
So I did a list of some programming languages and letter "a", and tried to apply everything we learned so far plus some internet tutorials to understand how to translate human logic into lines of code, but obviously I am missing something, because it doesn't work :(
That is how my code looks like at the moment:
mylist = ['fortran', 'basic', 'java', 'python', 'c++']
letter = 'a'
a_list = []
def count_letter(mylist):
count = 0
for i in range(len(mylist)):
if letter in i:
count += 1
a_list.append(i)
return a_list
print(len(a_list))
Result is - no result. Online-python compiler returns response ** process exited - return code: 0 **
My question is - what could I miss or positioned wrongly that loop doesn't work. I want to understand it for myself.
In tutorials I have found one construction which returns correct answer (and looks very elegant and compact), but it has no function, so it is not really what we needed to write:
mylist = ['fortran', 'basic', 'java', 'python', 'c++']
letter = 'a'
res = len ([ele for ele in mylist if letter in ele])
print ('Amount of words containing a: ' +str(res))
Here system response: 3 , as expected.
Please tell me what should I check in code #1.
Few mistakes I found in your code:
When you do for i in range(len(mylist)), you are actually looping through the numbers 1,2,... instead of elements of mylist. So you have to use "for i in mylist" to loop through elements of the array mylist.
When you return from a function, the code that is after the return is not executed. So you have to print it first and then return from the function.
Don't forget to call the function. Otherwise the function won't be executed.
No need count variable as you can access the length using len method.
mylist = ['fortran', 'basic', 'java', 'python', 'c++']
letter = 'a'
a_list = []
def count_letter(mylist):
for i in mylist:
if letter in i:
a_list.append(i)
print(len(a_list))
return a_list
print(count_letter(mylist))
All the best in your journey!
Personally, I find Python source code easier to read when things are indented by four spaces. So, here is your function again with a wider indentation:
def count_letter(mylist):
count = 0
for i in range(len(mylist)):
if letter in i:
count += 1
a_list.append(i)
return a_list
print(len(a_list))
for i in range(...) will iterate over a collection of integers. So, i will take on a new integer value for each iteration of the loop. First i will be 0, then 1 on the next iteration, and so on.
You then ask if letter in i:. This can never be true. letter is a string, and i is an integer. A string can never be "in" an integer - so this if-statement will never execute. Rather, you want to check if letter is in the current word (the ith word in the list). The if-statement should read:
if letter in mylist[i]:
...
Where mylist[i] is the current word.
You then increment count and append i to a_list. You probably meant to append mylist[i] to a_list, but I don't see why you even need a_list. You just need count, since that keeps track of how many words you've encountered so far for which the condition is true. count is also the variable you should be returning in the end, since that is the purpose of the function: to return the number of words (not the words themselves) which contain a certain letter.
Also, the way your final print statement is indented makes it part of the function's body. It's after the return, though, which means it will never actually get a chance to print. When you use return inside a function, it ends the function, and flow of execution returns to the place from which the function was originally invoked.
One final change that needs to be applied, is that your function should accept a letter to look for as a parameter. Right now, your function only takes one parameter - the list of words through which to search.
Here are the changes I would apply to your code:
def count_letter(words, letter): # I find 'words' is a better name than 'mylist'.
count = 0
for i in range(len(words)):
current_word = words[i]
if letter in current_word:
count += 1
return count
Here is how you might use the function:
words = ["hello", "world", "apple", "sauce"]
letter = "e"
count = count_letter(words, letter)
print("The letter '{}' appeared in {} words.".format(letter, count))
Output:
The letter 'e' appeared in 3 words.
I think that 'takes' means that function must be defined with two parameters: words_list and letter:
def count_letter(words_list, letter):
Algorithm in natural language could be: give me sum of words where letter is present for every word in words list.
In Python it can be expressed as:
def count_letter(words_list, letter):
return sum(letter in word for word in words_list)
Some explanation: letter in word returns boolean value (True or False) and in Python bools are subclass of integer (True is 1 and False is 0). If letter is in word the result would be 1 and if not it would be 0. Summing up of results gives number of words where letter is present
I have read all your answers, some important points I wrote down, sat today again with my code, and after some more tries it worked...
So final version looks like:
words = ['fortran', 'basic', 'java', 'python', 'c++']
letter = "a"
def count_letter(words, letter):
count = 0
for word in words:
if letter in word:
count += 1
return count
print(count_letter((words),letter))
System response:
3
What is not yet obvious for me: correct indents (they were also part of a problem), and additional pair of parentheses around words in print line. But it comes with learning.
Thank you once again!

Cannot remove two vowels in a row

I have to enter a string, remove all spaces and print the string without vowels. I also have to print a string of all the removed vowels.
I have gotten very close to this goal, but for some reason when I try to remove all the vowels it will not remove two vowels in a row. Why is this? Please give answers for this specific block of code, as solutions have helped me solve the challenge but not my specific problem
# first define our function
def disemvowel(words):
# separate the sentence into separate letters in a list
no_v = list(words.lower().replace(" ", ""))
print no_v
# create an empty list for all vowels
v = []
# assign the number 0 to a
a = 0
for l in no_v:
# if a letter in the list is a vowel:
if l == "a" or l == "e" or l == "i" or l == "o" or l == "u":
# add it to the vowel list
v.append(l)
#print v
# delete it from the original list with a
del no_v[a]
print no_v
# increment a by 1, in order to keep a's position in the list moving
else:
a += 1
# print both lists with all spaces removed, joined together
print "".join(no_v)
print "".join(v)
disemvowel(raw_input(""))
Mistakes
So there are a lot of other, and perhaps better approaches to solve this problem. But as you mentioned I just discuss your failures or what you can do better.
1. Make a list of input word
There are a lot of thins you could do better
no_v = list(words.lower().replace(" ", ""))
You don't replaces all spaces cause of " " -> " " so just use this instead
no_v = list(words.lower().translate( None, string.whitespace))
2. Replace for loop with while loop
Because if you delete an element of the list the for l in no_v: will go to the next position. But because of the deletion you need the same position, to remove all the vowels in no_v and put them in v.
while a < len(no_v):
l = no_v[a]
3. Return the values
Cause it's a function don't print the values just return them. In this case replace the print no_v print v and just return and print them.
return (no_v,v) # returning both lists as tuple
4. Not a mistake but be prepared for python 3.x
Just try to use always print("Have a nice day") instead of print "Have a nice day"
Your Algorithm without the mistakes
Your algorithm now looks like this
import string
def disemvowel(words):
no_v = list(words.lower().translate( None, string.whitespace))
v = []
a = 0
while a < len(no_v):
l = no_v[a]
if l == "a" or l == "e" or l == "i" or l == "o" or l == "u":
v.append(l)
del no_v[a]
else:
a += 1
return ("".join(no_v),"".join(v))
print(disemvowel("Stackoverflow is cool !"))
Output
For the sentence Stackoverflow is cool !\n it outputs
('stckvrflwscl!', 'aoeoioo')
How I would do this in python
Not asked but I give you a solution I would probably use. Cause it has something to do with string replacement, or matching I would just use regex.
def myDisemvowel(words):
words = words.lower().translate( None, string.whitespace)
nv = re.sub("[aeiou]*","", words)
v = re.sub("[^a^e^i^o^u]*","", words)
return (nv, v)
print(myDisemvowel("Stackoverflow is cool !\n"))
I use just a regular expression and for the nv string I just replace all voewls with and empty string. For the vowel string I just replace the group of all non vowels with an empty string. If you write this compact, you could solve this with 2 lines of code (Just returning the replacement)
Output
For the sentence Stackoverflow is cool !\n it outputs
('stckvrflwscl!', 'aoeoioo')
You are modifying no_v while iterating through it. It'd be a lot simpler just to make two new lists, one with vowels and one without.
Another option is to convert it to a while loop:
while a < len(no_v):
l = no_v[a]
This way you have just a single variable tracking your place in no_v instead of the two you currently have.
For educational purposes, this all can be made significantly less cumbersome.
def devowel(input_str, vowels="aeiou"):
filtered_chars = [char for char in input_str
if char.lower() not in vowels and not char.isspace()]
return ''.join(filtered_chars)
assert devowel('big BOOM') == 'bgBM'
To help you learn, do the following:
Define a function that returns True if a particular character has to be removed.
Using that function, loop through the characters of the input string and only leave eligible characters.
In the above, avoid using indexes and len(), instead iterate over characters, as in for char in input_str:.
Learn about list comprehensions.
(Bonus points:) Read about the filter function.

Translation from English to Pig Latin

I'm doing part of the 'PigLatin translation' program.
Here is the part I'm doing writing right now.
input_str = input("Input a word: ")
consonant_check = 0
while input_str[int(consonant_check)] != 'a' or 'e' or 'i' or 'u':
output_str = input_str[:int(consonant_check)] + input_str[0,int(consonant_check)] + 'ay'
consonant_check = int(consonant_check) + 1
else:
print(output_str)
This part is supposed to check if the word input begins with a consonant. If it does, the program could remove all consonants from the beginning of the word and append them to the end of the word. Then append "ay" to the end of the word.
By collecting information online I had some clues about how to make it happen but I think there are still something wrong with my code.
I would approach it similar to what you intended, resulting in the code below.
In short, check the first character of a string. If it's not a vowel (not in ['a','e','i','o','u']), move the character to the end of the string. Keep doing that until you hit a vowel (so 'string' becomes 'trings' then 'ringst' then 'ingstr' before breaking the loop). Once you finally hit a vowel, you leave the loop, and print the modified string + 'ay'. If the first character is a vowel, you leave the loop and print the string + 'ay'.
There's no need to set a consonant check - you're always checking the first character (0). And there's no need to have two variables - just keep modifying and replacing the original string.
word_string = input("Input a word: ")
while word_string[0] not in ['a','e','i','o','u']:
word_string = word_string[1:] + word_string[0:1]
else:
print(word_string + 'ay')
This isn't a direct answer to your question, but my solution to the pig-latin problem. When learning python, I found that looking at completed examples helped a great deal.
word = "snake"
import string
# Create a list of vowels an consonants
vowels = ['a','e','i','o','u','y']
vowels += [v.upper() for v in vowels]
consonants = [x for x in string.ascii_letters if x not in vowels]
if word[0] in consonants:
# Find the first vowel
idx = min([word.find(v) for v in vowels if word.find(v)>0])
# Split the word at this point and add 'ay'
word = word[idx:] + word[:idx] + 'ay'
print(word)
# Returns "akesnay"
I think your logic is overall a little messed up. I would suggest tackling the problem like this.
1.) Check to see if the first letter is a consonant, if not, do nothing, if so, go to step 2
2.) Find all of the consonants in the word and store them in a list
3.) If it is, remove the vowels from the word, and then append all of the consonant onto the end, followed by 'ay'.
There are infinite ways to actually implement this and I think it would be a good exercise for you to try to implement it yourself, but let me know if you need any more help.

Removing items for a list using a loop in Python

I am very new to programming in general and have started with Python. I am working through various problems to try and better my understanding.
I am trying to define a function that removes vowels from a string. This is what I have tried:
def anti_vowel(text):
new = []
for i in range(len(text)):
new.append(text[i])
print new
for x in new:
if x == "e" or x == "E" or x == "a" or x == "A" or x == "i" or x == "I" or x == "o" or x == "O" or x == "u" or x == "U":
new.remove(x)
return "".join(new)
This is removing vowels from the first words of a string, but not the final word:
eg:
anti_vowel("Hey look words!")
returns: "Hy lk words!"
Can somebody please explain where I am going wrong so I can learn from this?
Thanks :)
You should not delete items from a list while iterating through it. You will find numerous posts on Stack Overflow explaining why.
I would use the filter function
>>> vowels = 'aeiouAEIOU'
>>> myString = 'This is my string that has vowels in it'
>>> filter(lambda i : i not in vowels, myString)
'Ths s my strng tht hs vwls n t'
Written as a function, this would be
def anti_vowel(text):
vowels = 'aeiouAEIOU'
return filter(lambda letter : letter not in vowels, text)
Test
>>> anti_vowel(myString)
'Ths s my strng tht hs vwls n t'
You seem to have approached this a bit backwards. Firstly, note that:
new = []
for i in range(len(text)):
new.append(text[i])
is just:
new = list(text)
Secondly, why not check before appending, rather than afterwards? Then you only have to iterate over the characters once. This could be:
def anti_vowel(text):
"""Remove all vowels from the supplied text.""" # explanatory docstring
non_vowels = [] # clear variable names
vowels = set("aeiouAEIOU") # sets allow fast membership tests
for char in text: # iterate directly over characters, no need for 'i'
if char not in vowels: # test membership of vowels
non_vowels.append(char) # add non-vowels only
return "".join(non_vowels)
A quick example:
>>> anti_vowel("Hey look words!")
'Hy lk wrds!'
This simplifies further to a list comprehension:
def anti_vowel(text):
"""Remove all vowels from the supplied text."""
vowels = set("aeiouAEIOU")
return "".join([char for char in text if char not in vowels])
You can use a list comp:
def anti_vowel(text):
vowels = 'aeiouAEIOU'
return "".join([x for x in text if x not in vowels])
print anti_vowel("Hey look words!")
Hy lk wrds!
The list comprehension filters the vowels from the words.
You can also do it succinctly with a comprehension:
def anti_vowel(text):
return ''.join(ch for ch in text if ch.upper() not in 'AEIOU')
Iteration is an indexed operation. When you remove an item from a list while iterating over it, you essentially change the indices of every item in the list that follows the item you removed. When you loop over the list
['h','e','y',' ','l','o','o','k',' ','w','o','r','d','s']
whilst removing an item in 'aeiou', on the second iteration of the loop, you remove 'e' from your list and your left with
['h','y',' ','l','o','o','k',' ','w','o','r','d','s']
then on the third iteration, instead of testing your if statement on the y, which was originally in the third position, it is now testing it on the ' ', which is what is in the third position of the the modified list.
mylist.remove(x)
will search for the first matching value of x inmylist and remove it. When your loop gets to the first 'o' in the list, it removes it, thereby changing the index of the following 'o' by -1. On the next iteration of the loop, it is looking at 'k' instead of the subsequent 'o'.
However, why then did your function remove the first two 'o's and not the last one?
Your loop looked at the first 'o', not the second 'o', and looked at the third 'o'. In total your loop found two matches for 'o' and performed the remove function on both. And again, since the remove function will find the first matching item in the list and remove it, that's why it removed the first two 'o's, although for the removal of the second 'o' your loop was actually iterating over the third 'o'.
You were fortunate to have done this test on a string with consecutive vowels. Had you done it on a string without consecutive vowels, you would have removed all the vowels with your function and it would have appeared to work as you intended.

Python: Adding Copies of a Character in a String

I'm trying to figure out how to add copies of a character in a string, as long as the character is a vowel.
For example, if I input the word copy('app'), it would ideally return 'aaaapp!'. I know that strings are immutable, but there has to be a way! I've been staring at this for hours.
Note: I don't want a solution to my code, preferably just a hint to get me in the right direction.
Edit: Thanks for all the help!
One of my ideas was: word += word + i*4 but that returns something like 'appaaaa!'
def copy(word):
"('string') ==> ('string') Adds four copies of vowel and an '!' to the string"
vowel = 'aeiouAEIOU'
for i in word:
if i in vowel:
#Missing code Here
return word + '!'
You can use re.sub pretty easily:
>>> re.sub('([aeiouAEIOU])',r'\1\1\1\1','string')
'striiiing'
Or, if you want the number of substitutions to be variable:
>>> N=4
>>> re.sub('([aeiouAEIOU])',r'\1'*N,'string')
'striiiing'
The key is to make a new string. If the character is not a vowel, you just copy it to the new string. If it's a vowel, you copy four copies of it to the new string. Then you return the new string. Here's one way to do it:
def copy(word):
vowels = set ("AEIOUaeiou")
return "".join(char * 4 if char in vowels else char for char in word) + "!"
Compose a separate string while you scan your input:
s = ''
for i in word:
if i in vowel:
s += i*4
else:
s += i
s += '!'
You can copy each character of the string to a list, insert vowels at your leisure and then join the list back to a string: ''.join(mylist))

Categories