PygLatin game - Help making alphabet of the word go to end - python-3.x

I was trying to code this on codecademy.com , but due to some bug it it shows the lesson is completed. so I can't take a hint.
Break It Down
Now let's take what we've learned so far and write a Pig Latin translator.
Pig Latin is a language game, where you move the first letter of the word to the end and add "ay." So "Python" becomes "ythonpay." To write a Pig Latin translator in Python, here are the steps we'll need to take:
Ask the user to input a word in English.
Make sure the user entered a valid word.
Convert the word from English to Pig Latin.
Display the translation result.
word=raw.input("Please enter a word: ")
if word.isalpha():
print "Thanks the word is valid"
else
print "Please enter a valid word"
x =len(word)
for m in range [0,x]
word=word[1]+word[2]
so far I entered a word and checked if it is valid.
I was trying a loop but I failed .. but I haven't been taught the loop in codeacademy so I guess I have to achieve the pyglatin word without it.
I can't think of anything please help

word = raw_input ("give me a word: ")
if len(word) > 3 and word.isalpha():
print word.lower() + " Pyg Latin: " + word[1:] + word[0] + "ay"
else:
print "Try nex time, by!"
try this. It should give lohaAay for Aloha what is accordance with definition PygLatin.
In line 3 is clue :
word.lower is printing lower cases original word.
then we print " Pyg Latin: "
and now stright to target:
word[1:] - original word without first letter
word[0] - it is only first letter
"ay" that our tail.

a = raw_input('tape :')
if a.isalpha():
print a[1:] + a[0] + 'ay'

This should work. It ask user to input an English word. It validates the word and confirms with a Thank you message (if the input is not an English word, it will post a message for that). It will then translates it to PygLatin by moving the first alphabet to last and adding ay in the end.
pyg = 'ay'
word = raw_input ("Type a word: ").lower()
if word.isalpha():
print "Thanks, the word is valid"
first=word [0]
new_word= word +first +pyg
new_word= new_word[1:len(new_word)]
print "The pyg_latin translation is: ",new_word
else:
print "The word is not a valid english word"

Related

Python hangman script will not work if there are spaces

current code -
string = input("Enter word")
guessed= False
alphabet = 'abcdefghijklmnopqrstuvwxyz'
guesses=[]
while guessed== False:
char = input("Enter one letter :").lower()
if len(char) == 1:
if char not in alphabet:
print("Error you have not entered a letter")
elif char in guesses:
print("Letter has been guessed before")
elif char not in string:
print("Sorry this letter is not part of the word")
guesses.append(char)
elif char in string:
print("Well done")
guesses.append(char)
else:
print("Error")
else:
print("Only 1 character should be entered")
status= ''
if guessed == False:
for letter in string:
if letter in guesses:
status+=letter
if status==string:
print("Congratulations you have won")
guessed=True
else:
status+='_'
print(status)
If the word is "hello world" and the user guessed the words correctly the output below is displayed:
Well done
hello_world
Enter one letter :
The user is asked again to enter another letter even though the word is found. Im not sure on how to fix this.
I would add an extra condition for spaces like this
for letter in string:
if letter in guesses:
status+=letter
if status==string:
print("Congratulations you have won")
guessed=True
elif letter == ' ':
status += ' '
else:
status+='_'
This way the user sees that there are actually two words but does not have to enter a space explicitly.
Output
Enter one letter :h
Well done
h____ _____
Enter one letter :e
Well done
he___ _____
...
Enter one letter :d
Well done
Congratulations you have won
hello world
hello world contains a space, and yet space is not allowed as a guessed letter, so even if the user guesses all the right letters, the status will at best become hello_world, which is not equal to hello world, leaving the game unfinished.

How to get my Python program to pass an online grading system?

Question:
The hand is displayed.
The user may input a word or a single period (the string ".")
to indicate they're done playing
Invalid words are rejected, and a message is displayed asking
the user to choose another word until they enter a valid word or "."
When a valid word is entered, it uses up letters from the hand.
After every valid word: the score for that word is displayed,
the remaining letters in the hand are displayed, and the user
is asked to input another word.
The sum of the word scores is displayed when the hand finishes.
The hand finishes when there are no more unused letters or the user inputs a "."
hand: dictionary (string -> int)
wordList: list of lowercase strings
I am trying to write a code for my Python programming online course. However, I am getting an error :
ERROR: Failed to display hand correctly - be sure 'Current Hand' and the display of the hand are on the same line!
Here is my code :
def playHand(hand, wordList, n):
total = 0
while True:
print("\nCurrent Hand:",)
displayHand(hand)
entered = input('Enter word, or a "." to indicate that you are finished: ')
if entered == '.':
print ("Goodbye! Total score: " + str(total) +" points.")
break
if isValidWord(entered, hand, wordList) == False:
print ("Invalid word, please try again.")
else:
total += getWordScore(entered, n)
print (str(entered), "earned", getWordScore(entered,n), "points. Total:", str(total))
hand = updateHand(hand, entered)
if calculateHandlen(hand) == 0:
print ("\nRun out of letters. Total score: " + str(total) +" points.")
break
The answer is in your code already:
def displayHand(hand):
for letter in hand.keys():
for j in range(hand[letter]):
print(letter,end=" ") # print all on the same line
print() # print an empty line
Use end=" " in your print statement!!

