Inheritance answer overlap - python

I have to make a program that converts a string to pig latin and include an constructor + example of the program. I then have to make a subclass based on it with a overwritten method to add a few new rules.
In the original class file I have the constructor:
pig = pigLatin_Class("First test")
print(pig)
pig.sentence = "Changing it up"
print(pig)
Which works correctly, however in my new subclass:
gib = gibberish_class("test")
print(gib)
Which also works correctly but prints out the answers from the super class as well, even though they're outside of the class definition.
I'm using:
import assignment_a3_1 as a3_1
class gibberish_class(a3_1.pigLatin_Class):
as my inheritance.
Any solutions?
EDIT:
In regards to the naming conventions, I'm just using what we were told to use, also I've only been coding for a month or two at most, doing a uni course, be gentle! :D
Super:
class pigLatin_Class(object):
vowels = ["a","e","i","o","u","A","E","I","O","U"]
def __init__(self, initialSentence):
self.__sentence = initialSentence
self.sentencePig = []
self.pLatin_converter(self.__sentence)
def pLatin_converter(self, sentence):
wordList = sentence.split(" ")
for word in wordList:
isVowel = False
wList = list(word)
for character in word: #vowel checks
if(character in pigLatin_Class.vowels):
isVowel = True
break
if(isVowel == False): #finishing if no vowels
wList.append(wList.pop(0))
word = ''.join(wList) + "way "
self.sentencePig.append(word)
if(''.join(wList) == word): #Stops it from iterating through again if it contains no vowels
if(wList[0] in pigLatin_Class.vowels):
word = ''.join(wList) + "hay "
self.sentencePig.append(word)
elif(wList[0] not in pigLatin_Class.vowels): #contains vowels but not first
for i in range(len(wList)):
if(wList[i] in pigLatin_Class.vowels):
wList = wList[i:] + wList[:i]
word = ''.join(wList) + "ay "
self.sentencePig.append(word)
break
def __str__(self):
string = ("\n The translation of '" + self.__sentence + "' is: " + ''.join(self.sentencePig))
return string
#property
def sentence(self):
return self.__sentence
#sentence.setter
def sentence(self, value):
self.__sentence = value
self.sentencePig = []
self.pLatin_converter(self.__sentence)
pig = pigLatin_Class("First test")
print(pig)
pig.sentence = "Changing it up"
print(pig)
Subclass:
import assignment_a3_1 as a3_1
class gibberish_class(a3_1.pigLatin_Class):
symb = ["0","1","2","3","4","5","6","7","8","9",",",".","/",";","#","[","]","=","-","(",")","*","&","^","%","$","£","_","+","{","}","~","<","#",":","?",">","<","|"]
vowels = a3_1.pigLatin_Class.vowels
def pLatin_converter(self, sentence):
wordList = sentence.split(" ")
for word in wordList:
suffix = 0
isVowel = False
wList = list(word)
for character in word: #vowel checks
if(character in gibberish_class.vowels):
isVowel = True
break
if(isVowel == False): #finishing if no vowels
wList.append(wList.pop(0))
suffix = 1
if(''.join(wList) == word): #Stops it from iterating through again if it contains no vowels
if(wList[0] in gibberish_class.vowels):
suffix = 2
elif(wList[0] not in gibberish_class.vowels): #contains vowels but not first
for i in range(len(wList)):
if(wList[i] in gibberish_class.vowels):
wList = wList[i:] + wList[:i]
suffix = 3
break
for character in wList:
#print(character)
if(character in gibberish_class.symb):
wList.append(character)
if(suffix == 1):
word = ''.join(wList) + "way "
elif(suffix == 2):
word = ''.join(wList) + "hay "
elif(suffix == 3):
word = ''.join(wList) + "ay "
self.sentencePig.append(word)
gib = gibberish_class("test")
gib.pLatin_converter
print(gib)
EDIT TWO:
The another question was very helpful in stopping the main method, however the str method is still called in the first question, just printing an empty string, said if statement just causes the program to throw errors if used in the str method. How would I solve that?

Here's a skeleton of how a typical program like yours could look.
class PigLatin(object):
def __init__(self, text):
...
# Add helper methods to taste.
def splitIntoWords(self):
return ... # re.split would help here.
def mangle(self):
# Do your conversion, put it into result
...
return result
class Gibberish(PigLatin):
# No __init__ since you inherit it.
def mangle(self):
# This method replaces, aka overrides, mangle() of PigLatin.
# You can use other methods, e.g. self.splitIntoWords().
...
return result
if __name__ == '__main__':
text = 'Hello world!'
print 'Do you know what "%s" would be in Pig Latin?' % text
print 'It is %s' % PigLatin(text).mangle()
print 'And now some Gibberish: %s' Gibberish(text).mangle
Hope this helps.

