I can't find anything to help me out on this method of sorting. How do I do it?

Recommended Answers

All 18 Replies

You can, for fun, choose sort algorithm, use list of words (strings) and use len() for comparison...
http://www.daniweb.com/code/snippet452.html
Then, if you have problems making it work you can post code, so we can see what is wrong ;)

You can, for fun, choose sort algorithm, use list of words (strings) and use len() for comparison...
http://www.daniweb.com/code/snippet452.html
Then, if you have problems making it work you can post code, so we can see what is wrong ;)

I'm sorry, but I don't understand that code snippet. What are algorithms? And how do I implement them in the following code:

list1 = ['Herring','used','to','be','abundant','in','the','Atlantic','Ocean','then','herring','got','overfished']
print list1
list1.sort()
print list1
list1.sort(key=str.lower)
print list1
list1.reverse()
print list1

I'm doing the task in the Programs for beginners to try out thread, but in the tutorial I used it never mentioned the random factor; reverse, key, cmp sorting; or algorithms. Could you help me learn more?

Oh, one of Vegaseat's brain teasers. There are several ways to solve this. If you look in the Python reference manual under sort for lists, you find that you can specify your own custom sort method. In this case it would be sorting by length of each word/string in the list. Here is an example:

list1 = ['Herring','used','to','be','abundant','in','the','Atlantic','Ocean','then','herring','got','overfished']
print "Original list1:"
print list1
print
print "Using list1.sort(), which is case sensitive sort:"
list1.sort()
print list1
print 
print "using list1.sort(key=str.lower), makes a case insensitive sort:"
# actually compares everything as all lower case
list1.sort(key=str.lower)
print list1
print
print "Reverse the last list using list1.reverse()"
list1.reverse()
print list1
print
print "Sort list1 by length of word, short to long:"

def bylength(word1, word2):
    """
    write your own compare function:
    returns value > 0 of word1 longer then word2
    returns value = 0 if the same length
    returns value < 0 of word2 longer than word1
    """
    return len(word1) - len(word2)

# change the compare method of sort
list1.sort(cmp=bylength)

print list1

I have added some comments, please study it carefully and experiment with it until you undertand fully.

New issue: I've forgotten how to check if an Item appears multiple times in a list, so I can have the program delete the extras. Case insensitive. Oh, yeah. Nice avvy ^_^ Love Pepe LePeu!

There are several ways to do this.

First use a for loop, word.lower() and list2.append(word) to create a new list2 from list1 with all lower case words.

Now you can convert list2 to a set with set1 = set(list2) which by design has only unique words. Convert this back to a list with list3 = list(set1). Use print in each case to check your interim results.

You can also construct the for loop so that you only append the lowercase word if its not already in list2. Then you don't need to do the set() stuff.

Vegaseat makes you think, doesn't he?

If anyone figures out a different way to sort by word length, or form a unique word list, please attach your code to this thread! Would be fun to see your ideas!!!!!

Merci, Pepe, Ma Cherie! Mwah!!! Mwah!!

Doesn't create the lower case list, just makes list2 a copy of list. Help with word.lower()?

list = ['Herring','used','to','be','abundant','in','the','Atlantic','Ocean','then','herring','got','overfished']
print list
list.sort()
print list
list.sort(key=str.lower)
print list
list.reverse()
print list
def bylength(word1, word2):
    return len(word1) - len(word2)
list.sort(cmp=bylength)
print list
def makeUnique(word):
    n=1
    word = list(n)
    for n in list():
        list = word.lower(n)
        list2.append(word)
        print list2

Where am I going wrong?

One word of advice right away:
"Do not use list as a variable name since list is a function in Python!"

Use listA or something like that:

listA = ['Herring','used','to','be','abundant','in','the','Atlantic','Ocean','then','herring','got','overfished']
# start with an empty list
listB = []
# go through each word in listA
# convert it to lower case
# add it to listB with append()
for word in listA:
    word = word.lower()
    listB.append(word)

print listB

