Shayd3
Shayd3

Reputation: 141

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

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.

Upvotes: 6

Views: 47626

Answers (10)

Abdessamad
Abdessamad

Reputation: 1

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

Upvotes: 0

Sandz
Sandz

Reputation: 1

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)

Upvotes: 0

Tirbo06
Tirbo06

Reputation: 773

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'

Upvotes: 0

Ankit Sharma
Ankit Sharma

Reputation: 1654

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)

Upvotes: 4

harish joshi
harish joshi

Reputation: 1

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.

Upvotes: 0

Tal hodorkovsky
Tal hodorkovsky

Reputation: 21

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

Upvotes: 0

2RMalinowski
2RMalinowski

Reputation: 367

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

Upvotes: 0

theideasmith
theideasmith

Reputation: 2925

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

Upvotes: 1

John1024
John1024

Reputation: 113924

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.

Upvotes: 21

wasserfeder
wasserfeder

Reputation: 486

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

Upvotes: 0

Related Questions