Pig Latin Function Sentence - python

THe rules for the pig latin sentences are:
1.for words beginning with consonants, all letters before the first vowel are moved to the end of the word, and is further appended by 'ay'
2.for words that begin with vowels, the word is appended by 'hay'
3.for words that do not contain a vowel, the first letter is moved to the end of the word and is appended with 'way'
4. all non characters (i.e., numbers, symbols) are ignored
The main part of the code executes an infinite loop that takes a string input from the user, invokes the pigLatin function and prints the result returned. The pigLatin function receives a list of words as its input and converts them to pig latin using the rules above. The main part exits when the user input "Quit this program" as the input sentence for conversion. Verify your program for all cases (including invalid inputs) and save your program.
I find it very difficult to solve rule 3. As I test the code, the out put isn't correct...
I struggle it for the whole night and couldn't sleep....Please help
Here is my code:
enter code here
sentence=input('input:')
VOWELS=['a','e','i','o','u']
CONSONANTS=['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
def pigLatin():
t=-1
for word in newsentence:
if word[0] in CONSONANTS:
if 'a'and'e'and'i'and'o'and'u' not in word[1:]:
print(word[1:]+word[0]+'way',end=' ')
for u in word:
t +=1
if u in VOWELS:
print (word[t:]+word[0:t]+'ay',end=' ')
break
elif word[0] in VOWELS:
print (word[0:]+'hay',end=' ')
else:
print (word[0:])
while sentence!=('Quit the program'):
newsentence=sentence.split()
pigLatin()
sentence=input('input:')

As Willem Van Onsem said, this line doesn't do what you think:
if 'a'and'e'and'i'and'o'and'u' not in word[1:]:
You should try experimenting with the interpreter.
'a' and 'e' not in "bar"
# returns True
This is happening because and is a logical operator which looks at what comes before and after it. It is doing this:
'a' and ('e' not in "bar")
which evaluates to
'a' and True
which evaluates to True, because non-empty strings get assigned the boolean True.
Here is something that will work. It uses the all function, which only returns True if all of its elements are true, and a feature of Python called comprehension which allows you to do tidy loops:
vowels = "aeiou"
all(char not in vowels for char in word)

Related

What is the difference between using range in the first program and not using it in the second program?

For an assignment, I needed to make a program that counts the vowels and consonants in a string using for i in range(0, len(str)):
I put this program together using what I learned, but I can't really wrap my head around why it works.
vowelCount = 0
consonantCount = 0
sentence = input("Enter your sentence: ")
for char in range(0, len(sentence)):
if sentence[char] in "aeiouAEIOU":
vowelCount += 1
if sentence[char] in "bcdfghjklmnpqrstvwxyBCDFGHJKLMNPQRSTVWXYZ":
consonantCount += 1
print("There are", vowelCount, "vowels")
print("There are", consonantCount, "consonants")
Why am I getting the range of the length of the sentence?
Here's an alternative program I wrote without the range.
vowelCount = 0
consonantCount = 0
sentence = input("Enter your sentence: ")
for i in sentence:
if i in "aeiouAEIOU":
vowelCount += 1
if i in "bcdfghjklmnpqrstvwxyBCDFGHJKLMNPQRSTVWXYZ":
consonantCount += 1
print("There are", vowelCount, "vowels")
print("There are", consonantCount, "consonants")
Why do I need to use sentence[char] in the range version? Why the brackets?
Your program is going through sentence one letter at a time. For each letter (retreived by sentence[char]) it checks whether it is in the list of vowels (if yes, increment vowelCount) or in the list of consonants (if yes, increment consonantCount).
The form a in b for strings a and b checks whether a is contained somewhere as exact substring in b. So if a is just a single letter, it checks whether b contains the letter a anywhere.
I suspect part of your confusion might arise because of the word "char." In the following code snippet, range(0, len(sentence)) generates numerical values. Thus, char is an index.
for char in range(0, len(sentence))
In other words, on the first iteration through the loop sentence[char] really looks something like sentence[0], or the first character in the sentence. If this character is in the string "aeiouAEIOU", the the boolean conditional in the loop returns TRUE
Note that if sentence[char] in "aeiouAEIOU" could be re-written like
if sentence[char] in set(['a','e','i','o','u','A','E','I','O','U'])
First: "aeiouAEIOU" is a string, which can also be seen as a List of characters in this context.
So ['a', 'e', 'i', 'o'....'U'] is equivalent to this string representation above.
Second: The in operator in python checks if the element on the left side is "in" the list on the right side. So for example
1 in [1,2,3] would return TRUE while 10 in [1,2,3] would return FALSE. Or for characters, 'o' in "Foobar" would return TRUE while 'c' in "Foobar" would return FALSE
The rest is just (pseudocode) IF ... THEN increase a number, so you basically loop through every character of a sentence and increase two variables if the character is in the list of vovels or in the list of consonants. After the loop is finished, you present the final counts.

Why is my function partially doing what it’s supposed to do?

So I’m trying to write a Python 3 function for a challenge that takes in a string, removes the vowels and returns it without the vowels. I wrote the below code but it seems to only take out the vowels partially while leaving some untouched.
def remove_vowels(string):
vowels = ['a','e','i','o','u']
newstring = ""
for letter in string:
if letter in vowels:
newstring = string.replace(letter,””)
else:
pass
return newstring
Your original python code with the following input
print(remove_vowels("The quick brown fox jumps over the lazy dog"))
returns "The quick brwn fx jumps ver the lazy dg"
The reason this only removes the "o" vowel is because your iterating through each vowel and updating your new string to the passed string minus the current vowel your on. So for example the first time through your for loop your "newstring" variable will be:
The quick brown fox jumps over the lzy dog
Then the next iteration your "newstring" variable will be set to
Th quick brown fox jumps ovr th lazy dog
And so on and so on. The reason my example only removes the o's is because there is no U to replace so the string replace method is never called leaving the "newstring" variables without o's.
To fix this you would just remove newstring completely and update the original string as this is it's own variable and this would technically work as is.
Although this can be compressed and refactored for better performance quite easily as you don't actually need to iterate through your string at all (nor do you need any type of new string as the passed string is it's own variable you are able to update) as pythons "String.replace" will replace ALL occurrences of the supplied substring and return the resulting string (if you don't supply a max amount of occurrences).
The following code below works
def remove_vowels(string):
vowels = 'aeiou'
for vowel in vowels: string = string.replace(vowel,'')
return string
print(remove_vowels("The quick brown fox jumps over the lazy dog"))
and returns "Th qck brwn fx jmps vr th lzy dg"
That's because you're setting newstring to a different string output on every iteration of the loop newstring = string.replace("")
You need to set newstring to the replaced string, and then run the next iteration of replace on newstring. Like this:
def remove_vowels(string):
vowels = ['a','e','i','o','u']
newstring = string
for letter in newstring:
if letter in vowels:
newstring = newstring.replace(letter , "")
return newstring
string = "stack overflow"
print("Original string = ", string)
print("String with vowels removed = ", remove_vowels(string))
Output:
Original string = stack overflow
String with vowels removed = stck vrflw
An alternative, short solution with a list comprehension:
def remove_vowels(string):
not_vowels = [letter for letter in string if letter not in 'aeiou']
return ''.join(not_vowels)
Make the following modifications to your code and it should work like a charm :)
def remove_vowels(string):
vowels = 'aeiou'
for letter in string:
if letter in vowels:
string = string.replace(letter," ")
else:
pass
return string
You are replacing a character in original string each time, but the original string never changes with current logic (except in the last loop).
try this inside IF condition
newstring = newstring.replace(letter,"")
(also initialize newstring = string before for loop)
Your code has several defects:
You are updating new_string with string, which does not change, and that results in only the last vowel in the list is deleted.
You do not need else: pass, it's ok with only the if clause. The else: pass is redundant.
You are cycling through the letters in string, which is not the fastest way to do things, also, it will create all kinds of weird errors if your code is changing string. You can knock outfor i in new_string:if i in vowels with for i in vowels
The vowels does not have to be a list if you are only iterating over it.Try a tuple or a str for better efficiency.
The overall fix:
def remove_vowels(string):
vowels = ('a','e','i','o','u')
newstring = string
for letter in vowels:
newstring = newstring.replace(letter,””)
return newstring
or:
def remove_vowels(string):
vowels = ('a','e','i','o','u')
for letter in vowels:
string = string.replace(letter,””)
return string

