Python Simple Loop in function - python

for word in sentence.split():
if word[0] in VOWELS:
pig_latin = word + "ay"
else:
pig_latin = word[1:] + word[0] + "ay"
return pig_latin
How do I make it so that the return prints the whole sentence in the main, not just the one word?

You have to build the whole sentence in some way. For example, you can build up a list of words:
pig_words = []
for word in sentence.split():
if word[0] in VOWELS:
pig_latin = word + "ay"
else:
pig_latin = word[1:] + word[0] + "ay"
pig_words.append(pig_latin)
return pig_words
If you want to turn it back into a sentence, the opposite of split is join, so just change the last line to:
return ' '.join(pig_words)

You need to append the values to a list and remove the return statement from the loop, so that it will return the list after the for loops has finished iterating.
words = []
for word in sentence.split():
if word[0] in VOWELS:
pig_latin = word + "ay"
else:
pig_latin = word[1:] + word[0] + "ay"
words.append(pig_latin)
return words

Your return statement is executed on the first pass though your for loop. Even if you un-indented the return statement to run at the conclusion, you would then only have the last translated word in the pig_latin variable.
To translate the whole sentence, you should only return after the entire for loop runs to completion, saving the accumulated list of translated words.
entensesay = []
for word in sentence.split():
if word[0] in VOWELS:
entensesay.append(word + "ay")
else:
entensesay.append(word[1:] + word[0] + "ay")
return ' '.join(entensesay)
It is also good habit to avoid doing string concatenation in loops in Python. List append method is more efficient, and then use ' '.join() to produce the final concatenated string.

Related

How do I make my code capitalize the first letter of the word that has a capital letter in it? (Pig Latin)

My code so far is:
def to_pig(string):
words = string.split()
for i, word in enumerate(words):
'''
if first letter is a vowel
'''
if word[0] in 'aeiou':
words[i] = words[i]+ "yay"
elif word[0] in 'AEIOU':
words[i] = words[i]+ "yay"
else:
'''
else get vowel position and postfix all the consonants
present before that vowel to the end of the word along with "ay"
'''
has_vowel = False
for j, letter in enumerate(word):
if letter in 'aeiou':
words[i] = word[j:] + word[:j] + "ay"
has_vowel = True
break
#if the word doesn't have any vowel then simply postfix "ay"
if(has_vowel == False):
words[i] = words[i]+ "ay"
pig_latin = ' '.join(words)
return pig_latin
My code right now coverts a string to pig latin string. If a word starts with one or more consonants followed by a vowel, the consonants up to but not including the first vowel are moved to the end of the word and "ay" is added. If a word begins with a vowel, then "yay" is added to the end.
String:
"The rain in Spain stays mainly in the plains"
However, my code returns:
"eThay ainray inyay ainSpay aysstay ainlymay inyay ethay ainsplay"
While it should return:
"Ethay ainray inyay Ainspay aysstay ainlymay inyay ethay ainsplay"
How do I fix my code so that it returns the first letter capital for the word that has a capital letter?
Use any(... isupper()) to check for the presence of a capital letter and str.title() to capitalize the first letter.
>>> words = "eThay ainray inyay ainSpay aysstay ainlymay inyay ethay ainsplay".split()
>>> words = [word.title() if any(c.isupper() for c in word) else word for word in words]
>>> ' '.join(words)
'Ethay ainray inyay Ainspay aysstay ainlymay inyay ethay ainsplay'
A one-line solution would be to check whether the word contains a capital letter. If so, you want to convert the capital letter to a lowercase letter and then capitalize the first letter of that word. You could do that as such. Suppose you have your array of words, then:
words = [i[0].upper() + i[1:].lower() if i.lower() != i else i for i in words]

Python - I need to rearrange a character of a string element in a list

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.

How can I create a code that translates a string sentence to Pyglatin? [duplicate]

