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

Time:02-24

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

CodePudding user response:

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!

CodePudding user response:

Try this simple solution, the only code I have changed was the checking of each word. This code checks,

  1. If the min_word variable haven't already been set meaning we're on our first word
  2. Or if the current word is shorter than the previous min_word
def word_length(phrase):
    splitphrase = phrase.split(" ") # split the phrase into each individual word

    min_word = '' # store the shortest word we've found yet
    for _, element in enumerate(splitphrase): # enumerate over each individual ord
        if min_word != '' or 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

    print(min_word)

CodePudding user response:

How about like this:

def word_length(phrase):
    words = phrase.split()
    sw = words[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

  • Related