Longest word in a string using python programming - python-3.x

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)

Related

name, *line = input().split() in here can i use *line as a list?

I was doing a question on python and i got "name, *line = input().split() " this line in the code section. Then i searched and found that this line grabs the rest of the input as a list. Now, i want to use *line as a list for my furthur code. I have two question here.
Is *line actual a list?
How Can i use it as a list for furthur calculation?
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
Annotated code:
if __name__ == '__main__':
n = int(input('Enter number of students: '))
student_marks = {}
for _ in range(n): # _ character ignores the value returned by the generator
# split on whitespace, first argument goes to name, remaining go to line
name, *line = input('Enter record(name mrks1 mrks2 ...): ').split()
# line is indeed a list
print(type(line))
# parse the list "line" containing strings into floats/real numbers
scores = list(map(float, line))
# add it to the student dictionary, with value in "name" as the key
student_marks[name] = scores
query_name = input()

How do I print the output in one line as opposed to it creating a new line?

For some reason, I cannot seem to find where I have gone wrong with this program. It simply takes a file and reverses the text in the file, but for some reason all of separate sentences print on a new and I need them to print on the same line.
Here is my code for reference:
def read_file(filename):
try:
sentences = []
with open(filename, 'r') as infile:
sentence = ''
for line in infile.readlines():
if(line.strip())=='':continue
for word in line.split():
if word[-1] in ['.', '?', '!']:
sentence += word
sentences.append(sentence)
sentence = ''
else:
sentence += word + ' '
return sentences
except:
return None
def reverse_line(sentence):
stack = []
punctuation=sentence[-1]
sentence=sentence[:-1].lower()
words=sentence.split()
words[-1] = words[-1].title()
for word in words:
stack.append(word)
reversed_sentence = ''
while len(stack) != 0:
reversed_sentence += stack.pop() + ' '
return reversed_sentence.strip()+punctuation
def main():
filepath = input('File: ')
sentences = read_file(filepath)
if sentences is None:
print('Unable to read data from file: {}'.format(filepath))
return
for sentence in sentences:
reverse_sentence = reverse_line(sentence)
print(reverse_sentence)
main()
You can use the end keyword argument:
print(reverse_sentence, end=' ')
The default value for the end is \n, printing a new-line character at the end.
https://docs.python.org/3.3/library/functions.html#print

Python split string every n character

I need help finding a way to split a string every nth character, but I need it to overlap so as to get all the
An example should be clearer:
I would like to go from "BANANA" to "BA", "AN", "NA", "AN", "NA", "
Here's my code so far
import string
import re
def player1(s):
pos1 = []
inP1 = "AN"
p = str(len(inP1))
n = re.findall()
for n in range(len(s)):
if s[n] == inP1:
pos1.append(n)
points1 = len(pos1)
return points1
if __name__ == '__main__':
= "BANANA"
You can do this pretty simply with list comprehension;
input_string = "BANANA"
[input_string[i]+input_string[i+1] for i in range(0,len(input_string)-1)]
or for every nth character:
index_range = 3
[''.join([input_string[j] for j in range(i, i+index_range)]) for i in range(0,len(input_string)-index_range+1)]
This will iterate over each letter in the word banana, 0 through 6.
Then print each letter plus the next letter. Else statement for when the word reaches the last letter.
def splitFunc(word):
for i in range(0, len(word)-1):
if i < len(word):
print(word[i] + word[i+1])
else:
break
splitFunc("BANANA")
Hope this helps
Those are called n-grams.
This should work :)
text = "BANANA"
n = 2
chars = [c for c in text]
ngrams = []
for i in range(len(chars)-n + 1):
ngram = "".join(chars[i:i+n])
ngrams.append(ngram)
print(ngrams)
output: ['BA', 'AN', 'NA, 'AN', 'NA']

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)

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