Pig Latin Program in Python - python-3.x

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)))

Related

How to delete the vowel from a given string

How to delete the vowel from the given string?
letter = 'raeiou'
new_string = []
for i in letter:
new_string.append(i)
for j in new_string:
if j == 'a' or j == 'e' or j == 'i' or j == 'o' or j == 'u':
new_string.remove(j)
final = ''.join(new_string)
print('The string after removing the vowels is {}'.format(final))
expected output r but reo
When you do:
for j in new_string:
...
new_string.remove(...)
you are modifying a list while looping on it (see e.g. strange result when removing item from a list).
You could simply skip vowels when you create new_list in the first place:
for i in letter:
if not i in 'aeiou':
new_string.append(i)
final = ''.join(new_string)
Here is an alternative suggestion:
def func(s):
for c in 'aeiouAEIOU':
s = ''.join(s.split(c))
return s
You don't need two loops for this!
letter = 'raeiou'
new_string = letter
vowels = ('a', 'e', 'i', 'o', 'u')
for i in letter:
if i in vowels:
new_string = new_string.replace(i,"");
print('The string after removing the vowels is {}'.format(new_string))

converting phone letters to numbers and using while loop

I am currently writing function that takes in a string and converts that string (which is a phone number) into numbers only. In addition I am also using a while loop asking the user if they want to continue. My output is only showing me the first number or letter I type in, I want to know why. This is what I have so far:
def translate_num(convert):
answer=input('insert y to continue')
convert=input('Enter phone number here')
while answer=='y':
for word in convert:
phone_num=[]
if word == 'A' or word == 'B' or word == 'C':
phone_num.append('2')
elif word == 'D' or word == 'E' or word == 'F':
phone_num.append('3')
elif word == 'G' or word == 'H' or word == 'I':
phone_num.append('4')
elif word == 'J' or word == 'K' or word == 'L':
phone_num.append('5')
elif word == 'M' or word == 'N' or word == 'O':
phone_num.append('6')
elif word == 'P' or word == 'Q' or word == 'R' or word== 'S':
phone_num.append('7')
elif word == 'T' or word == 'U' or word == 'V':
phone_num.append('8')
elif word == 'W' or word == 'X' or word == 'Y' or word=='Z':
phone_num.append('9')
else:
phone_num.append(word)
print(phone_num)
answer=input('insert y to continue')
return
translate_num('555-361-FOOD')
you are re-initializing the phone_num with phone_num=[] value after going through each value in convert. Instead declare phone_num=[] once at the start of the function, also as pointed out by kabanus the return statement needs to be de-intended by a block. My implementation below seems to work (I have removed the redundant input statements since you are already calling the function, I have also added code to convert the number list back to a string :
def translate_num(convert):
#answer=input('insert y to continue')
#convert=input('Enter phone number here')
phone_num=[]
while True:
for word in convert:
if word == 'A' or word == 'B' or word == 'C':
phone_num.append('2')
elif word == 'D' or word == 'E' or word == 'F':
phone_num.append('3')
elif word == 'G' or word == 'H' or word == 'I':
phone_num.append('4')
elif word == 'J' or word == 'K' or word == 'L':
phone_num.append('5')
elif word == 'M' or word == 'N' or word == 'O':
phone_num.append('6')
elif word == 'P' or word == 'Q' or word == 'R' or word== 'S':
phone_num.append('7')
elif word == 'T' or word == 'U' or word == 'V':
phone_num.append('8')
elif word == 'W' or word == 'X' or word == 'Y' or word=='Z':
phone_num.append('9')
else:
phone_num.append(word)
#print(phone_num)
#answer=input('insert y to continue')
number=''
for item in phone_num:
number=number+str(item)
return (number)
print (translate_num('555-361-FOOD'))

Return value of function gets ignored

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.

How do I make my "Lingo" game in python 3.5 work?

The game is slightly different from the lingo, in the sense that any wordlength can be used. How can I make my program print a ? when the letter is in the word but not on the correct spot? and how do I make it print the actually letter if the letter is in the correct spot? e.g the word is "tank" and the user entered "town" it should print "t--?" I got everything working until the point where I have to make my code output characters other than "-"
(The words are in dutch, but that shouldnt make any difference)
import random
wordlist = ["hond", "haas", "neus", "peer","fruit", "laptop","raam","computer", "python", "hakan", "akkas", "mohammed", "amine", "school","informatica"]
word = random.choice(wordlist)
print("Your secret word has ", len(word), "letters")
while True:
guessword = input("Guess the word:")
if len(Guessword) != len(word): print("type a word with", len(word),"letters")
elif guessword == word: break
elif guessword != word:
if guessword != word: print("-" * len(word))
print("Congratulations, you guessed the word correctly!")
I also have to make the game tell you how many turns it took you to guess the word as well as implementing a score system based off time.
EDIT: Has to be as compact as possible
One way of doing it using enumerate:
import random
wordlist = ["hond", "haas", "neus", "peer","fruit", "laptop","raam","computer", "python", "hakan", "akkas", "mohammed", "amine", "school","informatica"]
# 'word' hardcoded for testing
word = "tank" #random.choice(wordlist)
print("Your secret word has ", len(word), "letters")
while True:
guessword = input("Guess the word:")
if len(guessword) != len(word): print("type a word with", len(word),"letters")
elif guessword == word: break
elif guessword != word:
for position, letter in enumerate(guessword):
if letter == word[position]:
print(letter, end="")
elif letter not in word:
print("-", end="")
else:
print("?", end="")
print("")
print("Congratulations, you guessed the word correctly!")
Testing:
$ python3.5 word_game.py
Your secret word has 4 letters
Guess the word:town
t--?
Guess the word:tans
tan-
Guess the word:tank
Congratulations, you guessed the word correctly!

Try/Exception flow control

Codes:
def get_wordlen():
wordfamily_lst = []
while True:
try:
word_len = int(input('\nPlease enter length of the word you wish to guess: '))
input_File = open('dic.txt', 'r').read().split()
for word in input_File:
if len(word) == word_len:
wordfamily_lst.append(word)
else:
print("Sorry, there's no word of that length")
continue
except ValueError:
print('Please enter a numeric value for word length')
continue
return word_len, wordfamily_lst
wordlen, wordfamilylst = get_wordlen()
print(wordlen,wordfamilylst)
How can i modify my "else" statement to safeguard against user input of word length that the txt. file does not contain. Right now, my codes will display the print statement for EVERY word that doesn't match with the user input of word length.
I'd like just one print statement and loop back to the top of the while loop.
Please give me some suggestions.
You could modify your try block as:
word_len = int(input('\nPlease enter length of the word you wish to guess: '))
input_File = open('dic.txt', 'r').read().split()
wordfamily_lst = []
for word in input_File:
if len(word) == word_len:
wordfamily_lst.append(word)
if not wordfamily_lst:
print("Sorry, there's no word of that length")
continue
The for word in input_File: will execute for all words in the file
appending the word to wordfamily_lst only if the lengths match.
Since we are now assigning wordfamily_lst = [] inside the while
block, the if not wordfamily_lst: will make sure the error is
printed only if the input word is not present in the file.
On a related note, it would be a good idea to move the code to read the file outside the while True: block, read all the words in the file into a list once and compare the user input with this new list.
To summarize, this is what I mean:
def get_wordlen():
input_file_words = open('dic.txt', 'r').read().split()
while True:
try:
word_len = int(input('\nPlease enter length of the word you wish to guess: '))
wordfamily_lst = []
for word in input_file_words:
if len(word) == word_len:
wordfamily_lst.append(word)
if not wordfamily_lst:
print("Sorry, there's no word of that length")
continue
except ValueError:
print('Please enter a numeric value for word length')
continue
return word_len, wordfamily_lst
wordlen, wordfamilylst = get_wordlen()
print(wordlen,wordfamilylst)

Resources