Python Forum
Thread Rating:
  • 3 Vote(s) - 2.67 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sorting File
#1
Write a program that displays the current justices ordered by the year they joined the Supreme Court. 


So there is a file containing the justices in this form: 
Henry,Baldwin,Andrew Jackson,PA,1830,1844

I have to create a new file and sort them into justices ordered by year they joined, and remove the excess information. Ex: Henry Baldwin.
This is what I have so far but I'm just starting out so I'm having difficulty. Any pseudocode or suggestions would be helpful. Thanks
def main():
    justices = placeDataIntoList("Justices.text")
    justices.sort
    createFile(justices)

def placeDataIntoList(fileName):
    data = []
    infile = open(filename, 'r')
    line = infile.readLine()
    for i in range(0,n):
        data = line.splt(',')
        justices(i).firsName = data(0)
        justicess(i).lastName = data(1)
        justices(i).apptPres = data(2)
        justices(i).state = data(3)
        justices(i).yrAppointed = data(4)
        justices(i).yrLeft = data(5)
    return data

Attached Files

.txt   Justices.txt (Size: 4.77 KB / Downloads: 681)
Reply
#2
Parentheses call a function, so justices(i) calls the justices function, which is not defined. I would just keep the items in a list, and line.split(',') gives you that list. Append that to the data list, rather than replacing the data list each loop iteration (which means at the end of placeDataIntoList you are returning one justice's data).

That will give you a list you can correctly sort. The standard way to do this is with the key parameter of the sort method. You pass a function to the key parameter, typically a lambda function. I'm assuming you've covered that in class if the teacher assigned this as homework. You can also read up on all that in the online documentation. The online documentation is great, you should really check it out.

After that you just need to extract the first two items of the list with a slice (datum[:2]), use the join method to put a space between them, and write it out to a file.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sorting Text within a .txt file drogers10940 9 22,379 Dec-16-2017, 04:23 PM
Last Post: squenson

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020