Piglatin Conversion Program - python-3.x

I am trying to create a program that can convert both from and English sentence into Piglatin and from Piglatin into English.
So far, the English to Piglatin portions are working fine, but I am having trouble converting from Piglatin to English.
def eng2Pig(sentence):
sentsplit = sentence.split()
for part in sentsplit:
print((part[1:] + part[0] + "ay"), end = " ")
def pig2Eng(sentence):
sentv1 = sentence.replace("ay", "")
sentsplit = sentv1.split()
for part in sentsplit:
print(part[-1] + part[:-1], end = " ")
def aySearch(sentence):
numwords = len(sentence.split())
numay = sentence.count("ay ")
if numwords == numay:
pig2Eng(sentence)
else:
eng2Pig(sentence)
x = input("Enter your sentence: ")
x = x + " "
aySearch(x)
I am having troubles converting English words that originally contain ay. For example, today converted to Piglatin would be odaytay. However, I am replacing ay with "" to remove the extra added ay.
Perhaps I need to count the number of ay(s) in a word, then based off of that, decide if I want to remove more than one ay.
Thanks -
Good luck

One problem is doing a replace ("ay", "") will change the word say int s, so it will corrupt your sentence. Here's a better solution.
def pig2Eng(sentence):
eng = ""
sentsplit = sentence.split()
for word in sentsplit:
eng += word[-3:-2] + word[:-3] + " "
return eng
print (pig2Eng("igpay atinlay siay tupidsay"))
Also note that is usually better programming form to return the result rather than printing it in the function.

Here is what I ended up doing - this worked well.
def eng2Pig(sentence):
pig = ""
sentsplit = sentence.split()
for part in sentsplit:
pig += (part[1:] + part[0] + "ay" + " ")
return pig
def pig2Eng(sentence):
eng = ""
sentsplit = sentence.split()
for part in sentsplit:
eng += (part[-3] + part[:-3] + " ")
return eng
def aySearch(sentence):
numwords = len(sentence.split())
numay = sentence.count("ay ")
if numwords == numay:
return pig2Eng(sentence)
else:
return eng2Pig(sentence)
def main():
x = input("Enter your sentence: ")
x = x + " "
print(aySearch(x))
main()

Related

Improving in function clarity and efficiency in python

I am very new in programming so I need help in "cleaning up my code" if the code is a mess if not then please recommend some better commands that accomplish the same purpose of any line or multiple lines.
Here is my program.
import random
def random_num():
lower_bound = input("what is your lower bound: ")
upper_bound = input("What is your upper bound: ")
trials = input("How many time would you like to try: ")
random_number = random.randint(int(lower_bound),
int(upper_bound))
user_input = input(
"What is the number that I am thinking in the range "
+ lower_bound + "-" + upper_bound + " (only " + trials + " tries): ")
ending = "Thanks For Playing"
continue_game = "That's it. Do you want to continue the game?
(Yes/No): "
count = 0
while True:
answer = int(user_input)
if count == int(trials) - 1:
lost = input("Sorry you have lost " + continue_game).lower()
if lost in ["yes"]:
random_num()
else:
return ending
else:
if answer == random_number:
win = input(continue_game).lower()
if win in ["yes"]:
random_num()
else:
return ending
elif answer >= random_number:
user_input = input("The number is smaller than that: ")
else:
user_input = input("The number is bigger than that: ")
count += 1
print(random_num())

moving between indexes in a list in python

In Python, I populate info from a file to a list and then print the first index in the list, now I want to print the next index from the list without multiple my code.
How can I promote the index i'm printing?
question = open("questions.txt", "r")
print(question.readlines()[0])
tanswer = open("answers.txt", "r")
correct_answer = float(tanswer.readlines()[0])
uanswer = float(input("Write the answer: "))
if correct_answer==uanswer:
print("Amazing " + str(correct_answer) + " is the correct answer")
else:
print("Wrong " + str(uanswer) + " is not correct, Try again please. ")
As far as I understood, you are trying to split the lines.
let's say
line = '1000 2000 3000'
line = line.split(' ')
then you will get line[0]
Try this I hope this helps.
Use zip:
with open("questions.txt") as ques, open("answers.txt") as ans:
for q, a in zip(ques, ans):
print(q)
uanswer = input("Write the answer: ")
if float(a) == float(uanswer):
print("Amazing " + str(a) + " is the correct answer")
else:
print("Wrong " + str(uanswer) + " is not correct, Try again please. ")

Caesar Cipher shift on new lines