"""
result:
['herring', 'used', 'to', 'be', 'abundant', 'in', 'the', 'atlantic', 'ocean', 'then', 'herring', 'got', 'overfished']
"""

To make listB unique via a set, add this to the above code:

setB = set(listB)
listC = list(setB)
print listC

"""
notice that set() changes the word order to its own efficient hash order
result:
['be', 'used', 'overfished', 'then', 'ocean', 'to', 'atlantic', 'in', 'got', 'the', 'abundant', 'herring']
"""

Thanks again Pepe. I really appreciate this!

If anyone figures out a different way to sort by word length....

>>> list1 = ['Herring','used','to','be','abundant','in','the','Atlantic','Ocean','then','herring','got','overfished']
>>> lengthlist = map(len,list1)
>>> lengthlist
[7, 4, 2, 2, 8, 2, 3, 8, 5, 4, 7, 3, 10]
>>> all = zip(lengthlist,list1)
>>> all
[(7, 'Herring'), (4, 'used'), (2, 'to'), (2, 'be'), (8, 'abundant'), (2, 'in'), (3, 'the'), (8, 'Atlantic'), (5, 'Ocean'), (4, 'then'), (7, 'herring'), (3, 'got'), (10, 'overfished')]
>>> allzip.sort()
>>> for i in allzip:
... 	print i
... 
(2, 'be')
(2, 'in')
(2, 'to')
(3, 'got')
(3, 'the')
(4, 'then')
(4, 'used')
(5, 'Ocean')
(7, 'Herring')
(7, 'herring')
(8, 'Atlantic')
(8, 'abundant')
(10, 'overfished')

don't know whether its what you mean by sort by word length..pardon me if not..

I think both Ene's and ghostdog74's solutions to the sort list by wordlength project are very clever! One could also use list comprehension for this.

This example uses list comprehension to remove duplicate elements, and is a modified version from vagaseat's code snippet at: http://www.daniweb.com/code/snippet454.html

gwb = "We got into deficit because the economy went into the recession that is how we got into deficit"

# convert to all lower case words
gwb = gwb.lower()

# form a list of words
rawList = gwb.split()

print "The raw list containing duplicates:"
print rawList

"""
result -->
The raw list containing duplicates:
['we', 'got', 'into', 'deficit', 'because', 'the', 'economy', 'went', 'into', 'the', 'recession', 'that', 'is', 'how', 'we', 'got', 'into', 'deficit']
"""

# create an empty list
uniqueList = []
# use list comprehension to exclude duplicate words when forming uniqueList
[uniqueList.append(str1) for str1 in rawList if not uniqueList.count(str1)]

print "\nThe unique list (no duplicates):"
print uniqueList

"""
result -->
The unique list (no duplicates):
['we', 'got', 'into', 'deficit', 'because', 'the', 'economy', 'went', 'recession', 'that', 'is', 'how']
"""

Ene, thanks for finding this old snippet. I knew I had done something like it. I hope our friend chris99 doesn't get too overwhelmed with the concept of list comprehensions. Actually the snippet at:
http://www.daniweb.com/code/snippet454.html
was written to explain list comprehensions. Using it for uniqueList is actually a special case where the list is not return as normal, but is formed in place. After a while list comprehensions become standard Python thought.

Simple and easy way to do it in Python
words = sorted(words, key = lambda str: len(str))

list.sort(key=len)

Just as an aside, a way to eliminate duplicates from lists, which the OP asked about:

list1 = [1, 2, 7, 3, 9, 2, 3, 5, 1, 0, 9]
set1 = {list1[x] for x in len(list1))}
list2 = list(set1) # can optionally redefine list1

Although I'm sure that code could be more compact.

Something like this ...

list1 = [1, 2, 7, 3, 9, 2, 3, 5, 1, 0, 9]
list2 = list(set(list1))
print(list1)
print(list2)

'''
[1, 2, 7, 3, 9, 2, 3, 5, 1, 0, 9]
[0, 1, 2, 3, 5, 7, 9]
'''

Thanks for simplifying that, Vega :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.