Finding the position of two words that are the same in a list [duplicate]

This question already has answers here:
How to find all occurrences of an element in a list
(18 answers)
Closed 6 years ago.
So I created this code to ask a person to input a sentence.
After that they type a word in that sentence.
Then the code will output the position that word is in.
print("Type a sentence here")
sentence = input("")
sentence = sentence.split()
print("Now type a word in that sentence.")
word = input('')
if word in sentence:
print("I found",word,"in your sentence.")
else:
print("That word is not in your sentence.")
print(sentence.index(word))
The problem I am having is that if they put two of the same word in the sentence it only outputs the first one. Please can you help.
You could use the built-in enumerate to associate every word in your list sentence with its corresponding position. Then use a list comprehension to get every occurrence of the word in the list.
print([i for i, j in enumerate(sentence) if j == word])
Some further considerations would be that maybe you want to convert your sentence to lower case and remove punctuation before attempting to match your word, such that proper punctuation and capitalization will not trip up your matching. Further, you don't need the '' in input() in order for it to be valid - an empty input() without a prompt is fine.
This pb is solved by this script :
import re
print("Type a sentence here")
sentence = raw_input("")
print("Now type a word in that sentence.")
word = raw_input('')
words = re.sub("[^\w]", " ", sentence).split() # using re
position = 1
list_pos = []
for w in words :
if w == word:
print position
list_pos.append(position)
position += 1
if list_pos:
print("I found",word,"in your sentence.")
else:
print("That word is not in your sentence.")
print list_pos

Keeps on telling me that my code is not running all the way through What am I doing wrong?

print ('Welcome to the Pig Latin Translator!')
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = word[1:len(new_word)] + first + pyg
else:
print ('empty')
Doing this in code academy keeps on telling me that my code is not running all the way through on line 8
Normally you should get an error saying
Name 'new_word' is not defined
This is because you're using new_word before it even exists. Before starting the loop you can set new_word to word:
new_word = original.lower()
The other times it will use the last new_word.
You're using new_word before you defined it (in the initialization of new_word itself). You probably meant to use word:
new_word = word[1:len(word)] + first + pyg
Also, you'd probably want to print out new_word when you're done, otherwise the program won't have any output for a non-empty input.

stemming. i need to write a code for this

If you search for something in Google and use a word like "running", Google is smart enough to match "run" or "runs" as well. That's because search engines do what's called stemming before matching words.
In English, stemming involves removing common endings from words to produce a base word. It's hard to come up with a complete set of rules that work for all words, but this simplified set does a pretty good job:
If the word starts with a capital letter, output it without changes.
If the word ends in 's', 'ed', or 'ing' remove those letters, but if the resulting stemmed word is only 1 or 2 letters long (e.g. chopping the ing from sing), use the original word.
Your program should read one word of input and print out the corresponding stemmed word. For example:
Enter the word: states
state
Another example interaction with your program is:
Enter the word: rowed
row
Remember that capitalised words should not be stemmed:
Enter the word: James
James
and nor should words that become too short after stemming:
Enter the word: sing
sing
Here is the code:
word = input("Enter the word:")
x = 'ing'
y = 'ed'
z = 's'
first = word[:1]
last = word[-1:]
uppercase = first.upper
if word == uppercase:
print("")
elif (x in word) == True:
word = (word.replace('ing',''))
print(word)
elif (y in word) == True:
word = (word.replace('ed',''))
print(word)
elif (z in word) == True:
word = (word.replace('s',''))
print(word)
I see two options. Either this is a homework question, in which case - please try to solve your own homework.
The other case - you need this in real life. If so, please look at NLTK for Python natural language processing needs. In particular see http://nltk.org/api/nltk.stem.html
Install NLTK toolkit
and try this
from nltk.stem.porter import PorterStemmer
PorterStemmer.stem_word(word)

Resources