Python: Finding Longest/Shortest Words In a List and Calling Them in a Function
Asked Answered
S

10

5

I have a list of words: words=["alpha","omega","up","down","over","under","purple","red","blue","green"] I have two functions that are supposed to find the shortest and longest words in this list:

def bigWords(list=[], *args):
    largestWord=""
    largestLen=0
    for word in list:
        if largestWord<len(word):
            largestWord=len(word)
            largestWord=word
    print "The longest word(s) in the list is %s." % largestWord

def smallWords(list=[], *args):
    smallestWord=""
    smallestLen=0
    for word in list:
        if smallestLen>len(word):
            smallestLen>len(word)
            smallestWord=word
    print "The shortest word(s) in the list is: %s." % (smallestWord)

I have these functions nested so I can call them all at once:

def callFunctions():
###Words###
    words=["alpha","omega","up","down","over","under","purple","red","blue","green"]

    wordLength=lenList(words)
    print "The amount of words[] is %d" % wordLength
    func_list2 = [bigWords, smallWords]
    for f in func_list2:
        map(f, words)

callFunctions()

This is just returning this without inputing the words in the list:

The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .

Not sure why, any help is appreciated.

Szabo answered 1/10, 2014 at 1:30 Comment(0)
B
20

If you like, there are simpler ways to approach the problem:

words=["alpha","omega","up","down","over","under","purple","red","blue","green"]
sortedwords = sorted(words, key=len)
print "The number of words in the list is: %s." % (len(words),)
print "The shortest word in the list is: %s." % (sortedwords[0],)
print "The longest word in the list is: %s." % (sortedwords[-1],)

This produces:

The number of words in the list is: 10.
The shortest word in the list is: up.
The longest word in the list is: purple.
Boccherini answered 1/10, 2014 at 1:44 Comment(0)
G
4

Just use max and min functions having key as the length

y = []
for names in range(4):
   name = raw_input('Enter:')
   y += name,
s = max(y, key=len)
r = min(y, key=len)
Glare answered 5/7, 2017 at 7:13 Comment(0)
M
1

You are so close - but I think the problem is incallFunctions(). You are mapping the functions in func_list2 to every string in the words array, not applying the function to the array as a whole. It was a good idea to use map, which is a powerful function, but you don't need to use it here. Here is code that I tested with a simple online interpreter. Try it. Good luck with whatever you are learning/ the project you are making!

def bigWords(list=[], *args):
    largestWord=""
    for word in list:       
        if len(largestWord)<len(word):
            largestWord= word
    print "The longest word(s) in the list is %s." % largestWord
    return largestWord

def smallWords(list=[], *args):
    smallestWord = bigWords(list)
    for word in list:
        if len(smallestWord)> len(word):
            smallestWord = word
    print "The shortest word(s) in the list is: %s." % (smallestWord)


def callFunctions():
###Words###
    words=["alpha","omega","up","down","over","under","purple","red","blue","green"]

    wordLength=len(words)
    print "The amount of words[] is %d" % wordLength
    func_list2 = [bigWords, smallWords]
    for f in func_list2:
        f(words)

callFunctions()
Maker answered 1/10, 2014 at 2:0 Comment(0)
C
0

First, you have an error in the code of function bigWords. You should compare with the length and not the word as follows

def bigWords(list=[], *args):
    largestWord=""
    largestLen=0
    for word in list:
        if largestLen<len(word):
            largestLen=len(word)
            largestWord=word
    print "The longest word(s) in the list is %s." % largestWord

Second, to use the two functions, you need to call them for the list of words and not for each word:

def callFunctions():
###Words###
    words=["alpha","omega","up","down","over","under","purple","red","blue","green"]

   wordLength=lenList(words)
   print "The amount of words[] is %d" % wordLength
   func_list2 = [bigWords, smallWords]
   for f in func_list2:
       f(words)

callFunctions()
Culdesac answered 1/10, 2014 at 1:43 Comment(2)
How would I go about finding the smallest word? My output keeps giving me "e" as the smallest word.Szabo
@Szabo you also have a bug in that function. Replace the first line in the if block with smallestLen=len(word).Culdesac
T
0

Try this simple solution:

def find_longest_and_shortest_word(list_of_words):
    longest_word = list_of_words[0]
    shortest_word = list_of_words[0]
    for word in list_of_words:
        if len(longest_word) < len(word):
            longest_word = word
        if len(shortest_word) > len(word):
            shortest_word = word
    print(f'The longest word is: {longest_word}')
    print(f'The shortest word is: {shortest_word}')
    return longest_word, shortest_word
Tingaling answered 1/1, 2019 at 22:39 Comment(0)
S
0

you can sort you list using sorted() function that allows you to sort the list by the length of the strings in it.for that you need to add key=len so the function will sort by length and not by alphabecit order. you also need to give to the function reverse=true so it will be easier to access to the longest string (it will be in [0] at the list)

def longest(my_list): my_list = sorted(my_list, key=len, reverse=True) return my_list[0] list1 = ['aaa', 'bbbb', 'cccccc', 'd'] print(longest(list1))

Steiger answered 28/2, 2019 at 17:16 Comment(0)
P
0
def longestWord(words):
longest=''
for num in range(len(words)):
    if len(longest)<len(words[num]):
        longest=words[num]
print ('longest word is {}'.format(longest))

try calling :longestWord(['longerthanlongest','long','longer','longest'])

same thing can be done to find the samllest.

Pes answered 13/5, 2020 at 15:43 Comment(1)
Hey Harish! Please read up on writing an answer before answering your next question! Enjoy your stay at SO :)Trainee
R
0
words = ["alpha","omega","up","down","over","under","purple","red","blue","green"]

#GET LONGEST WORD
max(words, key=len)
>>> 'purple'

#GET SHORTEST WORD
min(words, key=len)
>>> 'up'
Rancor answered 1/5, 2021 at 7:13 Comment(0)
C
0
def find_longest_word(word):
    
    word_split = word.split()
    
    string = []
    for i in word_split:
        clean_word = "".join(ch for ch in i if ch.isalnum())
        string.append(clean_word)
    
    max_len = -1
    for strings in string:
        if len(strings) > max_len:
            max_len = len(strings)
            longest = strings
    return f'"{longest}" is the longest word in the sentence.' 
  
  
sentence = '''In this example, char.isalnum()
checks if each character in the original string 
is alphanumeric'''       
    
result = find_longest_word(sentence)
print(result)
Casebook answered 13/2 at 7:39 Comment(0)
P
0

Simple solutions, using list comprehension:

l = ["Exercices", "Python", "PHP", "JavaScript", "TypeScript"] #your list

def longest_word(l):

    #Get lengths of words in your basic list
    lengths = [len(i) for i in l]

    #Find index of longest length in the new lengths list
    longestLength_index = lengths.index(max(lengths))

    #Return the longest word
    return l[longestLength_index]

print("Longest word: ", longest_word(l)) #Output: Longest word: JavaScript
Peshawar answered 26/7 at 15:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.