Pig Latin Code in Python - python

I am a beginner in Python, and I want my code to move the first one or two consonants to the end of the word and add -ay. I have gotten my code to do this but it doesn't work for sentences. I need help with the list. Also, the returned, translated sentence needs to start with an uppercase letter and end with a period, just like the input sentence but I have no clue where to start with this! Here is my code so far:
pyg = 'ay'
original = raw_input('Enter a sentence:')
word = original.lower()
word_list = word.split
count = 0
for word in word_list:
if word[1] == "a" or word[1] == "e" or word[1] == "i" or word[1] == "u" or
word[1] == "o" or word[1] == "y":
first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_word)]
print new_word
else:
if word[1] != "a" or word[1] != "e" or word[1] != "i" or word[1] != "u" or
word[1] != "o" or word[1] != "y":
first = word[0]
second = word[1]
second_word = word + first + second + pyg
second_word = second_word[2:len(second_word)]
print second_word

I have tried creating the code using .format() , being beginner myself , I hope you find this code easy & helpful.
def pig_latin(text):
say = ""
words = text.split()
for word in words:
say += "{}{}{} ".format(word[1:], word[0], "ay")
return say
print(pig_latin("hello how are you"))
ellohay owhay reaay ouyay

This is a slightly generalized version of what you say you want. The difference is that the code below doesn't look at the first one or two letters: it shifts all initial consonants to the end, so that string becomes ingstray. Your problem statement says that should be ringstay, but that doesn't accord with the Pig Latin I learnt as a child. I've done this partly because I think your specification is incomplete, and partly because it makes the code simpler, and that makes it easier to understand. You can always amend the code if ringstay is really what you want. (Hint: put a counter in the while loop.) There is also a bug in this code, though you would be unlikely to find it: if an input word contains no vowels at all, for example cwm (a kind of Welsh fiddle) then the while loop will never terminate. (Hint: same solution.)
I haven't added the refinement, also dimly remembered from my childhood, that an original word that begins with a vowel gets the suffix way not ay, so I am good comes out as Iway amway oodgay not Iay amay oodgay.
The Pythonic way to do a membership test is to use in, not a long string of if x == 'a' or x == 'b' or x == 'c' tests.
Providing an initial capital and a final fullstop requires you to split the problem into two: (1) transform the words, and (2) punctuate the sentence. You can't do that if you print the transformed words out as you go along. So the code below assembles the words into a result list and then strings the list of words into a final sentence for punctuation.
pyg = 'ay'
original = raw_input('Enter a sentence:')
word_list = original.lower().split()
result = []
for word in word_list:
while word[0] not in "aeiouy":
word = word[1:] + word[0]
word += pyg
result.append(word)
final_sentence = " ".join(result)
print final_sentence[0].upper() + final_sentence[1:] + "."
Personally I consider it not good style to store a sentence in a variable called word, especially if the code actually stores a word in that same variable at a later point. So I've amended that too.
Edit since it appears my hint wasn't explicit enough:
To limit the number of consonants that get shifted to the end, you need to count them:
for word in word_list:
consonants = 0
while word[0] not in "aeiouy" and consonants < 2:
word = word[1:] + word[0]
consonants += 1
word += pyg
result.append(word)
To make sure the program isn't put into an infinite loop by a word with no consonants:
while word[0] not in "aeiouy" and consonants < len(word):

Related

How to replace the specified dash with the letter