Related

Maintaining first-letter capitalization in Python pig latin translator

I have a pig latin translator program (yes, I've searched and reviewed several posts) but cannot figure out one part regarding applying capitalization.
My thinking is once I have the final 'pigged word', if the first letter of the original input was uppercase, do the same for the translated/pigged word using the title() or capitalize() function (like Pig_Latin Captitalization).
I'm sure this overall solution could be improved but I'm really only seeking guidance on the capitalization piece. (Though all constructive criticism is always welcome!)
# If first letter was capitalized, maintain that in 'pigged' word
# Example: "Shark" to "Arkshay"
# Convert any other caps to lower
# Example: "ShaRK" still to "Arkshay"
if not first_one.islower():
pigged_input = pigged_input.title()
return pigged_input
That snippet is contained in the full code:
def pig_latin_translator(user_input):
""" Translator function """
vowels = "aieou"
special_two = ("qu")
first_one = user_input[0]
first_two = user_input[0:2]
pigged_input = ''
# Input begins with vowel: keep input and add "yay"
if first_one in vowels:
pigged_input = user_input.lower()
pigged_input += "yay"
return pigged_input
else:
pigged_input = user_input.lower()
# Input does not begin with vowel: find position of first vowel
for letter in user_input:
if letter in vowels:
index_value = user_input.index(letter)
break
# Special two-letter cases: move both letters to end and add "ay"
# Example: "quarter" to "arterquay"
if first_two in special_two:
pigged_input = user_input[2:] + user_input[:2] + "ay"
return pigged_input
# Regular pig latin: move indexed letter to end and add "ay"
else:
pigged_input = user_input[index_value:] + user_input[:index_value] + "ay"
return pigged_input
# If first letter was capitalized, maintain that in 'pigged' word
# Example: "Shark" to "Arkshay"
# Convert any other caps to lower
# Example: "ShaRK" still to "Arkshay"
if not first_one.islower():
pigged_input = pigged_input.title()
return pigged_input
def error_check_and_print(x):
""" Error checking function
If zero-length or contains non-alpha characters, print error message
Otherwise print result from translator function
"""
if len(x) == 0:
print("Error: Not anything!")
elif not x.isalpha():
print("Error: Not alpha only!")
else:
return print(pig_latin_translator(x))
pigged_Shark = error_check_and_print("Shark")
# returns "arkShay" but want "Arkshay"
You return the word arkShay before captalized ...Please return pigged_input only at function end.
I have modified your code
def pig_latin_translator(user_input):
""" Translator function """
vowels = "aieou"
special_two = ("qu")
first_one = user_input[0]
first_two = user_input[0:2]
pigged_input = ''
# Input begins with vowel: keep input and add "yay"
if first_one in vowels:
pigged_input = user_input.lower()
pigged_input += "yay"
else:
pigged_input = user_input.lower()
# Input does not begin with vowel: find position of first vowel
for letter in user_input:
if letter in vowels:
index_value = user_input.index(letter)
break
# Special two-letter cases: move both letters to end and add "ay"
# Example: "quarter" to "arterquay"
if first_two in special_two:
pigged_input = user_input[2:] + user_input[:2] + "ay"
# return pigged_input
# Regular pig latin: move indexed letter to end and add "ay"
else:
pigged_input = user_input[index_value:] + user_input[:index_value] + "ay"
# return pigged_input
# If first letter was capitalized, maintain that in 'pigged' word
# Example: "Shark" to "Arkshay"
# Convert any other caps to lower
# Example: "ShaRK" still to "Arkshay"
if not first_one.islower():
pigged_input = pigged_input.title()
return pigged_input
def error_check_and_print(x):
""" Error checking function
If zero-length or contains non-alpha characters, print error message
Otherwise print result from translator function
"""
if len(x) == 0:
print("Error: Not anything!")
elif not x.isalpha():
print("Error: Not alpha only!")
else:
return print(pig_latin_translator(x))
pigged_Shark = error_check_and_print("Shark")

Python | Returns none when doing a while loop

# Let's put it all together. Write code for the function process_madlib, which takes in
# a string "madlib" and returns the string "processed", where each instance of
**# "NOUN" is replaced with a random noun and each instance of "VERB" is
# replaced with a random verb. You're free to change what the random functions
**# return as verbs or nouns for your own fun, but for submissions keep the code the way it is!****
from random import randint
def random_verb():
random_num = randint(0, 1)
if random_num == 0:
return "run"
else:
return "kayak"
def random_noun():
random_num = randint(0,1)
if random_num == 0:
return "sofa"
else:
return "llama"
def word_transformer(word):
if word == "NOUN":
return random_noun()
elif word == "VERB":
return random_verb()
else:
return word[0]
def process_madlib(text):
proc =""
lenght = len("NOUN")
i=0
while text[i:i+lenght] !='':
i +=1
if text[i:1+lenght] == "NOUN":
proc= text[i:-1] + word_transformer("NOUN") + text[i+lenght:]
return proc
**
**# you may find the built-in len function useful for this quiz
# documentation: https://docs.python.org/2/library/functions.html#len**
**
test_string_1 = "ds NOUN ds"
test_string_2 = "I'm going to VERB VERB to the store and pick up a NOUN or two."
print process_madlib(test_string_1)
print process_madlib(test_string_2)
Always Return none , if i tested it manually and change "i" all look good
edit : adding code ......
your can read the instruction in the comments
Your code has a few issues with the variable you're using in the loop, specifically you should be using lenght + i instead of lenght + 1. Also, you're incrementing i in the wrong spot.
Here's a version that works:
def process_madlib(text):
proc = ""
lenght = len("NOUN")
i = 0
while text[i:lenght + i] != '':
if text[i:lenght + i] == "NOUN":
proc = text[i:-1] + word_transformer("NOUN") + text[i + lenght:]
return proc
i += 1
return text
test_string_1 = "NOUN ds"
test_string_2 = "I'm going to VERB to the store and pick up a NOUN or two."
print(process_madlib(test_string_1))
print(process_madlib(test_string_2))
It looks like you misspelled "lenght". It should be "length".
Aside from that, what I think you are trying to use is len(i).
Here is the code in the middle.
while text[i:len(text)+1] !='':
i +=1
if text[i:len(text)+1] == "NOUN":
proc= text[i:-1] + word_transformer("NOUN") + text[i+len(text):]
return proc
edited based on Aran-Fey's comment.

CodeHS Python, remove all from string

I am using CodeHS for my Computer Science Principles class and one of the problems in the Strings section is really confusing me. We have to remove all of one string from another string.
These are the official instructions:
Write a function called remove_all_from_string that takes two strings, and returns a copy of the first string with all instances of the second string removed. You can assume that the second string is only one letter, like "a".
We are required use:
A function definition with parameters
A while loop
The find method
Slicing and the + operator
A return statement
We are expected to only have to use those 5 things to make it work.
I attempted to write this program but my function doesn't do anything and I am really stumped.
def remove_all_from_string(word, letter):
while letter in word:
x=word.find(letter)
if x==-1:
continue
else:
return x
print word[:x] + word[x+1:]
remove_all_from_string("alabama", "a")
The easiest way to do this would obviously just be
def remove_all_from_string(word, letter):
return word.replace(letter, "")
However, considering the parameters, another way we could do this is like so:
def remove_all_from_string(word, letter):
while letter in word:
x=word.find(letter)
if x == -1:
continue
else:
word = word[:x] + word[x+1:]
return word
You could run this and print it by typing
>>> print(remove_all_from_string("Word Here", "e"))
#returns Word hr
def remove_all_from_string(word, letter):
while letter in word:
x=word.find(letter)
if x == -1:
continue
else:
word = word[:x] + word[x+1:]
return word
print(remove_all_from_string("hello", "l"))
def remove_all_from_string(word, letter):
letters = len(word)
while letters >= 0:
x=word.find(letter)
if x == -1:
letters = letters - 1
continue
else:
# Found a match
word = word[:x] + word[x+1:]
letters = letters - 1
return word
remove_all_from_string("alabama", "a")
I have this so far and it keeps saying that message is not defined and when I define it with find_secret_word it says "find_secret_word" is not defined, what do I do?
This is my code:
`word = "bananas"
letter = "na"
index = word.find(letter)
def remove_all_from_string(word, letter):
while letter in word:
x=word.find(letter)
if x == -1:
continue
else:
word = word[:x] + word[x+1:]
return word
word = word[:index] + word[index+len(letter):]
print(remove_all_from_string("hello", "l"))
def find_secret_word(message):
while True:
return hidden_word
hidden_word = "iCjnyAyT"
for letter in message:
if letter.upper():
hidden_word = hidden_word + letter
print (find_secret_word(message))`

Odd Python logic error

I apologize if this is just a dumb slip-up on my part, but I am relatively inexperienced with Python and I can't figure out why this isn't working.
I have a class called Game, which contains a word_list that has been read in from a text file. One of the method of the class is as follows:
def make_guess(self, guess):
print("Guess: ", guess)
if guess == self.target_word:
print("Got it!")
if guess in self.word_list:
num_right = self.compare_letters(guess, self.target_word)
else:
print("Not valid guess; not in list")
No matter what input I give it, I can never make it trip the if guess in self.word_list path. I tried comparing the type of the variables (each word in the list, and my input), but they appeared to be the same to me.
The whole definition of the class if it helps:
class Game:
def __init__(self, difficulty):
self.difficulty = difficulty
if 0 < difficulty < 3:
self.remaining_guesses = 5
elif 3 <= difficulty < 5:
self.remaining_guesses = 4
else:
self.remaining_guesses = 3
self.word_list = []
self.dictionary = open("wordsEn.txt")
for word in self.dictionary:
percent = int(floor(1000*random()))
if len(word) == 6 and percent < 2:
self.word_list.append(word)
self.dictionary.close()
percent = int(floor(len(self.word_list)*random()))
self.target_word = self.word_list[percent]
def make_guess(self, guess):
print("Guess: ", guess)
if guess == self.target_word:
print("Got it!")
if guess in self.word_list:
num_right = self.compare_letters(guess, self.target_word)
else:
print("Not valid guess; not in list")
def display_word_list(self):
print("in display")
print(self.remaining_guesses)
for word in self.word_list:
print(word)
print("Target: ", self.target_word)
def compare_letters(self, guess, target_word):
for letter in guess:
if letter == letter:
print("yes")
`
In main, I have:
new_game = Game(difficulty)
guess = input("Guess: ")
new_game.make_guess(guess)
Even if I deliberately guess a word that I know to be in the list, it never says that the word is in fact in the list. What stupid mistake am I making? (and if you could point out ways I could adhere more to the Python style, that would be appreciated as well!)
You need to strip newlines from lines of wordsEn.txt. After
for word in self.dictionary:
insert:
word = word.rstrip()
I'm assuming that each line of wordsEn.txt lists a single word.
Instead of adding the full line to self.word_list, add each word by calling self.dictionary = open("wordsEn.txt").read().split() instead. Here is your edited class:
class Game:
def __init__(self, difficulty):
self.difficulty = difficulty
if 0 < difficulty < 3:
self.remaining_guesses = 5
elif 3 <= difficulty < 5:
self.remaining_guesses = 4
else:
self.remaining_guesses = 3
self.word_list = []
self.dictionary = open("wordsEn.txt").read().split()
for word in self.dictionary:
percent = int(floor(1000*random()))
if len(word) == 6 and percent < 2:
self.word_list.append(word)
self.dictionary.close()
percent = int(floor(len(self.word_list)*random()))
self.target_word = self.word_list[percent]
def make_guess(self, guess):
print("Guess: ", guess)
if guess == self.target_word:
print("Got it!")
if guess in self.word_list:
num_right = self.compare_letters(guess, self.target_word)
else:
print("Not valid guess; not in list")
def display_word_list(self):
print("in display")
print(self.remaining_guesses)
for word in self.word_list:
print(word)
print("Target: ", self.target_word)
def compare_letters(self, guess, target_word):
for letter in guess:
if letter == letter:
print("yes")
Demonstrating the above concept of .read().split():
>>> file = open('blah.txt')
>>> for word in file:
... word
...
'Hello,\n'
'\n'
'These\n'
'Are\n'
'Some\n'
'Vocabulary\n'
'Words\n'
'\n'
'Regards,\n'
'Me\n'
>>> file = open('blah.txt').read().split()
>>> for word in file:
... word
...
'Hello,'
'These'
'Are'
'Some'
'Vocabulary'
'Words'
'Regards,'
'Me'
>>>
In the line where you say
for word in self.dictionary:
This reads an entire line from the text file. So the variable word doesn't refer to a word in the text file. You should first read a line from the text file and then take individual words from the line. Like this :
for line in self.dictionary:
words=line.split();
for word in words:

How can i use "str.find" (python) to locate the next character after a space or " "?

Its a pretty simple operation, but i cant make it work. I know there are plenty of other ways to do this and i have a working code at the moment. But since this is school related, and the teacher asks specifically for str.find i have to make it work his way.
My code at the moment:
def initialer(name):
forname =[0]
space = name.find(" ")
surname = ???
return initialer
print initialer("Andy Olsen")
My working code, but not accepted for this assignment:
def initialer(name):
x = name.split(" ")
y = [words[0] for words in x]
return ".".join(y) + "."
Any suggestions?
my_str = "hello world!"
print my_str[my_str.find(" ") + 1]
Only two words:
def initialer(name):
space_pos = name.find(' ')
if space_pos == -1:
return name[0]
else:
return name[0] + name[space_pos + 1]
Multiple words:
def initialer(name):
space_pos = name.find(' ')
if space_pos == -1:
return name[0]
else:
return name[0] + initialer(name[space_pos + 1:])
More pythonic:
def initialer(name, splitter=' '):
words = name.split(splitter)
return u''.join(zip(*words)[0])

Categories

Resources