[Tutor] methods of sorting

Patti Scott pscott_74 at yahoo.com
Wed Apr 23 01:18:38 CEST 2014


I'm practicing with lists.  I was looking for documentation on sorting with cmp() because it isn't immediately clear to me how comparing items two at a time can sort the entire list.  Identify max or min values, yes, but not sort the whole list.  So, the Sorting HOW TO (Dalke, Hettinger)  posted on python.org goes into detail on using a key parameter for sorted() and .sort(), and using operator module functions.  


How obsolete are the cmp() and the decorate-sort-undecorate methods?  To be understood but probably not used in new code?

Python Programming, Zelle;  Python 2.7.3,  PowerShell, Notepad ++

I tried several means of sorting for exercises, eg

# sortgpa3.py
# extended to let user print report out by name,GPA or credit hours

from gpa import Student, makeStudent
    
def readStudents(filename):
    infile = open(filename, 'r')
    students = []
    for line in infile:
        students.append(makeStudent(line))
    infile.close()
    return students
    
def writeStudents(students, filename):
    outfile = open(filename, 'w')
    for s in students:
        outfile.write("%0.2f\t%s\t%0.2f\t%0.2f\n" % (s.gpa(),s.getName(), s.getHours(), s.getQPoints()))
    outfile.close()
    
def cmpGPA(s1, s2):
    #function compares two students based on GPA
    return cmp(s1.gpa(), s2.gpa())

def cmpHours(s1, s2):
    #function compares two students based on credits
    return cmp(s1.getHours(), s2.getHours())
    
def cmpNames(s1, s2):
    #function compares two students' names
    return cmp(s1.getName(), s2.getName())
    
def main():
    print "This program sorts student grade information by GPA."
    order = raw_input("Do you want results printed by name, credits or GPA? ")
    filename = raw_input("Enter the name of the data file: ")
    data = readStudents(filename)
    if order[0] == ('c' or 'C'):
        data.sort(cmpHours)
    elif order[0] == ('g' or "G"):
        data.sort(cmpGPA)
    else:
        data.sort(cmpNames)
    filename = raw_input("Enter a name for the output file: ")
    writeStudents(data, filename)
    
    print "The data has been written to file %s." % (filename)
    
        
main()


or, 


def main():
    print "This program sorts students based on user request."
    filename = raw_input("Enter name of the file containing student data: ")
    data = readStudents(filename)
    order = raw_input("Choose the field on which to sort students (name, GPA or credits): ")
    #print order[0]
    if order[0] == ('n' or "N"):
        tuples = [(student.getName(), student) for student in data]
        tuples.sort()
        data = [(tuples[i][1]) for i in range(len(tuples))]
        #data.sort()
        
    elif order[0] == ('c' or "C"):
        tuples = [(student.getHours(), student) for student in data]
        tuples.sort()
        data = [(tuples[i][1]) for i in range(len(tuples))]
        
    elif order[0] == ('g' or "G"):
        tuples = [(student.gpa(), student) for student in data]
        tuples.sort()
        data = [(tuples[i][1]) for i in range(len(tuples))]
    
    filename = raw_input("Enter a name for the output file: ")
    writeStudents(data, filename)
    print "The data has been written to %s ." % (filename)
    
if __name__=='__main__':
    main()

or, 


def main():
    print "This program sorts students based on user request."
    filename = raw_input("Enter name of the file containing student data: ")
    data = readStudents(filename)
    order = raw_input("Choose the field on which to sort students (name, GPA or credits): ")
    print order[0]
    if order[0] == ('g' or "G"):
        data = sorted(data, key=lambda student: student.gpa())
    elif order[0] == ('c' or "C"):
        data = sorted(data, key=lambda student: student.getHours())
    elif order[0] == ('n' or "N"):
        data = sorted(data, key=lambda student: student.getName())
    filename = raw_input("Enter a name for the output file: ")
    writeStudents(data, filename)
    print "The data has been written to %s ." % (filename)
    
if __name__=='__main__':
    main()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140422/cae641ef/attachment-0001.html>


More information about the Tutor mailing list