This question already has answers here:
python pig latin converter
(2 answers)
Closed 6 years ago.
I have a python code to translate a one worded string to pyglatin and is as follows:
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original)>0 and original.isalpha():
word = original.lower()
first = word[0]
rest = word[1:]
new_word = rest+first+pyg
print new_word
However, I'm stumped on how to translate an entire sentence to Pyglatin. The problem I'm working on has these following conditions: for words that begin with consonants, all initial consonants are moved to the end of the word and 'ay' is appended. For words that begin with a vowel, the initial vowel remains, but 'way' is added to the end of the word.
As an example, the string 'How are you today?' would be 'owhay areway uoyay odaytay?'
Read in a sentence. Break it into individual words (split method). Translate each word to Pig Latin. Concatenate the translations.
Does that get you moving?
Try this. Use split and put it into an empty string.
original = raw_input("Enter Sentence: ")
conversion = ""
for word in original.split():
if len(word)>0 and word.isalpha():
word = word.lower()
first = word[0]
rest = word[1:]
pyg = "ay"
pygword = rest+first+pyg
conversion += pygword + " "
print conversion
Here is my try, but if you are not doing it yourself at least try to understand it. (You are free to ask of course)
This has basic ability to deal with special characters like the "?"
def pygword(word):
vowels = 'aeiou'
if word[0] in vowels:
return word + 'way'
else:
while word[0] not in vowels:
word = word[1:]+word[0]
return word + "ay"
def pygsentence(sentence):
final = ''
for word in sentence.lower().split(): #split the sentence
#words should only end in symols in correct grammar
if word[-1] in '.,;:!?':
symbol = word[-1]
word = word[:-1]
else:
symbol = ''
if word.isalpha(): #check if word is alphanumerically
final += pygword(word)+symbol+' '
else:
return "There is a strange thing in one of your words."
return final[:-1] #remove last unecessary space
There may be faster, more robust, simpler, better understandable ways to do this, but this how I would start.
Test yields me:
In[1]: pygsentence("How are you today? I am fine, thank you very much good sir!")
Out[1]: 'owhay areway ouyay odaytay? iway amway inefay, ankthay ouyay eryvay uchmay oodgay irsay!'
Your code does not obey the vowel/consonant rule, so I did my own converter for single words.
Just realized that it won't be able to deal with apastrophes in the middle of words (we don't really have theese in german ;) ) so there is a little task left for you.
edit: I did not know in which order you wanted the consonants apended, since that became not clear from your example. So i made an alternative pygword function:
def pygword2(word):
vowels = 'aeiou'
if word[0] in vowels:
return word + 'way'
else:
startcons = ''
while word[0] not in vowels:
startcons = word[0] +startcons
word = word[1:]
word = word+startcons
return word + "ay"
See the differnece:
In[48]: pygword("street")
Out[48]: 'eetstray'
In[49]: pygword2("street")
Out[49]: 'eetrtsay'

print results of while loop on the same line [duplicate]

This question already has answers here:
Print in one line dynamically [duplicate]
(22 answers)
Closed 8 years ago.
So I am writing a program that asks for your input, puts the words of the sentence you entered into a list and makes the words in the statement go trough the while loop one by one.
The while loops works as follows:
if the first letter of a word is a Vowel it print the word + hay.
Ifthe first letter of the word is not a vowel it puts the first letter of the word at the end of the word + ay
the code:
VOWELS = ['a','e','i','o','u']
def pig_latin(phrase):
#We make sure the input is changed in only lower case letters.
#The words in your sentence are also putted into a list
lowercase_phrase = phrase.lower()
word_list = lowercase_phrase.split()
print word_list
x = 0
while x < len(word_list):
word = word_list[x]
if word[0] in VOWELS:
print word + 'hay'
else:
print word[1:] + word[0] + 'ay'
x = x+1
pig_latin(raw_input('Enter the sentence you want to translate to Pig Latin, do not use punctation and numbers please.'))
My problem:
If i enter for example: "Hello my name is John" in the_raw input at the end of the code i will get the following output:
ellohay
ymay
amenay
ishay
ohnjay
But i actually want the following output:
ellohay ymay amenay ishay ohnjay
If someone could explain me how to achieve this output it would be appriciated
Save the new words in another list, then at the end:
print(" ".join(pig_latin_words))
Example:
VOWELS = {'a','e','i','o','u'}
def pig_latin(phrase):
#We make sure the input is changed in only lower case letters.
#The words in your sentence are also putted into a list
word_list = phrase.lower().split()
print(word_list)
pig_latin_words = []
for word in word_list:
if word[0] in VOWELS:
pig_latin_words.append(word + "hay")
else:
pig_latin_words.append(word[1:] + word[0] + "ay")
pig_latin_phrase = " ".join(pig_latin_words)
print(pig_latin_phrase)
return pig_latin_phrase
Append a comma (,) at the end of your print statements to avoid the newline:
while x < len(word_list):
word = word_list[x]
if word[0] in VOWELS:
print word + 'hay',
else:
print word[1:] + word[0] + 'ay',
x = x+1

PigLatin translator for words starting with multiple consonants[Python]

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

Categories