Python - Find the shortest word in a list - python

Hi all I know there may have been a few similar questions asked already but I would appreciate it if you could give me a more specific solution for what I have attempted.
Basically the program should return the shortest word in the list. The shortest word cannot be an empty string. <-- I'm also not sure how to do this part.
Thanks for the help! : )
Main Program:
n = int((input("Enter amount of words: "))
sw = st.word(n)
print("The shortest word is: {0:.s}" .format(sw))
Function:
def word(n):
l1 = []
for i in range(n):
words = str(input("Enter word: "))
l1.append(words)
s = l1
nxt = l1
for i in range(n+1):
if s[i] < nxt[i+1]:
smallest = s[i]
if nxt[i+1] < s[i]:
smallest = nxt[i+1]
return smallest

You could just use build in min function:
l = ["ab", "abc", "", "fff", "gdfgfdg","a", "3455"]
print(min((word for word in l if word), key=len))
# results in: a
Some explanation:
(word for word in l if word) is generator expression,
if word condition assures that empty strings are not used,
key=len
uses length of each word to look for a minium

You should always prefer to use built-in functions rather than writing your own (maybe except the cases when you are learning). #Marcin describes the work of min function very well, so, I want to present you a filter function as a replacement for generator expressions.
Let's see the way how min and filter may work together:
In [1]: l = ["ab", "abc", "", "fff", "gdfgfdg","a", "3455"]
In [2]: min(filter(None, l), key=len)
Out[2]: 'a'
It may be less intuitive, comparing with #Marcin solution, but I prefer to use high order functions, instead of generators. Reading the text, where one word has 40% frequency (word for word in l if word - 3 / 7) - no, thanks :).
Just a quote from documentation:
In [3]: filter?
Type: type
String form: <class 'filter'>
Namespace: Python builtin
Docstring:
filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true

If you want first minimum word.
n = raw_input('Enter words breaking with spaces:')
wordList = n.split()
print min([(word, len(word)) for word in wordList], key=lambda x:x[1])
If you want all the minimum words.
n = raw_input('Enter words breaking with spaces:')
wordList = n.split()
minimunWordLength = min([len(word) for word in wordList])
minimunWords = filter(lambda x:len(x) == minimunWordLength,wordList)
print minimunWords

Algo:
Get User Input for numbers words by raw_input(). Handle exception handling when user enters wrong input i.e. non integer value.
Check enter number is grater then 0 or not. If yes the go to next steps. otherwise print You enter value less then 1.
Call getSmallWord function, pass words counter as argument.
Use for loop and range function to accept word from the user and add to set variable because words may be duplicates from the user, set will not add duplicate words.
Assign first element from the set as smallest and remove this word from the set.
Iterate every element from the set and check if current element i.e. word length is smaller then smallest word then assign this word as smallest.
Return smallest word.
print result.
Demo:
def getSmallWord(n):
#- Use set because set will add one one word when user enter duplicate words.
words = set()
for i in range(n):
word = raw_input("Enter word: ")
words.add(word)
#- Assign First word as smallest.
smallest_word = words.pop()
#- Iterate words from the 1 index. because we assign 0th element as Smallest.
for word in words:
#- Check Lenght of current elemnt from the User Input with the Smallest Word.
if len(word)<len(smallest_word):
smallest_word = word
return smallest_word
if __name__=="__main__":
try:
n = int(raw_input("Enter amount of words: "))
except ValueError:
n = 5
print "Enter Wrong number input. Number of Words are %d"%n
if n>0:
sw = getSmallWord(n)
print "The shortest word is: %s" %sw
else:
print "You enter value less then 1."
Output:
vivek#vivek:~/Desktop/stackoverflow/anna$ python 8.py
Enter amount of words: 5
Enter word: qwert
Enter word: asdf
Enter word: as
Enter word: asdf
Enter word: qwer
The shortest word is: as
Note:
Use raw_input() for Python 2.x
Use input() for Python 3.x

Related

Write a function longest_word that asks the user for words and returns the longest word entered by the user

Write a function longest_word that asks the user for words and returns the longest word entered by the user. It should stop when the user hits return without typing a word. If multiple words have the same maximum length, return the first word entered by the user. If the user quits before entering any words, return “No words were entered”. This function should use a searching loop. (Hint: remember that the len function returns the length of a string.)
def longest_word():
word = input("enter a word")
if word == "":
return "No words were entered"
max = 0
while len(word) > max :
max = len(word)
new_word = input("enter a word")
if len(new_word) <= len(word):
print(word)
else:
print(new_word)
longest_word()
I understand that I need to iterate the while loop until the user enters without typing any words, but I do not know how to write the corresponding code.
The logic of your code had some flaws.
You need to run the while loop until the input is "" or an empty string and the len(word)>max needs to be inside an if statement. This is because the input value decides whether to break the loop or continue it, the difference in lengths just determines the result.
The returned word should be the longest one(only). But the block:
if len(new_word) <= len(word):
print(word)
else:
print(new_word)
Prints every entered word that is longer than the previous one.
3. You need to change the value of the previous word or the longest word every time a longer word is entered so that it is updated, not just the value of the length.
The code might look like:
def longest_word():
word = input("enter a word")
if word == "":
return "No words were entered"
max = 0 # This variable is not exactly required
longest = word # this variable stores the longest word(currently)
new_word = None # This assignment is for checking for empty strings
while new_word != "" :
max = len(word)
new_word = input("enter a word")
if len(new_word) >= len(longest): # If the entered word is longer, change
# value of the longest word
longest = new_word
print(longest) # Print the longest word.
longest_word()
This is not necessary but avoid naming variables the same as keywords as it often causes a confusion
Some key points of what this function needs to do:
It needs to return the longest word, not print it.
It needs to keep track of the longest word seen so far (so it can return it when it's done). Keeping track of the length of the longest word is not sufficient.
Here's how I might write it:
def longest_word():
longest = ""
while True:
word = input("enter a word")
if not word:
return longest or "No words were entered"
if len(word) > len(longest):
longest = word
Note that the return line immediately ends the loop once no word is entered, and the or statement handles the case where nothing was entered prior to that point.
The remaining if statement ensures that longest is the longest word seen so far.

Why is my function to find the smallest word in an array not working?

I am writing a program to print out the smallest word in phrase. The output is supposed to give me the word "I" but it is instead printing out the word "am". How can I fix this? Please help, I am new to Python
#Given a string 'phrase' consisting of some words separated
# by some number of spaces, return the
# smallest word in the string.
def word_length(phrase):
splitphrase = phrase.split(" ")
min_word = ''
for i, element in enumerate(splitphrase):
if i < len(splitphrase)-1 and (len(element) <= len((splitphrase[i+1]))):
min_word = element
print(min_word)
word_length("hello I am Sam and am tall")
I'll put my code down below and then explain the changes I made:
def word_length(phrase):
splitphrase = phrase.split(" ")
min_word = splitphrase[0] #setting default value as first word
for element in (splitphrase): #for each word in the list
if len(element) < len(min_word): #if the word is shorter than our current min_word
min_word = element #redefine min_word if the current word is shorter
print(min_word)
word_length("hello I am Sam and am tall")
Output:
I
Similar to your code, we start by using the split() function to break our sentence up into words in a list.
To start finding the smallest word, we can define our min_word to initially be splitphrase[0] as our default value.
To determine if other words in the list are min_word, while iterating through every word in the list, if the length of the word we are iterating through in our list is less than the length of current min_word, we redefine min_word to be that current element.
I hope this helped! Let me know if you need any further help or clarification!
the maximum word length possible is the length of the sentence
I check that each word is smaller than the maximum length
if it is smaller I reassign the value of min_word and the min_word_length
def word_length(phrase):
splitphrase = phrase.split(" ")
max_word_lenght = len(phrase)
for el in splitphrase:
if len(el) <= max_word_lenght:
max_word_lenght = len(el)
min_word = el
print(min_word)
word_length("hello I am Sam and am tall")
If you are new to python I would recommend learning a debugging tool so you can better understand the flow of your program.
If you use the command line a possibility is PDB (https://realpython.com/python-debugging-pdb/).
If you use IDE (Spyder, VS, PyTorch) they should have a debugger built-in
How about like this:
def word_length(phrase):
sw = (words := phrase.split())[0]
for word in words[1:]:
if len(word) < len(sw):
sw = word
return sw
print(word_length("hello I am Sam and am tall"))
Note:
This will fail if phrase is an empty string or None. You will also need Python 3.8+
This code, just checks each word if its length if less than the previous shortest words length.
def word_length(phrase):
splitphrase = phrase.split(" ") # Split the phrase into each individual word
min_word = splitphrase[0] # Store the shortest word we've found yet
for element in splitphrase: # Iterate over every word
if len(element) < len(min_word): # Check if we haven't already set the min_word or this word is smaller than the current min_word
min_word = element # Set min_word to the new shortest word
print(min_word)
word_length('Hello how is it going today') # > is

find the longest word and the largest number in a text file

So im learning python right now and i really need your help.
For example you do have random text file with words and numbers inside.
You need to find the longest word and maximum number in this file.
I managed to do the first half, i found the longest word:
def longest_word(word):
with open(word, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print (("the longest word is :"), longest_word ('text.txt'))
can you help me with the second part? how to find maximum number in a file?
You can implement error handling and try to parse the str as int: "2" --> 2
def longest_integer(word):
max_int = 0
with open(word, 'r') as infile:
words = infile.read().split()
for word in words:
try:
int_val = int(word)
if int_val > max_int:
max_int = int_val
except:
pass
return max_int
print (("the longest integer is :"), longest_integer ('text.txt'))
You're almost there! You can check each word to see if it's actually an integer, and then check if that value is greater than the previous max. This assumes the goal is to find the largest integer
for word in words:
try:
if int(word) > MAX_INT:
MAX_INT = word
except:
pass
with open(word, 'r') as infile:
data = infile.read()
nums = [int(num) for num in re.findall('\d+', data)
max_num = max(nums)
As numbers are integers you might get them using str's method isdigit, consider following example:
words = ['abc', '123', 'xyz', '1', '999']
numbers = [i for i in words if i.isdigit()]
print(numbers) # ['123', '1', '999']
then you might provide max with int as key following way:
print(max(numbers, key=int)) # 999
remember to NOT compare strs representing numbers as it might give surprising results, for example:
print(max(['9000','999'])) # 999
note that ValueError will occur if original list (words) do not contain any number.
Edit: I forget to note that above works solely for non-negative integers, to allow also negative one, you might write function for checking that as follow:
def represent_int(x):
if not x: # empty str
return False
if x[0] == '-': # leading - that is negative integer
return x[1:].isdigit()
return x.isdigit()
and use it as follows:
numbers = [i for i in words if represent_int(i)]
note that I assume represent_int will be feeded solely with strs.

Find words in a sentence and its index position using a for loop

I am writing a code that prompts the user to enter a sentence which is then defined as str1 and then is prompted to enter a word defined as str2.
For example:
Please enter a sentence: i like to code in python and code things
Thank you, you entered: i like to code in python and code things
Please enter a word: code
I want to use a for loop to find str2 in str1 to print whether the word is or is not found, and if it has been found, the index position(s) of str2.
Currently I have this code:
str1Input = input("Please enter a sentence: ")
print("Thank you, you entered: ",str1Input)
str1 = str1Input.split()
str2 = input("Please enter a word: ")
if str2 in str1:
for str2 in str1:
print("That word was found at index position", str1.index(str2)+1)
else:
print("Sorry that word was not found")
Although, the outcome appears to print whether or not the index position was found but then prints the index position of every word inside the sentence. Also if I am searching of a certain word that appears twice in that sentence, it just prints the index position of the first time the word is seen in the sentence, for example:
Please enter a sentence: i like to code in python and code things
Please enter a word: code
Thank you, you entered: i like to code in python and code things
That word was found at index position: 1
That word was found at index position: 2
That word was found at index position: 3
That word was found at index position: 4
That word was found at index position: 5
That word was found at index position: 6
That word was found at index position: 7
That word was found at index position: 4
That word was found at index position: 9
If anyone could help me and anyone else attempting something similar to this that would be extremely helpful!
You can use a conditional list comprehension (it's like a for-loop):
>>> str1 = 'i like to code in python and code things'
>>> str2 = 'code'
>>> indices = [idx for idx, word in enumerate(str1Input.split(), 1) if word == str2]
>>> indices
[4, 8]
Giving you the indices of the matches. Then you can do whatever you like with those:
if indices:
for idx in indices:
print('word found at position {}'.format(idx)
else:
print('word not found')
Your attempt actually wasn't too bad but you did one mistake: for str2 in str1: this overwrites your str2 variable which holds the string to look for! Also index will always give you the first index of your variable so when you did str1.index(str2)+1 you looked for the first occurence of the currently investigated item! That's why you had That word was found at index position: 4 two times because it only looked for the first 'code'.
The documentation is always useful to read:
list.index:
Return the index in the list of the first item whose value is x. It is an error if there is no such item.
Use the enumerate python built-in function:
for index, word in enumerate(splitted_sentence):
if word == target_word:
print("Index: ", index)
docs: https://docs.python.org/3.3/library/functions.html#enumerate
UPD: list.index() method returns the lowest index of matching element. That's why you always get same index if your word appears twice in a sentence.
Check the docs on this as well: https://docs.python.org/3.6/tutorial/datastructures.html#more-on-lists
Just make sure to use comparisons in if/else statements and think about what your loop is doing.
Hope this is simple enough but effective:
EDIT: Add a counter rather than using ".index()". Just keeps it nice and basic:
str1In = "I like to code a few things and code a lot"
str2 = "code"
str1 = str1In.split()
indexCount = 0
for word in str1:
if word == str2:
print("Your word was found at index point",int(indexCount))
else:
print("Your word was not found at",int(indexCount))
indexCount += 1
Your problem is in for loop: you assign values from str1 to local variable str1 each iteration. It's called variable shadowing.
The solution is to use different variable name in loop declaration.
What you can do is make a list out of str1 and find where str2 occurs in the list. Here is the code:
str1 = "i like to code in python and code things"
str2 = "code"
the_indexes = []
the_new_list = [str1.split(' ')]
the_count = str1.count(str2)
if the_count > 0:
for i in range(len(the_new_list[0])):
if the_new_list[0][i] == str2:
the_indexes.append(i)
else:
print str2, " not found in the first sentence"
print "The indexes are: "
for i in the_indexes:
print i

Python wordlist

I would like to compare the input letters(dictionary) with the list(textfile with words) and print the words matching the inputed letters. What have I done wrong?(I know i only have a print YES or NO-function if it finds a matching word at the moment. What's the best way to create this function by the way?).
def ordlista(list):
fil = open("ord.txt", "r")
words = fil.readlines()
list = []
for w in words:
w = w.strip()
list.append(w)
return list
chars = {}
word = raw_input("Write 9 letters: ")
for w in word:
w = w.lower()
if w not in chars:
chars[w] = 1
else:
chars[w] += 1
if chars.keys() in ordlista(list):
print "YES"
else:
print "NO"
chars.keys() is a list, so
chars.keys() in ordlista(list):
will never be True. What you want is match the letter counts against each word in your list. So I'd suggest
charsum = sum(chars.values())
for word in wordlist:
if len(word) == charsum and all([(word.count(c) == chars[c]) for c in chars]):
print "YES for word '%s'" % word
EDIT: If you want those words to match which have at least the letter counts (i.e. a word with 3 a's will match an input of two a's), then you'll have to change the == to a >=.
EDIT2: Since you want exact matches, the easiest solution would be to count the number of chars and make sure the word has that length.
You are checking for the presence of the entire list of keys in your character list, rather than checking for each key individually. You must iterate over your keys individually, and then check for their presence.
for k in chars:
if k in ordlista(list):
print "YES"
else:
print "NO"
If you want to print the words which consist solely of the letters in your character list, you may use the following approach.
for word in ordlista(list):
if not filter(lambda char: char not in chars, word):
print word
Use sets:
chars = set(raw_input("Write 9 letters: "))
for word in ordlista(None):
if(set(word) == chars):
print "YES for '%s'" % word
BTW, the argument list to ordlista is unnecessary, as it is not used. I would also advise against using the name list in general, because it hides the built-in <type 'list'>
Update: I have read your comment on jellybean's post. If every letter can only be used once, you can obviously not use sets!

Categories

Resources