Siimple Python. Not sure why my program is outputting this - python-3.x

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)

Related

Longest word in a string using python programming

Hello guys I am still an armature in python was hoping if anyone could help with this solution.
Write a function called longest which will take a string of space separated words and will return the longest one.
For example:
longest("This is Fabulous") => "Fabulous"
longest("F") => "F"
class Test(unittest.TestCase):
def test_longest_word(self):
sentence = "This is Fabulous"
self.assertEqual('Fabulous', longest(sentence))
def test_one_word(self):
sentence = "This"
self.assertEqual("This", longest(sentence))
This is my solution so far;
def find_longest_word(word_list):
longest_word = ''
longest_size = 0
for word in word_list:
if (len(word) > longest_size)
longest_word = word
longest_size = len(word)
return longest_word
words = input('Please enter a few words')
word_list = words.split()
find_longest_word(word_list)
Unfortunately am getting this error when I try to test the code
"File "", line 6
if (len(word) > longest_size)
^
SyntaxError: invalid syntax
Any help please I will highly appreciate?
def find_longest_word(myText):
a = myText.split(' ')
return max(a, key=len)
text = "This is Fabulous"
print (find_longest_word(text)) #Fabulous
EDIT: The solution above works if you want one of the longest words and not all of them. For example if my text is "Hey ! How are you ?" It will return just "Hey". If you want it to return ["Hey", "How", "are", "you"]
Better use this.
def find_longest_word(myText):
a = myText.split(' ')
m = max(map(len,a))
return [x for x in a if len(x) == m]
print (find_longest_word("Hey ! How are you ?")) #['Hey', 'How', 'are', 'you']
See also, this question
You are missing the : at the end of the if statement
Use the updated code below, I fixed your indentation issues too.
def find_longest_word(word_list):
longest_word = ''
longest_size = 0
for word in word_list:
if (len(word) > longest_size):
longest_word = word
longest_size = len(word)
return longest_word
words = input('Please enter a few words')
word_list = words.split()
find_longest_word(word_list)
Code sample is incorrect. I get the following message if I try to output:
Error on line 15: print(longest_word("chair", "couch", "table"))
TypeError: longest_word() takes 1 positional argument but 3 were given
So the code looks like this:
def longest_word(word_list):
longest_word = ''
longest_size = 0
for word in word_list:
if (len(word) > longest_size):
longest_word = word
longest_size = len(word)
return longest_word
words = input("chair", "couch", "table")
word_list = words.split()
find_longest_word(word_list)
# longest word in a text
text = input("Enter your text")
#Create a list of strings by splitting the original string
split_txt = text.split(" ")
# create a dictionary as word:len(word)
text_dic = {i:len(i)for i in split_txt}
long_word = max([v for v in text_dic.values()])
for k,v in text_dic.items():
if long_word == v:
print(k)

Unable to solve this issue with the code

I am having some issues with this question for which i have tried to make 2 solutions.The first one works partially but the second one does not.Here is the question
Question with which i am having the issue.Has sample input and output
Here are the 2 codes which i have written
number=int(input())
S=input()
w=list(S[:])
w_count=0
other_count=0
v_count=0
vv_count=0
i=0
while(i<(len(w))):
try:
if w[i]=='w':
w_count+=1
elif w[i]=='v' and w[i+1]=='v':
vv_count+=1
i+=1
else:
other_count+=1
except IndexError:
pass
i+=1
max_length=w_count*2+other_count+v_count
min_length=0
min_length=w_count+other_count+vv_count
print(min_length,max_length)
The other Logic has been implemented with the help of a for loop for which 3 test cases are passing
for value in range(len(w)):
try:
if w[value]=='w':
w_count+=1
elif w[value]=='v' and w[value+1]=='v':
vv_count+=1
else:
other_count+=1
except IndexError:
pass
If think you can keep it simple with:
my_string = "avwvb"
max_len = len(my_string.replace("w", "vv"))
min_len = len(my_string.replace("w", "vv").replace("vv", "w"))
print(max_len, min_len)
Or a little faster:
my_string = "avwvb"
max_string = my_string.replace("w", "vv")
min_string = max_string.replace("vv", "w")
max_len = len(max_string)
min_len = len(min_string)
print(max_len, min_len)
You can try this. It's similar to your for loop solution but uses string indexing a bit better.
For the first problem I'm just expanding the string as much as possible changing all ws into 2 vs.
The second is a bit trickier. I first expand the string using the previous method, and then build a new string where any vv combinations can be turned into w. I use 2 indexes, i for the longer string and j for the shorter version of the string, in order to avoid index errors.
def longer(s):
for i in range(0,len(s)):
x = s[i]
if x == 'w':
new_str = s[:i] + 'v' + s[i+1:]
if (i + 1 >= len(s)):
new_str = new_str + 'v'
else:
new_str = new_str[:i] + 'v' + new_str[i:]
s = new_str
return s
def shorter(s):
long_str = longer(s)
short_str = long_str[0]
j = 1
for i in range(1,len(long_str)):
x = long_str[i]
if x == 'v' and short_str[j-1] == 'v':
short_str = short_str[:j-1] + 'w'
j = j -1
else:
short_str = short_str + x
j = j +1
return short_str
print len(longer("avwvb"))
print len(shorter("avwvb"))