lower vs islower methods in if statements

def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "Q"
else:
translation = translation + "q"
else:
translation = translation + letter
return translation
print(translate(input("Enter phrase to translate: ")))
Hi, I'm new to Python and this is my first post here. I'm following a Python tutorial and I'm a little confused, this code executes fine, I'm just wondering why the following code works:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "Q"
If letter.lower converts each letter in sequence to a lower case, how could the next if statement return anything for letter.isupper?
If the phrase is "AaAa", wouldn't letter.lower() convert that to aaaa first, before checking the letter.isupper, meaning nothing could be isupper? Yet, it still works, and AaAa returns QqQq.
Also, is my formatting correct for posting the code on here? I just pasted it and clicked the bracket button.
Thanks
The lower method'1 only returns a lowercase letter (or the original string if there is no lowercase version); it does not change letter itself.
>>> letter = 'A'
>>> letter
'A'
>>> letter.lower()
'a'
>>> letter
'A"
lower() will return the lowercase character and you are checking if its a vowel. The letter itself is not changed e.g. A will remain as A
if letter.lower() in "aeiou":
The next line you are checking if its in upper case using isupper to add uppercase Q else lowercase q
if letter.isupper():
Don't get confused .I will make you very clear with your codes.
Please follow the steps below:-
1.your code:
if letter.lower() in "aeiou":
if letter.isupper():
translation=translation + "Q"
else:
translation=translation + "q"
In the first line of above code ,first of all you converted the letter(it can be in uppercase or lowercase) to lowercase.Then you checked that if it is in "aeiou" or not ,if the letter is there in "aeiou" then next if statement will get executed.
Now plese note that the letter you converted in the first line to lowercase remains in lowercase upto the execution of first line only,it means that the role of original case of the letter(case of letter while inputting it ) comes in account from second line,it also mean that the isupper() function do not change the case of the letter permanently.
3.According to your input "AaAa".First the letter 'A' will get converted into 'a' and as
'a' is there in "aeiou" control of program will go to second 'if' statement and there your letter is "A"(original case while input) so you get 'Q' as the result of 3rd statement and then this process continues for all letter("AaAa") and your output is "QqQq".
For more clarification of your doubt please refer to the code below and you will never stuck in this problem anymore:-
s="AaAa"
for letter in s:
print(letter.lower())
print(letter)
output:
a
A
a
a
a
A
a
a
ya you are correct with your formatting of code .You can post your question in a more better way but the way you have posted is also fine.

