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.
Related
I have been asked to create a simple word guessing game that will select a random word from a list, but then displays that word with every alternate letter replaced with a hyphen.
I have figured out the selection of the random word, but after that I don't have any idea.
The prompt does mention using the modulus operator (%) within a for-loop to detect if a letter's position is odd or even, which I understand to an extent, but I cant figure out how to make it work in this case.
Code using a for loop in Python:
word = "Python" #Add your code for random words instead
ans = ""
for i in range(len(word)):
if i%2 != 0:
ans += "-"
else:
ans += word[i]
print(ans)
Output:
P-t-o-
You could get letters at even positions using a striding subscript (word[::2]) and join them with an hyphen. Make sure to have an extra space for the last letter in case the word has an even number of letters.
word = "Elephant"
hyphened = "-".join((word+' ')[::2])
print(hyphened)
E-e-h-n-
This solution is even simpler than a for loop:
original_word = "alternate" #generate a word
word = list(original_word) #split the string in chars
word[1::2]=["-"]*len(word[1::2]) #replace chars in odd positions with '-'
print(original_word)
print("".join(word))
Hope this is useful.
I'm writing a pig latin decoder. This section works with 'qu' works but currently only is the third letter of the word is a vowel. I am implementing an if statement to get it to work for words that have a consonant as the third letter, but keep getting this error: TypeError: 'in ' requires string as left operand, not list
Here is my code:
if w[-2:] == 'ay':
RegW = []
y = w.find('-')
beginningw = w[y:]
if vowel not in beginningw[0]:
RegW.append(beginningw[0:-2] + w[0:y])
else:
RegW.append('qu' + w[0:y])
return RegW[0]
It works for these word:
ay-quay (quay)
iz-quay (quiz)
eue-quay (queue)
but NOT an-quray (quran) (returns quan w/o if statement I'm trying to)
If vowel is a list of vowel characters, I think you want this:
if beginningw[0] not in vowel:
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)+'!'
I need to write a program that will add a number of random letters after each letter in the supplied word.
Here is what I have:
import random
import string
def add_letters(word,number):
for i in range(number):
letters=''.join(random.choice(string.ascii_letters))
new_word=(letters.join(word))
return new_word
Here is what the output is supposed to look like if we enter add_letters(cat,1):
cZaQtR
My program always returns 1 letter even if I give it a different number. Also, it's always the same "random" letter after each letter in the word.
Any idea what I'm doing wrong?
There are a lot of logic errors here, and some clumsy coding (but don't worry, you'll get better while practicing)
At each loop, your new_word gets erased
You are assigning to new_word a generated letter plus the original word, it's not what you want to do.
No need to use ''.join
A correct answer would be something like:
def add_letters(word,number):
new_word = ""
for c in word: # iterate through the word
letters = ""
for k in range(number): # concatenate n random letters
letters += random.choice(string.ascii_letters)
new_word += c + letters # add the current char plus the letters to the new word
return new_word
Your logic is not correct. I would suggest adding some debugging printout inside your loop and see what you get, something like the following:
for i in range(number):
letters=''.join(random.choice(string.ascii_letters))
new_word=(letters.join(word))
print i, letters, word, new_word
This should tell you where you are going wrong. As an extra hint, you might use a second loop outside the first one.
You're never maintaining your added letters on each iteration.
You do new_word=(letters.join(word)) on every iteration, which will never keep the random letters from previous iterations, and using 'something'.join('another something') will add the 'something' in between every character of the 'another something'.
What you would want to look at instead, would be something more along the lines of
def add_letters(word, number):
new_word = ''
for character in word:
new_word += character
for _ in range(number):
new_word += random.choice(string.ascii_letters)
return new_word
which will iterate over every character of the supplied word, add it to the new_word string, then randomly choose as many characters as required and add them to the new_word, and continue till the original word is finished, and returns the new word.
Your problem is happening when you enter your loop you are always only generating at most one random character at a time with this:
letters=''.join(random.choice(string.ascii_letters))
You might want to look at your problem a different way, and instead, make use of another method in random called sample
With sample, you can provide how many random characters you want every time you call it, and they will be unique. This in effect changes your loop to instead of iterating over your number, to iterate over the word and add your characters accordingly.
import random
import string
def add_letters(word,number):
new_word = ""
for i in word:
letters = ''.join(random.sample(string.ascii_letters, number))
new_word += "{}{}".format(i, letters)
return new_word
Calling:
add_letters('cat', 2)
Outputs:
cNbarHtTM
import random
import string
def add_letters(word,number):
"""
Adds "number" randomly selected ASCII letters to the end of "word"
"""
return word + "".join([random.choice(string.ascii_letters) for k in range(number)])
for i in range(10):
print(add_letters("foo", i))
The [random.choice...] thing is a list comprehension. They're a really cool, powerful thing in Python, which I'd recommend you read up on if you don't fully understand the code.
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))