I wish to write a hangman program and in order to do so, I have to replace the hash ('-') letter(s) with the user's guessed letter (guess). But when I run the code, it replaces all the hashes with the user's guess letter.
The code seems okay but I don't get the desired result.
words is a list of words I have written before the function.
def word_guess():
random.shuffle(words)
word = words[0]
words.pop(0)
print(word)
l_count = 0
for letter in word:
l_count += 1
# the hidden words are shown a '-'
blank = '-' * l_count
print(blank)
guess = input("please guess a letter ")
if guess in word:
# a list of the position of all the specified letters in the word
a = [i for i, letter in enumerate(word) if letter == guess]
for num in a:
blank_reformed = blank.replace(blank[num], guess)
print(blank_reformed)
word_guess()
e.g: when the word is 'funny', and guess is 'n', the output is 'nnnnn'.
How should I replace the desired hash string with guess letter?
it replaces all the hashes
This is exactly what blank.replace is supposed to do, though.
What you should do is replace that single character of the string. Since strings are immutable, you can't really do this. However, lists of strings are mutable, so you could do blank = ['-'] * l_count, which would be a list of dashes, and then modify blank[num]:
for num in a:
blank[num] = guess
print(blank)
A couple things to note:
inefficient/un-pythonic pop operation (see this)
l_count is just len(word)
un-pythonic, unreadable replacement
Instead, here's a better implementation:
def word_guess() -> str:
random.shuffle(words)
word = words.pop()
guess = input()
out = ''
for char in word:
if char == guess:
out.append(char)
else:
out.append('-')
return out
If you don't plan to use the locations of the correct guess later on, then you can simplify the last section of code:
word = 'hangman'
blank = '-------'
guess = 'a'
if guess in word:
blank_reformed = ''.join(guess if word[i] == guess else blank[i] for i in range(len(word)))
blank_reformed
'-a---a-'
(You still have some work to do make the overall game work...)

Converting a sentence into Pig Latin

I'm fairly new to Python and one of the practice projects I'm trying to do is converting sentences into pig latin. The original project was just converting words into pig latin, but I want to expand this into converting sentences.
Here's the code I have so far:
import sys
print("Pig Latin Maker")
VOWELS = 'aeiouy'
while True:
word = input ("Write a Word: ")
if word[0] in VOWELS:
pig_Latin = word + 'way'
else:
pig_Latin = word[1:] + word[0] + 'ay'
print ()
print ("{}".format(pig_Latin), file=sys.stderr)
end = input ("\n\n Press N\n")
if end.lower() == "n":
sys.exit()
The plan is to modify this so it splits all the words in the input sentence, converts each word to pig latin, and then spits it back out as one sentence but I'm not really sure how to do that.
I'm using Python 3.8. Any help is appreciated! Thank you.
You could split the sentence by the space character into separate strings each containing a word. You can then apply your current algorithm to every single word in that sentence. str has a method split which returns a list.
To get the words in a list, use listofwords = input('Write your sentence: ').split().
Then, you can combine the list of pig-latin words doing print(' '.join(listofpiglatin)).
import sys
print("Pig Latin Maker")
VOWELS = 'aeiouy'
while True:
listofwords = input ("Write a Sentence: ").split() # splits by spaces
listofpiglatin = []
for word in listofwords:
if word[0] in VOWELS:
pig_Latin = word + 'way'
else:
pig_Latin = word[1:] + word[0] + 'ay'
listofpiglatin.append(pig_Latin) # adds your new pig-latin word to our list
print()
print(' '.join(listofpiglatin)) # spits the words back as a sentence
end = input ("\n\n Press n")
if end.lower() == "n":
sys.exit()
I hope that this helps you learn!
Put your algorithm into a function:
def makePigLatin(word):
<your code here>
return latinWord
As other users mentioned, split the input and assign to a list:
words = input('blah').split()
Then apply your function to each word in the list:
translatedWords = map(makePigLatin, words)
Print them back out by joining them together:
print(' '.join(translatedWords))

Filter words in a sentence that begin with a certain range of letters

