Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 747
Shayd3 Avatar asked Oct 01 '14 01:10

Shayd3


2 Answers

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.
like image 87
John1024 Avatar answered Nov 10 '22 09:11

John1024


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)
like image 32
Ankit Sharma Avatar answered Nov 10 '22 09:11

Ankit Sharma