Acronym input text and reverse it

My task is to turn the input text to acronym and reverse it. The word should be more than 3 characters long and do not contain symbols such as ,!'?. For example if I have this sentence "That was quite easy?" the function should return EQT
I have done so far:
def acr(message):
words = message.split()
if check_length(words) is False:
return "the input long!"
else:
first_letters = []
for word in words:
first_letters.append(word[0])
result = "".join(first_letters)
return reverse(result.upper())
def check(word):
if len(word) > 3:
return False
def check_length(words):
if len(words) > 50:
return False
def rev(message):
reversed_message = message[::-1]
return reversed_message
I have problems with check function. How to correctly control the length of words and symbols?
A bit hacky in the sense that a comma is technically a special character (but you want the 'e' from easy), but this works perfectly for your example. Set up the "if" statement in the "for word in words" section.
def acronymize(message):
"""Turn the input text into the acronym and reverse it, if the text is not too long."""
words = message.split()
if check_message_length(words) is False:
return "Sorry, the input's just too long!"
else:
first_letters = []
for word in words:
if len(word) > 3 and word.isalnum()== True or (len(word) > 4 and ',' in word): #satisfies all conditions. Allows commas, but no other special characters.
first_letters.append(word[0])
result = "".join(first_letters)
return reverse(result.upper())
Basically the 'if' condition became if you have word of length > 3 characters AND the word is alphanumeric (then that satisfies all conditions) OTHERWISE (OR) if there is a comma next to the word (there will be len(word)+1 characters) and it will have a comma (,), that still satisfies the previous conditions, then populate the first_letters list.
Otherwise, ignore the word.
This way you don't even have to set up a check_word function.
This spits out the answer
'EQT'
A couple more examples from my code:
Input: Holy cow, does this really work??
Output: 'RTDH'
** Note that it did NOT include the word 'cow' because it did not have more than 3 letters.
Input: Holy cows, this DOES work!!
Output: 'DTCH'
** Note, now the term 'cows' gets counted because it has more than 3 letters.
You can similarly add any exceptions that you want (!, ? and .) using the 'or' format:
Ex: or (len(word) > 4 and '!' in word) or (len(word) > 4 and '?' in word)
The only assumption made for this is that the sentence is grammatically correct (as in, it won't have exclamation marks followed by commas).
It can be further cleaned up by making a list of the special characters that you would allow and passing that list into the or clause.
Hope that helps!
re.findall(r'(\w)\w{3,}', sentence) finds first letter of every at least four letter word
''.join(reversed(re.findall(r'(\w)\w{3,}', sentence))).upper()
re docs
If you want to ignore words preceding non-word characters, use (\w)\w{3,},?(?:$|\s) – this also allows a comma explicitly.
''.join(reversed(re.findall(r'(\w)\w{3,},?(?:$|\s)', sentence))).upper()

Python: Pig Latin Function

I'm stuck on a really hard question for my class in which I need to create a Pig Latin converter in Python for a given string.
Basically, here are the rules.
For any word that begins with one or more consonants (y is considered a consonant):
move the consonants to the end of the word and append the string 'ay'.
For all other words, append the string 'way' to the end.
The function also must be case deal with punctuation and case sensitivity, it is suggested that we create a separate function to find the initial vowel of any word and use it in the main function, which I kinda did, however, I'm having trouble implementing the Case and punctuation into my main formula and what to do if a word has no vowels (since "y" doesn't count as a vowel in our case, the word "my" doesn't have a vowel.
Here's my code so far.
def vowelfinder(astring):
vowels = ["A","E","I","O","U","a","e","i","o","u"]
alist = astring.split()
for i in alist:
for j in range(len(i)):
if i[j] in vowels:
print(j)
break
def igpay(astring):
vowelfinder(astring)
for i in alist
Any advice is helpful
# For any word that begins with one or more consonants (y is considered a consonant):
if "aeiouAEIOU".find(astring[0]) == -1:
# move the consonants to the end of the word and append the string 'ay'.
return astring[1:] + astring[0] + "ay"
# For all other words,
else:
# append the string 'way' to the end.
return astring + "way"
This is for a word. Splitting into words should be easy enough.
EDIT: brainfart.

Categories

Resources