I'm working on something but can't seem to get the code to do what I need it to -- I'm presented with the following code:
def pig_latin(string):
vowels = ['a', 'e', 'o', 'i', 'u']
if string[0] in vowels: #if the first letter is vowel
return string + 'ay'
elif string[1] in vowels: #if the first letter is consonant
return string[1:] + string[0] + 'ay'
elif string[2] in vowels: #if first two letters are consonants
return string[2:] + string[:2] + 'ay'
else: #if the first three letters are consonants
return string[3:] + string[:3] + 'ay'
With this, I'm supposed to modify my string "the empire strikes back" to instead read "ethay empireay ikesstray ackbay." I was able to change the code to at least get back "empireay" (and forgot exactly how) but haven't had success with the rest. What am I not seeing here?
You're code seems to work for one word - you just need to call it for all words in the sentence:
def pig_latin(string):
vowels = ['a', 'e', 'o', 'i', 'u']
if string[0] in vowels: #if the first letter is vowel
return string + 'ay'
elif string[1] in vowels: #if the first letter is consonant
return string[1:] + string[0] + 'ay'
elif string[2] in vowels: #if first two letters are consonants
return string[2:] + string[:2] + 'ay'
else: #if the first three letters are consonants
return string[3:] + string[:3] + 'ay'
string = "the empire strikes back"
parts = string.split(" ")
pig_latin_parts = [pig_latin(part) for part in parts]
print(" ".join(pig_latin_parts)) // prints "ethay empireay ikesstray ackbay"
Related
I'm trying to solve a problem that requires me to take a sentence and double each consonant and put an 'o' in between.
I know that it's possible to use an if statement in one line but the 'else' statement doesn't work.
vowels = list('aeiouyäöå')
consonants = list('qwrtpsdfghjklzxcvbnm')
# if letter is a consonant then double it and out 'o' in between.
def rovarspraket(sentence):
return ''.join([letter for letter in sentence if letter in vowels else (letter + 'o' + letter)])
print(rovarspraket('hello friend'))
# should output 'hohelollolo fofrorienondod'.
You have the syntax for the else-part in the conditional comprehension a bit wrong:
def rovarspraket(sentence):
return ''.join([l if l in vowels else (l + 'o' + l) for l in sentence])
Or even better (more robust wrt whitespace):
def rovarspraket(sentence):
return ''.join([(l + 'o' + l) if l in consonants else l for l in sentence])
>>> print(rovarspraket('hello friend'))
hohelollolo fofrorienondod
The space matters too:
return ''.join(letter if letter in vowels or letter == ' ' else (letter + 'o' + letter)for letter in sentence)
So whole, code:
vowels = list('aeiouyäöå')
consonants = list('qwrtpsdfghjklzxcvbnm')
# if letter is a consonant then double it and out 'o' in between.
def rovarspraket(sentence):
return ''.join(letter if letter in vowels or letter == ' ' else (letter + 'o' + letter)for letter in sentence)
print(rovarspraket('hello friend'))
Output:
hohelollolo fofrorienondod
I've been working on a Pig Latin program. However, it doesn't seem to be working and I can't figure out why.
user_input = input("Enter word to be translated:")
def translate(user_input):
first = user_input[0]
if first == "a" or "e" or "i" or "o" or "u":
user_input = user_input.lower()
user_input += "way"
return user_input
else:
user_input = user_input.lower()
user_input = user_input[1:]+first+"ay"
return user_input
print(translate(user_input))
On top of that, I was looking to utilize enumerate to find the position of the first vowel, slicing to isolate the first letter of the word and concatenation to form the word. I've read up on how to use it on a couple websites but I can't seem to figure out how to correctly apply it to this program. I think I would have to define Vowels = 'aeiou' before def translate(user_input) right??
You cannot chain if statements like that in Python, you have to do it the long way:
if first == "a" or first == "e" or first == "i" or first == "u":
or shorten it to:
if first in ["a", "e", "i", "u"]:
Here is the solution. I've made a few changes in your code which i will be explaining below.
user_input = input("Enter word to be translated:\n")
#change_1
vowels = ['a','e','i','o','u']
def translate(user_input):
first = user_input[0]
#change_2
if first in vowels:
user_input = user_input.lower()
user_input += "way"
return user_input
else:
user_input = user_input.lower()
#change_3
for letter in user_input:
if letter in vowels:
index_value = user_input.index(letter)
break
#change_4
user_input = user_input[index_value:] +user_input[:index_value]+ "ay"
return user_input
print(translate(user_input))
1) Create a list of vowels.
2) As our friend #zwer mentioned You cannot chain if statements like that in
Python. So
if first in vowels:
3) For every letter in user_input check if that letter is a vowel and if that letter is a vowel then find the index of it's occurrence.
For example take the word 'trash'
Here a is the first vowel and it's index is 2
if letter in vowels:
index_value = user_input.index(letter)
4) According to wikipedia
"all letters before the initial vowel are placed at the end of the word sequence"
For the word 'trash' it would be
user_string = user_input[2:] + user_input[:2]+"ay"
which would be slicing the word from that index to end, merged with letters before that index. And finally an "ay".
'ash' + 'tr' + 'ay'
Hope this helps.
You can define vowels in the outer scope.
vowels = 'a', 'e', 'i', 'o', 'u'
Then anywhere you can use:
if first in vowels:
My Solution covers the below rules:
1. A word is a consecutive sequence of letters (a-z, A-Z) or apostrophes. You may assume that the input to the function will only be a single "word". Examples: Zebra , apple
2. If a word starts with a vowel, the Pig Latin version is the original word with "way" added to the end
3. If a word starts with a consonant, or a series of consecutive consonants, the Pig Latin version transfers ALL consonants up to the first vowel to the end of the word, and adds "ay" to the end.
4. The letter 'y' should be treated as a consonant if it is the first letter of a word, but treated as a vowel otherwise.
5. If the original word is capitalized, the new Pig Latin version of the word should be capitalized in the first letter. If the original capital letter was a consonant, and thus moved, it should not be capitalized once in its new location.
Solution Starts here:
eng_to_pig_latin = {"football": "ootballfay", "Pittsburgh":"Ittsburghpay",
"Apple":"Appleway","oink":"oinkway",
"ontology":"ontologyway","yellow":"ellowyay","yttrium":"iumyttray"}
eng_word = 'yttrium'
vowels = 'aeiou'
def pig_latin(eng_word):
sub,str1 = [],''
first = eng_word[0]
second = eng_word[1]
# Rule 2
if first.lower() in vowels:
piglatin = eng_word +'way'
# Rule 3
elif first.lower() == first and second.lower() in vowels:
piglatin = eng_word[1:]+first+'ay'
elif first.lower()+second.lower() not in vowels:
# Rule 3 & 4
for l in eng_word:
if l not in vowels:
sub.append(l)
else:
str1 = eng_word[eng_word.index(l):]
break
str2 = ''.join(sub)
piglatin = str1+str2+'ay'
else:
# Rule 5
piglatin = eng_word[1:].capitalize()+first.lower()+'ay'
print(f'Test word is {eng_word} and its equivalent piglatin word is
{piglatin}. Comparison with mapping dictionary is
{eng_to_pig_latin[eng_word] == piglatin}')
pig_latin(eng_word)
Note: The dictionary uses is only to cross-check if the results are as expected, which I am doing in the last print statement.
my logic to translate given word in to Pig Latin translation
vowels=['a','e','i','o','u']
def igpay(name):
a_list=list(name)
if a_list[0] in vowels:
print("First letter is a Vowel")
apnd_letters="way"
else:
print("First letter is a Consonant")
a_list.append(a_list[0])
a_list.pop(0)
apnd_letters="ay"
print("Pig transaltion is {0}".format("".join(a_list)+str(apnd_letters)))
Output:
igpay("pig")
First letter is a Consonant
Pig transaltion is igpay
igpay("apple")
First letter is a Vowel
Pig transaltion is appleway
You can do it exactly the same as you are doing it except you will need to change the second line in translate:
if first == "a" or "e" or "i" or "o" or "u":
to:
if first == "a" or first == "e" or first == "i" or first == "o" or first == "u":
or:
if first in 'aeiou':
If you want to be able to use capital letters however, I would recommend changing first to first.lower().
This becomes:
user_input = input("Enter word to be translated:")
def translate(user_input):
first = user_input[0]
if first.lower() in 'aeiou':
user_input = user_input.lower()
user_input += "way"
return user_input
else:
user_input = user_input.lower()
user_input = user_input[1:]+first+"ay"
return user_input
print(translate(user_input))
If you want the code a bit shorter, I have managed to shorten it to:
def translate():
user_input = input('Enter a word or sentence')
for i in range(len(user_input.split())): print(str((user_input.split())[i][1::])+((user_input.split())[i])[0]+'ay', end=' ')
translate()
Here is another two ways to go about it
Method 1:
Using a function that recursively translates words
sentence = str(input('Input Sentence: '))
vowels = 'aeiouAEIOU'
# 1. strip removes whitespace before and after input
# 2. pig_word_latin deals with one word at a time
# 3. join collects all the words into one sentence with spaces
def pig_latin_word(word):
vowelStart = True
#print(word)
if word[0] not in vowels:
vowelStart = False
return pig_latin_word(word[1:] + word[:1])
elif word[0] in vowels and not vowelStart:
return word + 'ay'
elif word[0] in vowels and vowelStart:
return word + 'way'
def pig_latin(sentence):
words: list = sentence.strip().split(' ')
new_words = []
for word in words:
new_words.append(pig_latin_word(word))
print(" ".join(new_words))
pig_latin(sentence)
Method 2:
Using a function that recursively translates sentences by keeping track of spaces
sentence = str(input('Input Sentence: ')).strip()
vowels = 'aeiouAEIOU'
suffix = {}
suffix[True] = 'way'
suffix[False] = 'ay'
def pig_latin(sentence, acc='', cluster='', word=''):
#print('S:'+sentence, 'C:'+cluster, 'W:'+word)
#print('Acc:',acc)
new_word = len(word)==0
vowel_start= len(cluster)==0
#print('NW:',new_word, suffix[vowel_start])
#print('-')
if len(sentence) == 0:
return acc+word+cluster+suffix[vowel_start]
if sentence[0] == ' ':
return pig_latin(sentence[1:], acc+word+cluster+suffix[vowel_start]+' ')
if new_word == True:
if sentence[0] not in vowels:
#print('1---')
return pig_latin(sentence[1:], acc, cluster+sentence[0], '')
elif sentence[0] in vowels and not vowel_start:
#print('2---')
return pig_latin(sentence[1:], acc, cluster, word+sentence[0])
elif sentence[0] in vowels and vowel_start:
#print('3---')
return pig_latin(sentence[1:], acc, '', word+sentence[0])
else:
return pig_latin(sentence[1:], acc, cluster, word+sentence[0])
print(pig_latin(sentence))
So I have a function that takes a string input and turns it into pig latin.
For all words that begin with consonants (everything except vowels), I have to take the first letter of that word and move it to the back and then add "ay" to the word.
For example "like" would become "ikelay".
In my program, the string input given to me is first split and then each element of that newly created list is checked to see if the first character of that element is either a vowel, a consonant, or otherwise.
def simple_pig_latin(input, sep=" ", end="."):
splitinput = input.split(sep)
for i in splitinput:
if splitinput[splitinput.index(i)][0] in ['a','e','i','o','u']:
splitinput[splitinput.index(i)] = str(i) + "way"
elif splitinput[splitinput.index(i)][0] in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']:
splitinput[splitinput.index(i)] = str(i) + "ay"
else:
continue
finalstring = ' '.join(splitinput)
finalstring = finalstring + end
simple_pig_latin("i like this")
Notice in the elif branch, I am supposed to take the first letter of i and put it at the end of that word and add "ay" to it. Given the input string "i like this" I should turn the second word (since like starts with l, making it a consonant) into 'ikelay' How would I rearrange like so that it became ikel?
I tried to keep your structure while still removing the useless code :
def simple_pig_latin(input_text, sep=" ", end="."):
words = input_text.split(sep)
new_words = []
for word in words:
if word[0].lower() in ['a', 'e', 'i', 'o', 'u']:
new_words.append(word + "way")
else:
new_words.append(word[1:] + word[0] + "ay")
finalstring = sep.join(new_words)
finalstring = finalstring + end
return finalstring
print simple_pig_latin("i like this")
# iway ikelay histay.
Notes :
Your function needs to return something
It's probably easier to create a new list than to mutate the original one
if i is already a string, there's no need to call str(i)
i is usually used for an integer between 0 and n-1. Not for words.
word[0] is the first letter of your word
word[k:] is word without the first k letters
to simplify your code, I consider that if the first letter isn't a vowel, it must be a consonant.
I call lower() on the first letter in order to check if 'I' is a vowel.
For your question, you could change your code str(i) + "ay" to i[1:] + i[0] + "ay" in your elif branch.
I'm a beginner learning the python language and I'm stumped on how take the vowels of a word and replacing them with an underscore.
So far this is what I have come up with and it just doesn't work
word = input("Enter a word: ")
new_word = ""
vowels = "aeiouy"
for letter in word:
if letter != vowels:
new_word += word
else:
new_word += "_"
print(new_word)
You can use string.translate and maketrans.
from string import maketrans
vowels = "aeiouy"
t = "______"
st = "trying this string"
tran = maketrans(vowels, t)
print st.translate(tran)
# Gives tr__ng th_s str_ng
You may also want to check uppercases.
you can use regex
import re
print(re.sub("[aeiouAEIOU]", "_", "abc")) # prints _bc
Make vowels an array with each element it's own letter.
Then do
for letter in word:
if letter in vowels:
letter = "_"
Lists can be used to easily build words, and with .join() you can combine the list items into a single string.
word = 'pizza'
vowels = "aeiouy"
new_word = []
for letter in word:
if letter in vowels:
new_word.append('_')
else:
new_word.append(letter)
print(''.join(new_word))
Here's the same thing in a generator expression:
word = 'pizza'
vowels = "aeiouy"
new_word = ''.join(c if c not in vowels else '_' for c in word)
print(new_word)
To answer why your approach didn't work.
if letter != vowels:
Does not do what you are thinking. It actually compares the letter against a full string "aeiouy". It will always be unequal (e.g. "a" != "aeiouy" is True and so is any other letter).
More likely what you mean was
if letter in vowels:
Which under the hood will iterate over vowels and compare each character to letter, returning True if any of the letters match.
The second mistake is here
new_word += word
You are adding the original word to the new word rather than the letter you just checked. So make that
new_word += letter
The third thing to note is that your logic is the reverse of what you intended. You wanted to replace vowels with _ but your if statement allows vowels into the new word and replaces consonants with the underscore. So if you reverse your if and else clauses.
All up you end up with
word = input("Enter a word: ")
new_word = ""
vowels = "aeiouy"
for letter in word:
if letter in vowels:
new_word += '_'
else:
new_word += letter
print(new_word)
Using a list comprehension and setting vowels as a set object (this is really only valuable for speeding up performance if you have a large list of words over which you're iterating):
>>> vowels = set("aeiouy")
>>> word = 'ampersand'
>>> new_word = "".join([letter if letter not in vowels else "_" for letter in word])
>>> print(new_word)
_mp_rs_nd
If you have Python 3, use str.maketrans to build a string translation table:
vowels = "aeiouy"
vowels += vowels.upper()
tr = str.maketrans(vowels, '_' * len(vowels))
print('Yo, this is a wacky phrase!'.translate(tr))
Shows: __, th_s _s _ w_ck_ phr_s_!
DRAX: I'll do you even better!
def replace_vowels(word):
vowels = ['a', 'e', 'i', 'o', 'u']
for x in (word.lower()):
if x in vowels:
word = word.replace(x, "_")
print(word)
replace_vowels('Stackoverflow')
Output
St_ck_v_rfl_w
VOWELS = ('a', 'e', 'i', 'o', 'u')
def pigLatin(word):
first_letter = word[0]
if first_letter in VOWELS: # if word starts with a vowel...
return word + "hay" # then keep it as it is and add hay to the end
else:
return word[1:] + word[0] + "ay"
def findFirstVowel(word):
novowel = False
if novowel == False:
for c in word:
if c in VOWELS:
return c
I need to write a piglatin translator that can handle words that start with multiple consonants.
For example, the output I get currently when I enter "string" is:
PigLatin("string") = tringsay
I would want the output:
PigLatin("string") = ingstray
To write this, I wrote an additional function to iterate through the word and find the first vowel, but after that I am not sure how to proceed.
Any help would be appreciated.
After finding the first vowel, get its index in the string by doing word.index(c). Then, slice the whole word from the beginning to the index of the vowel
With that slice, put it at the end of the word and add 'ay', as you did in your first function.
You need to find the index of a consonant and slice on it.
Here's an example:
def isvowel(letter): return letter.lower() in "aeiou"
def pigLatin(word):
if isvowel(word[0]): # if word starts with a vowel...
return word + "hay" # then keep it as it is and add hay to the end
else:
first_vowel_position = get_first_vowel_position(word)
return word[first_vowel_position:] + word[:first_vowel_position] + "ay"
def get_first_vowel_position(word):
for position, letter in enumerate(word):
if isvowel(letter):
return position
return -1
There are probably more eloquent ways of doing this but this is my solution. Hopefully it helps!
def pigLatin(aString):
index = 0
stringLength = len(aString)
consonants = ''
# if aString starts with a vowel then just add 'way' to the end
if isVowel(aString[index]):
return aString + 'way'
else:
# the first letter is added to the list of consonants
consonants += aString[index]
index += 1
# if the next character of aString is a vowel, then from the index
# of the vowel onwards + any consonants + 'ay' is returned
while index < stringLength:
if isVowel(aString[index]):
return aString[index:stringLength] + consonants + 'ay'
else:
consonants += aString[index]
index += 1
return 'This word does contain any vowels.'
def isVowel(character):
vowels = 'aeiou'
return character in vowels