I am having a problem with my code trying to do an advanced caesar cipher shift. I changed a certain letter to another, and then added a string to certain parts of a file before encoding, but am having problems doing the shifting now. This is my code:
import string
import sys
count = 1
cont_cipher = "Y"
#User inputs text
while cont_cipher == "Y":
if count == 1:
file = str(input("Enter input file:" ""))
k = str(input("Enter shift amount: "))
purpose = str(input("Encode (E) or Decode (D) ?: "))
#Steps to encode the message, replace words/letter then shift
if purpose == "E":
my_file = open(file, "r")
file_contents = my_file.read()
#change all "e"s to "zw"s
for letter in file_contents:
if letter == "e":
file_contents = file_contents.replace(letter, "zw")
#add "hokie" to beginning, middle, and end of each line
lines = file_contents.split('\n')
def middle_message(lines, position, word_to_insert):
lines = lines[:position] + word_to_insert + lines[position:]
return lines
new_lines = ["hokie" + middle_message(lines[x], len(lines[x])//2, "hokie") + "hokie" for x in range(len(lines))]
#math to do the actual encryption
def caesar(word, shifts):
word_list = list(new_lines)
result = []
s = 0
for c in word_list:
next_ord = ord(c) + s + 2
if next_ord > 122:
next_ord = 97
result.append(chr(next_ord))
s = (s + 1) % shifts
return "".join(result)
if __name__ == "__main__":
print(caesar(my_file, 5))
#close file and add to count
my_file.close()
count = count + 1
The error I am getting is:
TypeError: ord() expected a character, but string of length 58 found
I know that I need to split it into individual characters, but am not sure how to do this. I need to use the updated message and not the original file in this step...

Siimple Python. Not sure why my program is outputting this

I am making a program to take in a sentence, convert each word to pig latin, and then spit it back out as a sentence. I have no idea where I have messed up. I input a sentence and run it and it says
built-in method lower of str object at 0x03547D40
s = input("Input an English sentence: ")
s = s[:-1]
string = s.lower
vStr = ("a","e","i","o","u")
def findFirstVowel(word):
for index in range(len(word)):
if word[index] in vStr:
return index
return -1
def translateWord():
if(vowel == -1) or (vowel == 0):
end = (word + "ay")
else:
end = (word[vowel:] + word[:vowel]+ "ay")
def pigLatinTranslator(string):
for word in string:
vowel = findFirstVowel(word)
translateWord(vowel)
return
print (string)
You have used the lower method incorrectly.
You should use it like this string = s.lower().
The parentheses change everything. When you don't use it, Python returns an object.
Built-in function should always use ()
Here is the corrected version of the code which should work:
s = input("Input an English sentence: \n").strip()
string = s.lower() #lowercasing
vStr = ("a","e","i","o","u")
def findFirstVowel(word):
for idx,chr in enumerate(word):
if chr in vStr:
return idx
return -1
def translateWord(vowel, word):
if(vowel == -1) or (vowel == 0):
end = (word + "ay")
else:
end = (word[vowel:] + word[:vowel]+ "ay")
def pigLatinTranslator(string):
for word in string:
vowel = findFirstVowel(word)
translateWord(vowel,word)
return
print(string)

How do I make my python code so that only text can be entered?

import random
def diceRoll(number):
roll = random.randint(1,number)
print("Rolling a ",number," sided die.")
return roll
def newAccount(playername):
print("Greetings ", playername,"! We'll generate your charecter's attributes by rolling some die")
skillroll = 10 + (int(round((diceRoll(12)/diceRoll(4)))))
strengthroll = 10 + (int(round((diceRoll(12)/diceRoll(4)))))
print("You have ",skillroll," skillpoints and ",strengthroll," strength!")
class newplayer:
name = playername
skill = skillroll
strength = strengthroll
save(newplayer)
def save(newplayer):
"""Saves all details"""
file = open("accounts.txt","a")
file.write("CharacterName = '" + newplayer.name + "'\n")
file.write("Strength = " + str(newplayer.strength) + '\n')
file.write("Skill = " + str(newplayer.skill) + '\n')
file.write("\n")
print("Saved account")
def newPlayer():
try:
player1 = input("What is your 1st player's name? ")
newAccount(player1)
except:
print("Please only enter letters for your character name ")
newPlayer()
newPlayer()
print(" ")
player2 = input("What is your 2nd player's name? ")
newAccount(player2)
The part in bold is the part of the code I have attempted to alter to add some sort of error handling. Someone help me out here please, I know it's probably simple but I can't find an answer to this question anywhere.
Pythons RegEx would be a quite easy solution:
import re
if not re.match("[a-z]+$",inputString):
#your exception handling

Resources