def convert_pig_latin(pig):
first_letter = pig[0]
#Check if Vowel
if first_letter in 'aeiou':
pig_word = pig + 'ay'
else:
pig_word = pig[1:] + first_letter + 'ay'
print('Pig Latin:',pig_word)
So basically, this only works for 1 single word input. Let's say the user enters a sentence, it won't work which is obvious. This code is in my functions tab, and my main module of course runs it with an input sentence given. Could someone please help me out how it'll take a whole sentence instead of just one word -.- Tried using a for loop but messed it up.
Appreciate it, thanks!
You could use a list comprehension here:
def pig_latin(sentence):
return ' '.join([s + 'ay' if s[0] in 'aeiou' else s[1:] + s[0] + 'ay' for s in sentence.split()])
print(pig_latin("convert all the words"))
Output:
onvertcay allay hetay ordsway
You could also keep your current approach where the function converts a single word, and use map():
>>> def pig_latin_word(s):
... return s + 'ay' if s[0] in 'aeiou' else s[1:] + s[0] + 'ay'
...
>>> ' '.join(map(pig_latin_word, "convert all the words".split()))
'onvertcay allay hetay ordsway'
>>>
Convert the string into a list of strings:
words = pig.split(' ')
Then you would run a for loop on the list:
for word in words:
#run your conversation code on each word
Then join the list back into a string:
pig = ' '.join(words)
Related
The objective of this python exercise is to build a function that turns text into pig latin, a simple text transformation that modifies each word by moving the first character to the end and appending "ay" to the end.
For example, python ends up as ythonpay.
I actually built this script, but I am confused as to why it is not iterating over all text.split elements? And why it is only modifying the last element?
def pig_latin(text):
say = ""
# Separate the text into words
words = text.split()
for word in words:
# Create the pig latin word and add it to the list
new_word = word[1:] + word[0] + "ay"
say = "".join(new_word)
# Turn the list back into a phrase
return say
print(pig_latin("hello how are you"))
# Should be "ellohay owhay reaay ouyay"
print(pig_latin("programming in python is fun"))
# Should be "rogrammingpay niay ythonpay siay unfay"
This section here is why. You only have one new_word variable, so each time this loop runs, it overwrites the previous value. The only value that doesn't get overwritten is the last one, and you end up with a single string.
for word in words:
new_word = word[1:] + word[0] + "ay"
say = "".join(new_word)
Instead, make sure that each new word ends up in a list. The most intuitive way to do it, IMO, is through list comprehension. Below is how you would format it for this, but look up how to do them. Seriously, it's a couple minutes of your time and they'll be one of your best friends as you continue to learn. You can also do the same thing with dictionaries.
pig_latin_text = [word[1:] + word[0] + "ay" for word in words]
say = " ".join(pig_latin)
def pig_latin(text):
say = ""
words = text.split()
for word in words:
newword = word[1:] + word[0] + 'ay'
say = say + " " + newword
return say
You are iterating over all the words, but you override the value in say in every iteration. Doing say = "".join(new_word) will not combine the new word with the existing value of say, but override it - the join function joins the arguments it receives, and in this case it only received new_word.
To fix it you should replace that line with:
say += " " + new_word
def pig_latin(text):
say = ""
# Separate the text into words
words = text.split()
for word in words:
# Create the pig latin word and add it to the list
new_word = word[1:] + word[0] + "ay"
say = say + " " + "".join(new_word)
# Turn the list back into a phrase
return say
print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"
print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"
Intention is to write a function that would reverse the words in a string. So that if the input is: "I am a student" the output should be "student am a I"
I have the following code in Python which first reverses all the characters in a string and then loops the reversed sentence to reverse the words and prints them to a "final sentence" variable.
Because the condition I am checking for is just a space, the first word doesn't get printed i.e. if the input is " I am a student" my code works (notice the space before "I") ... however if the input is "I am a student" then the output is just "student a am"
I need to know how can I modify my IF statement so it doesn't miss the first word
def reverse(sentence):
count = 0
new_sentence = ''
final_sentence = ''
counter = 0
word = ''
for char in sentence[::-1]:
new_sentence = new_sentence + char
for char in new_sentence:
if char != " ":
count = count + 1
continue
else:
for i in new_sentence[count-1::-1]:
if i != " ":
word = word + i
else:
break
count = count + 1
final_sentence = final_sentence + " " + word
word = ''
print final_sentence
reverse("I am a student")
I'm not sure why you are doing such complicated loops? You can just split the sentence, reverse and then join it again:
>>> ' '.join('I am a student'.split(' ')[::-1])
'student a am I'
To translate that into a function:
def reverse_sentence(sentence):
return ' '.join(sentence.split(' ')[::-1])
You're doing several strange things in your code. For example:
new_sentence = ''
for char in sentence[::-1]:
new_sentence = new_sentence + char
The string you're building through concatenation is already present in sentence[::-1]. You could've just done new_sentence = sentence[::-1].
You can check for the first word by using enumerate() and checking whether there is a space prior to that point in the sentence:
for idx,char in enumerate(new_sentence):
if char != " " or ' ' not in new_sentence[:idx]:
However, the easiest way to accomplish your actual goal is with split(), splitting the sentence by whitespace automatically. Use join() to put it back together once you've reversed it.
def reverse(sentence):
return ' '.join(sentence.split()[::-1])
Shift word to right and then reverse it.
You should take a word shift to right and reverse it then return as follows:
>>> shift_reverse('Introduction to Computer Programming')
gnimmargorP noitcudortnI ot retupmoC
I tried using this method to find the above answer but it doesnt seem to work
Please help :(
s= "I Me You"
def shift_reverse(s):
l= s.split()
new_str= ' '.join(l[-1:] + l[:-1])
new_str = new_str[::-1]
return (new_str)
print (shift_reverse(s))
but the print i get is
[evaluate untitled-3.py]
eM I uoY
You need to reverse each of the re-ordered list:
reordered = l[-1:] + l[:-1]
new_str = ' '.join(word[::-1] for word in reordered)
You can join a generator expression that generates reversed words in the rotated split list:
>>> s = 'Introduction to Computer Programming'
>>> ' '.join(w[::-1] for w in (lambda l: l[-1:] + l[:-1])(s.split()))
'gnimmargorP noitcudortnI ot retupmoC'
Here is a step by step with the functions:
Create shift function to move last word to beginning:
def shift(sentence):
words = sentence.split()
return ' '.join([words[-1]] + words[:-1])
Create reverse function to reverse all words in a sentence (uses list comprehension):
def reverse(sentence):
return ' '.join([word[::-1] for word in sentence.split()])
Create shift_reverse to reverse all words and then shift the last on to the start:
def shift_reverse(sentence):
return shift(reverse(sentence))
Result:
shift_reverse('Introduction to Computer Programming')
Output:
'gnimmargorP noitcudortnI ot retupmoC'
In new_str = new_str[::1], you're reversing the entire string, character per character.
ghi abc def
fed cba ihg
You have to reverse each word in the list of words.
def shift_reverse(string):
words = string.split()
shifted_words = [words[-1]] + words[:-1]
return ' '.join([word[::-1] for word in shifted_words])
You can shift the string over, the reverse each item:
>>> phrase = 'Introduction to Computer Programming'
>>> new = ' '.join([word[::-1] for word in [phrase.split()[-1]]+phrase.split()[:-1]])
>>> print new
gnimmargorP noitcudortnI ot retupmoC
>>>
def shift_reverse(s):
rev = ["".join(reversed(word)) for word in s.split(" ")]
return "{} {}".format(rev.pop(), " ".join(rev))
reverse all the strings, pop the last off the list of reversed words and join the remainder.
This should work for you
s= "Introduction to Computer Programming"
def shift_reverse(s):
l= s.split()
l = [l.pop()]+ l
return ' '.join(i[::-1] for i in l)
print (shift_reverse(s))
output:
gnimmargorP noitcudortnI ot retupmoC
Python 3. I am trying to return the function so that It would take a single word and convert it to Cow Latin. I want to get rid of the square bracket, the comma and single apostrophes when I run my function.
My function is:
alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
if word[0].lower() in alpha:
lista = (word.lower())
return lista[1:] + lista[0] + "oo"
else:
return word + "moo"
def cow_latinify_sentence(sentence):
words = sentence.split();
return [cow_latinify_word(word) for word in words]
when I test the function with
cow_latin = cow_latinify_sentence("Cook me some eggs")
print(cow_latin)
I get ['ookcoo', 'emoo', 'omesoo', 'eggsmoo'] but I want ookcoo emoo omesoo eggsmoo
Just add an asterisk before the variable name to unpack the list and feed its elements as positional arguments to print.
print(*cow_latin)
Use ' '.join(list) for concatenating the list elements into a string.
In your code:
alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
if word[0].lower() in alpha:
lista = (word.lower())
return lista[1:] + lista[0] + "oo"
else:
return word + "moo"
def cow_latinify_sentence(sentence):
words = sentence.split();
return ' '.join([cow_latinify_word(word) for word in words])
Your function cow_latinify_sentence returns a list of strings you need to join with spaces to get your desired output:
print(" ".join(cow_latin))
Let's define our variables:
>>> consonants = "bcdfghjklmnpqrstvwxyz"
>>> sentence = "Cook me some eggs"
Find the cow-latin:
>>> ' '.join(word[1:] + word[0] + 'oo' if word[0] in consonants else word + 'moo' for word in sentence.lower().split())
'ookcoo emoo omesoo eggsmoo'
sentence = input("Say a sentence: ").split()
vowels = 'aeiouAEIOU'
for i in sentence:
if i.isalpha() == True:
if i[0] in vowels:
print(i + "way")
new = i + "way"
sentence.replace(i, new)
else:
print(i[1:] + i[0] + "ay")
new = i[1:] + i[0] + "ay"
sentence.replace(i, new)
else:
print(i)
print(sentence)
I am trying to make a piglatin sentence converter, I have been able to make the converter print the correct values for the translation, but I cannot make the program change the actual values of the list, which I need it to do so that I can print the converted text like the original, in a string format like "I like rabbits" instead of a list like:
I
like
rabbits
I would like to know how I use the replace() function to change my list inside my for loop and if statements. If there is another way that is better that would be even better.
Thank You.
sentence.replace(i, new) function returns the new string - it doesn't do replacement in-place (on the original string).
You'd want to loop through indexes to easily modify the list being iterated over (you don't change your wheels whilst driving, do you?):
sentence = input("Say a sentence: ").split()
vowels = 'aeiouAEIOU'
for idx in range(len(sentence)):
to_replace = sentence[idx]
if to_replace.isalpha() == True:
if to_replace[0] in vowels:
print(to_replace + "way")
new = i + "way"
else:
print(to_replace[1:] + to_replace[0] + "ay")
new = to_replace[1:] + to_replace[0] + "ay"
sentence[idx] = new
else:
print(to_replace)
print(sentence)
You don't really need to call replace() (which is a string method, not list). You'd assign to sentence[idx] instead.
Your list doesn't have a .replace method but, the str's in the list do.
It looks as though you are wanting to modify your list while iterating through the items.
sentence = input("Say a sentence: ").split()
vowels = 'aeiouAEIOU'
for idx, word in enumerate(sentence):
if word.isalpha() == True:
if word[0] in vowels:
print(word + "way")
new = word + "way"
else:
print(word[1:] + word[0] + "ay")
new = word[1:] + word[0] + "ay"
sentence[idx] = new
else:
print(word)
print(sentence)
The enumerate builtin is especially useful when iterating and modifying items.