My task is to print all words in a sentence whose first letter is within a range of letters, for example: h-z.
This is my code so far, however it still prints words which begin with "g" and does not print the last word.
famous_quote = input("Enter a one sentence quote: ").lower()
word = ""
for ltr in famous_quote:
if ltr.isalpha() == True:
word = word + ltr
else:
if word > "g":
print(word)
word = ""
else:
word = ""
I'm only allowed to use ASCII comparisons, I've tried to compare the ASCII values but I don't know how to go about it in this context.
Sample input:
Wheresoever you go, go with all your heart
Sample output:
WHERESOEVER
YOU
WITH
YOUR
HEART
Algorithm I've come up with:
- split the words by building a placeholder variable: word
- Loop each character in the input string
- check if character is a letter
- add a letter to word each loop until a non-alpha char is encountered
- if character is alpha
- add character to word
- non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to else
- else
- check if word is greater than "g" alphabetically
- print word
- set word = empty string
- or else
- set word = empty string and build the next word
- Hint: use .lower()
You can define a neat little generator to split your sentence into words and compare the first letter of each.
def filter_words(sentence, lo, hi):
lo, hi = map(str.upper, (lo, hi))
words = sentence.upper().split()
for word in words:
if lo <= word[0] <= hi:
yield word
sentence = 'Wheresoever you go, go with all your heart'
print(*filter_words(sentence, 'h', 'z'), sep='\n')
WHERESOEVER
YOU
WITH
YOUR
HEART
This is how I approached this problem. It gave me a hard time since I am a beginer. But it seems to work fine.
quote = "quote goes here"
word = ""
for letter in quote:
if letter.isalpha():
word += letter
else:
if word > "":
print(word.upper())
word = ""
else:
word = ""
print(word.upper())
I added the space to the user_input and also used the word > 'h'. Below is how it looks:
user_input = input('Enter a phrase: ').lower()
user_input += ' '
word = ''
for char in user_input:
if char.isalpha():
word += char
else:
if word > 'h':
print(word.upper())
word = ''
else:
word = ''
This code worked for me...
The task is: Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-z
I was making the mistake of using word > "g" before, which needs to be replaced by word > "h".
Also, you need to add the last print command in order to print the last word in case the phrase does not end with a punctuation (as in the given example)
phrase = input ("Please enter a phrase: ").lower()
word = ""
for letter in phrase:
if letter.isalpha():
word += letter
else:
if(word > "h" ):
print(word)
word = ""
else:
word = ""
if word.lower() > 'h':
print(word)
Just one comment on the exercise, as a programming exercise this approach is fine but you would never do it this way in practice.
The two issues you've highlighted is that you are comparing the whole word instead of just the first character.
Simply change:
if word > "g":
To:
if word and word[0] > "g":
And if the quote doesn't finish with a punctuation you will miss the last word off, just add after the loop:
if word:
print(word)
You may note the output is all uppercase, so .lower() the whole quotation may be an issue, alternatively you can just .lower() the comparison, e.g.:
famous_quote = input("Enter a one sentence quote: ")
...
if word and word[0].lower() > "g":
Note: You can simplify your else: condition:
else:
if word and word[0] > "g":
print(word)
word = ""
You stated that you are not allowed to use the split() method. I am not sure what you can use, so here's a solution (not the optimal one).
famous_quote = input("Enter a one sentence quote:") + ' '
current_word = None
for c in famous_quote:
if ('a' <= c <= 'z') or ('A' <= c <= 'Z'):
if current_word is None:
current_word = c # start a new word
else:
current_word += c # append a new letter to current word
else:
if current_word is not None:
f = current_word[0] # first letter
if ('h' <= f <= 'z') or ('H' <= f <= 'Z'):
print(current_word)
current_word = None
Here is a sample run of the program. It preserves lowercase and uppercase. It also splits words on any non-ASCII character.
Enter a one sentence quote: Whereever you go, there you are!!!
Whereever
you
there
you
Note: Since printing is done when a non-ASCII character is encountered, a non-ASCII character is appended at the end of famous_quote.
Assuming that the famous quote contains only spaces as word separator, this should do the job:
words = input("Enter a one sentence quote: ").lower().split()
for word in words:
if word[0] > 'g':
print("{w} ".format(w = word))
split() transforms a string into a list (array). It takes, by default, the space character as parameter (hence I did not give the argument) and returns the list of words.
print() can be used in a lot of ways, due to python's history with this function.
You can .join() the list (getting a string as result) and print it:
print(" ".join(words))
you can also print with concatenations (considered ugly):
print(word+" ")
or you can use formatted printing, which I do use a lot for readibility:
print("{w} ".format(w = word))
interprets "{w}" and replaces it with word wherever "{w}" appears.
Print formatting is rather CPU consuming (but it is still really fast). Usually any print operation slows your application, you want to minimize making outputs if you are making CPU intensive apps in your future (here I don't do that because CPU is not the main concern).
1. Split the words by building a placeholder variable: word
Loop each character in the input string
and check if character is a letter. Then add letter to the variable "word". Loop until a non-alpha char is encountered.
2. If character is alpha or (alphabet)
Add character to word.
Non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to the "else" part.
input_quote = input("Enter a 1 sentence quote, non - alpha seperate words: ")
word = ""
for character in input_quote:
if character.isalpha():
word += character
3. Else
Check if word is greater than "g" alphabetically. Print word and set "word = empty" string.
else:
if word and word[0].lower() >= "h":
print("\n", word.upper())
word = ""
4. Or else
Set word = empty string and build the next word.
else:
word = ""
if word.lower() >= "h":
print("\n", word.upper())
The last "if" is explicitly coded to print the last word if it doesn't end with a non-alpha character like a space or punctuation.
I did this exact same problem. The issue most people are having (and no one seemed to point out) is when you encounter double punctuations or a punctuation followed by a space.
This is the code I used.
phrase = input("Please enter a famous quote: ")
word = ""
for letter in phrase:
if letter.isalpha() is True:
word += letter
elif len(word) < 1: <--- [This is what accounts for double punctuations]
word = ""
elif word[0].lower() >= "g":
print(word)
word = ""
else:
word = ""
print(word) <--- [accounts for last word if not punctuated]
Variable "word" already contains your last word of the phrase but since it does not fulfil the condition to enter the loop it does not gets printed. So you can check the below solution.
phrase = input("Enter a phrase after this: ")
word = ""
for char in phrase:
if char.isalpha():
word += char
else:
if word != "":
if word[0].lower() >= "h":
print(word.upper())
word = ""
else:
word = ""
if word[0].lower() >= "h":
print(word.upper())
This code works for me:
phrase=input("Enter a one sentence quote,non-alpha separate words: ")
word=""
for character in phrase:
if character.isalpha():
word+=character
else:
if word.lower()>="h".lower():
print(word.upper())
word="" -----this code defines the end of a word
else:
word=""
print(word.upper()) ------this will print the last word
I would use regular expressions and list compreshension as shown in the function below.
def words_fromH2Z():
text = input('Enter a quote you love : ')
return [word for word in re.findall('\w+', text) if not word[0] in list('aAbBcCdDeEfFgG')]
When I test the function by putting in the input "I always Visit stack Overflow for Help", I get:
words_fromH2Z()
Enter a quote you love : I always Visit stack Overflow for Help
['I', 'Visit', 'stack', 'Overflow', 'Help']
This worked well for me. I had to add the last two lines of code because without them, it wasn't printing the last word, even if it began with a letter between h and z.
word = ""
quote = input("Enter your quote")
for char in quote:
if char.isalpha():
word += char
elif word[0:1].lower() > "g":
print(word.upper())
word = ""
else:
word = ""
if word[0:1].lower() > "g":
print(word.upper())
famous_quote = input("Enter a one sentence quote:")
current_word = None
for c in famous_quote:
if c.isalpha():
if (c >= 'a') or (c >= 'A'):
if current_word is None:
current_word = c
else:
current_word += c
else:
if current_word is not None:
f = current_word[0]
if ('h' <= f <= 'z') or ('H' <= f <= 'Z'):
print (current_word.upper())
current_word = None
if famous_quote[-1].isalpha():
print (current_word.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.

Why do I get a "string index out of range" error with letter variable above while word: statement but not below?

Below is some code from a game I am creating which scrambles the letters of a random word for a player to guess. I was wondering why when I put my letter variable (which assigns a random letter from one of the words in my word bank to the variable letter) above my while word: statement there is a string index error but if I put the same variable in the while word: statement there is no error.
I know that in the string koala, for example, k is 0 and a is 4. Why would that change within the while statement? Or is there something else going on?
This works:
while word:
letter = random.randrange(len(word))
scrambled_word += word[letter]
word = word[:letter] + word[(letter+1):]
This does not work:
scrambled_word = ''
letter = random.randrange(len(word))
while word:
scrambled_word += word[letter]
word = word[:letter] + word[(letter+1):]
Why?
With each iteration of
while word:
scrambled_word += word[letter]
word = word[:letter] + word[(letter+1):]
word is shortened by one letter:
>>> "koala"[:3]
'koa'
>>> "koala"[4:]
'a'
so eventually word[letter] will try to access a letter that's no longer there.
If you want to scramble a word, there's a built-in function for that, though:
>>> word = "koala"
>>> l = list(word)
>>> random.shuffle(l)
>>> word = "".join(l)
>>> word
'oklaa'
(taking a detour via a list object because strings themselves are immutable and can't be shuffled directly).
I'm not a python programmer, but this is probably wrong:
word = word[:letter] + word[(letter+1):]
You need to check if the letter is the last one, otherwise word[(letter+1):] is out of bound.

Categories

Resources