Return value of function gets ignored - python-3.x

VOWELS = ['a', 'e', 'i', 'o', 'u']
BEGINNING = ["th", "st", "qu", "pl", "tr"]
def pig_latin2(word):
# word is a string to convert to pig-latin
string = word
string = string.lower()
# get first letter in string
test = string[0]
if test not in VOWELS:
# remove first letter from string skip index 0
string = string[1:] + string[0]
# add characters to string
string = string + "ay"
if test in VOWELS:
string = string + "hay"
print(string)
def pig_latin(word):
string = word
transfer_word = word
string.lower()
test = string[0] + string[1]
if test not in BEGINNING:
pig_latin2(transfer_word)
if test in BEGINNING:
string = string[2:] + string[0] + string[1] + "ay"
print(string)
When I un-comment the code below and replace print(string) with return string in above two functions, it only works for words in pig_latin(). As soon as word should be passed to pig_latin2() I get a value of None for all words and the programs crashes.
# def start_program():
# print("Would you like to convert words or sentence into pig latin?")
# answer = input("(y/n) >>>")
# print("Only have words with spaces, no punctuation marks!")
# word_list = ""
# if answer == "y":
# words = input("Provide words or sentence here: \n>>>")
# new_words = words.split()
# for word in new_words:
# word = pig_latin(word)
# word_list = word_list + " " + word
# print(word_list)
# elif answer == "n":
# print("Goodbye")
# quit()
# start_program()

You're not capturing the return value of the pig_latin2 function. So whatever that function does, you're discarding its output.
Fix this line in the pig_latin function:
if test not in BEGINNING:
string = pig_latin2(transfer_word) # <----------- forgot 'string =' here
When fixed thusly, it works for me. Having said that, there would still be a bunch of stuff to clean up.

Related

How do I print the output in one line as opposed to it creating a new line?

For some reason, I cannot seem to find where I have gone wrong with this program. It simply takes a file and reverses the text in the file, but for some reason all of separate sentences print on a new and I need them to print on the same line.
Here is my code for reference:
def read_file(filename):
try:
sentences = []
with open(filename, 'r') as infile:
sentence = ''
for line in infile.readlines():
if(line.strip())=='':continue
for word in line.split():
if word[-1] in ['.', '?', '!']:
sentence += word
sentences.append(sentence)
sentence = ''
else:
sentence += word + ' '
return sentences
except:
return None
def reverse_line(sentence):
stack = []
punctuation=sentence[-1]
sentence=sentence[:-1].lower()
words=sentence.split()
words[-1] = words[-1].title()
for word in words:
stack.append(word)
reversed_sentence = ''
while len(stack) != 0:
reversed_sentence += stack.pop() + ' '
return reversed_sentence.strip()+punctuation
def main():
filepath = input('File: ')
sentences = read_file(filepath)
if sentences is None:
print('Unable to read data from file: {}'.format(filepath))
return
for sentence in sentences:
reverse_sentence = reverse_line(sentence)
print(reverse_sentence)
main()
You can use the end keyword argument:
print(reverse_sentence, end=' ')
The default value for the end is \n, printing a new-line character at the end.
https://docs.python.org/3.3/library/functions.html#print

Pig Latin Program in Python

Write a program in Python 3 that converts a sentence typed in by the user to Pig Latin. Pig Latin has two rules:
If a word begins with a consonant all consonants before the first
vowel are moved to the end of the word and the letters "ay" are then
added to the end. e.g. "coin" becomes "oincay" and "flute" becomes
"uteflay". If a word begins with a vowel then "yay" is added to the
end. e.g."egg" becomes "eggyay" and "oak" becomes "oakyay".
My code works for individual words but does not work for sentence. I have tried entering:
wordList = word.lower().split(" ")
for word in wordList:
but it does not work.
#Pig Latin Program
import sys
VOWELS = ('a', 'e', 'i', 'o', 'u')
def pig_latin(word):
if (word[0] in VOWELS):
return (word +"yay")
else:
for letter in word:
if letter in VOWELS:
return (word[word.index(letter):] + word[:word.index(letter)] + "ay")
return word
word = ""
while True:
word = input("Type in the word or Exit to exit:")
if (word == "exit" or word == "Exit" or word == "EXIT"):
print("Goodbye")
sys.exit()
else:
print(pig_latin(word))
The input sentence: the rain in Spain
The output sentence: ethay ainray inyay ainSpay
So you could do something like this, it returns an iterable of all the pig-ed words and you can join them in the last step. You don't need that last return you have. My guess is the issue you saw was that you are returning in the first loop. you could track the return outside the loop and append to it in the loop and return that also.
import sys
VOWELS = ('a', 'e', 'i', 'o', 'u')
def pig_latin(word):
wordList = word.lower().split(" ")
for word in wordList:
if (word[0] in VOWELS):
yield (word +"yay")
else:
for letter in word:
if letter in VOWELS:
yield (word[word.index(letter):] + word[:word.index(letter)]+ "ay")
break
word = ""
while True:
word = input("Type in the word or Exit to exit:")
if (word == "exit" or word == "Exit" or word == "EXIT"):
print("Goodbye")
sys.exit()
else:
print(' '.join(pig_latin(word)))

My for loop is not iterating through all possible values