Piglatin Conversion Program

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

Recursion: Palindromes [duplicate]

This question already has answers here:
Recursive Function palindrome in Python [closed]
(10 answers)
Closed 7 years ago.
So I have this code for detecting if a string is a palindrome (the same forward and backwards) and I'm not sure how to change it to a recursive program
def isPalindrome(string):
i = 0
j = len(string) - 1
k = 0
while (i <= j):
if string[j] != string[i]:
k = 1
else:
i += 1
j -= 1
if k == 0:
return True
else:
return False
def main():
print("This program tests if strings are palindromes.")
word = input("Enter a string: ")
while word != "quit" :
if isPalindrome(word) == True:
print(word,"is a palindrome.")
else:
print(word,"is not a palindrome.")
word = input("Enter a string: ")
main()
I'm really bad with recursions and I don't really understand them any help would be great. Thanks
Without Recursion:
Ideally you might not need recursion for palindrome detection. It can be done simply as below.
def is_palindrome(word):
if word=="".join(reversed(word)):
return True
return False
Another shorter method
def is_palindrome(word):
return word[::-1]==word
Using Recursions:
For some reasons if you still require recursion and comfortable with arrays and indices, Use it like this.
def is_palindrome(word, end=0, start=0):
if end == 0:
end = len(word)-1
if start >= end:
return True
if word[start] != word[end]:
return False
start = start+1
end = end-1
return is_palindrome(start, end, word)
word = 'ramar'
print (is_palindrome(word))
This will be more Pythonic way with recursion
def is_palindrome(word):
if not word:
return True
else:
return word[0]==word[-1] and is_palindrome(word[1:-1])

Duplicate word in hangman game Python

I have a problem, when in Hangman game there is a word like happy, it only append 1 'p' in the list...run my code and please tell me what to do?
check my loops.
import random
import time
File=open("Dict.txt",'r')
Data = File.read()
Word = Data.split("\n")
A = random.randint(0,len(Word)-1)
Dict = Word[A]
print(Dict)
Dash = []
print("\n\n\t\t\t","_ "*len(Dict),"\n\n")
i = 0
while i < len(Dict):
letter = str(input("\n\nEnter an alphabet: "))
if letter == "" or letter not in 'abcdefghijklmnopqrstuvwxyz' or len(letter) != 1:
print("\n\n\t\tPlease Enter Some valid thing\n\n")
time.sleep(2)
i = i - 1
if letter in Dict:
Dash.append(letter)
else:
print("This is not in the word")
i = i - 1
for item in Dict:
if item in Dash:
print(item, end = " ")
else:
print("_", end = " ")
i = i + 1
The error is with the "break" on Line 25: once you have filled in one space with the letter "p", the loop breaks and will not fill in the second space with "p".
You need to have a flag variable to remember whether any space has been successfully filled in, like this:
success = False
for c in range(len(Dict)):
if x == Dict[c]:
Dash[c] = x
success = True
if not success:
Lives -= 1
P.S. There's something wrong with the indentation of the code you have posted.

Resources