I'm trying to store substrings of letters in 's' that are in alphabetical order in a list
s = 'azcbobobegghakl'
string = ''
List = []
i = -1
for letter in s:
if letter == s[0]:
string += letter
elif letter >= s[i]:
string += letter
elif letter < s[i]:
List.append(string)
string = letter
i += 1
print(List)
My expected result:
['az', 'c', 'bo', 'bo', 'beggh', 'akl']
And my actual Output:
['az', 'c', 'bo', 'bo']
Firstly, your first if statement is incorrect. It should be if i == -1:. Because of this bug, you are ignoring the second a character in s.
Secondly, at the end of the string you don't add what's left of string into List.
As such, the following is what you want:
s = 'azcbobobegghakl'
string = ''
List = []
i = -1
for letter in s:
if i == -1:
string += letter
elif letter >= s[i]:
string += letter
elif letter < s[i]:
List.append(string)
string = letter
i += 1
List.append(string)
print(List)
An example is available here.

Longest word in a string using python programming

Hello guys I am still an armature in python was hoping if anyone could help with this solution.
Write a function called longest which will take a string of space separated words and will return the longest one.
For example:
longest("This is Fabulous") => "Fabulous"
longest("F") => "F"
class Test(unittest.TestCase):
def test_longest_word(self):
sentence = "This is Fabulous"
self.assertEqual('Fabulous', longest(sentence))
def test_one_word(self):
sentence = "This"
self.assertEqual("This", longest(sentence))
This is my solution so far;
def find_longest_word(word_list):
longest_word = ''
longest_size = 0
for word in word_list:
if (len(word) > longest_size)
longest_word = word
longest_size = len(word)
return longest_word
words = input('Please enter a few words')
word_list = words.split()
find_longest_word(word_list)
Unfortunately am getting this error when I try to test the code
"File "", line 6
if (len(word) > longest_size)
^
SyntaxError: invalid syntax
Any help please I will highly appreciate?
def find_longest_word(myText):
a = myText.split(' ')
return max(a, key=len)
text = "This is Fabulous"
print (find_longest_word(text)) #Fabulous
EDIT: The solution above works if you want one of the longest words and not all of them. For example if my text is "Hey ! How are you ?" It will return just "Hey". If you want it to return ["Hey", "How", "are", "you"]
Better use this.
def find_longest_word(myText):
a = myText.split(' ')
m = max(map(len,a))
return [x for x in a if len(x) == m]
print (find_longest_word("Hey ! How are you ?")) #['Hey', 'How', 'are', 'you']
See also, this question
You are missing the : at the end of the if statement
Use the updated code below, I fixed your indentation issues too.
def find_longest_word(word_list):
longest_word = ''
longest_size = 0
for word in word_list:
if (len(word) > longest_size):
longest_word = word
longest_size = len(word)
return longest_word
words = input('Please enter a few words')
word_list = words.split()
find_longest_word(word_list)
Code sample is incorrect. I get the following message if I try to output:
Error on line 15: print(longest_word("chair", "couch", "table"))
TypeError: longest_word() takes 1 positional argument but 3 were given
So the code looks like this:
def longest_word(word_list):
longest_word = ''
longest_size = 0
for word in word_list:
if (len(word) > longest_size):
longest_word = word
longest_size = len(word)
return longest_word
words = input("chair", "couch", "table")
word_list = words.split()
find_longest_word(word_list)
# longest word in a text
text = input("Enter your text")
#Create a list of strings by splitting the original string
split_txt = text.split(" ")
# create a dictionary as word:len(word)
text_dic = {i:len(i)for i in split_txt}
long_word = max([v for v in text_dic.values()])
for k,v in text_dic.items():
if long_word == v:
print(k)

Boolean won't change in Python

I am attempting to create a program in Python that asks a user to input a string (preferably in lower-case), and then convert that string into sentence case. However, a boolean I am using in order to check whether the next letter needs to be capitalised will not be set to False, despite the conditions required for the 'if' statement being met.
class SentenceCaseProgram(object):
def __init__(self, isPunctuation, isSpace, sentence, new_sentence):
self.isPunctuation = isPunctuation
self.sentence = sentence
self.new_sentence = new_sentence
self.isSpace = isSpace
self.count = 0
def Input(self):
self.sentence = str(input("Type in a sentence (with punctuation) entirely in lowercase. "))
def SentenceCase(self):
for letter in self.sentence:
print(self.isPunctuation)
if self.count == 0:
letter = letter.capitalize()
if letter is ' ':
self.isSpace = True
if (self.isPunctuation == True) and (letter in 'abcdefghijklmnopqrstuvwxyz'):
letter = letter.capitalize()
self.isPunctuation = letter is '.' or '!' or '?' or ')'
if letter is 'i' and self.isSpace is True:
letter = letter.capitalize()
self.isSpace = False
self.count += 1
if letter == '.' or '!' or '?' or ')':
self.isPunctuation = True
else:
self.isPunctuation = False
self.new_sentence += letter
def Print(self):
print("Your sentence in sentence case is '%s'" % self.new_sentence)
def Main(self):
self.__init__(False, False, "", "")
self.Input()
self.SentenceCase()
self.Print()
app = SentenceCaseProgram(False, False, "", "")
app.Main()
When I run the program, the program asks for an input, and then capitalizes every single letter in the sentence, and the self.isPunctuation boolean will constantly be set to True, apart from with the first loop.
don't use is to compare strings, use ==
letter is '.' or '!' or '?' or ')' should be
letter == '.' or letter == '!' or letter == '?' or letter == ')'
OR
letter in '.!?)'

Resources