6 Replies - 2942 Views - Last Post: 20 January 2010 - 10:05 PM Rate Topic: -----

#1 gryphin  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 128
  • Joined: 29-October 05

Need help with python sort and output

Posted 20 January 2010 - 01:08 PM

I have been trying to figure this out for like a week... I need some serious help. I have even spoken with programming students and cannot get what I need done. I do not mind doing the work but have no experience in python. All my existing knowledge is c++ and c#. SO PLEASE HELP!!!!!!! Ok, I ranted/raved enough. The goal is to make it sort a list of names and grades thaat will not be in order and keep the name and grade together but sort them so the 3 highest grades (with their names) are put into a output file. I have the code so far like this :

f = open("Input_test_scores.txt", 'r')
f2 = open("best_scores.txt", 'w')

l = []

for line in f:
	s = line.split()
	name = s[0]
	score = s[1]
	l1 = [name, score]
	#print name

	l.append(l1)


	def mycmp(x,y):
		if x[1] < y[1]:
			print "less\n"
			return -1
		elif x[1]>y[1]:
			print "more\n"
			return 1
		else:
			return 0   

	l.sort(mycmp) 

for i in l:
	
	#print i
	f2.write(i[0] and i[1])
	

f.close()
f2.close()




And example of the grades would be like this:

bob 23$
jill 78$
bill 100$
george 99$
mary 98$
tim 45$



And the output file should show like this:
bill 100
george 99
mary 98



The $ shows the end of the line, I want it removed in the final result but I think I can figure the strip command out if I can get the rest... Anyone able to help me? Please?!?!?!

Gryphin.

** A quick edit **
I know about the print more/less lines not needing to be there, those were my attempt to see if the sort was running, and it seems to only be partially running.

This post has been edited by gryphin: 20 January 2010 - 01:10 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Need help with python sort and output

#2 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2871
  • View blog
  • Posts: 11,026
  • Joined: 15-July 08

Re: Need help with python sort and output

Posted 20 January 2010 - 01:20 PM

My first suggestion is to instead of making a list of lists (name, grade), to make a list of tuples (name, grade), so that the original list can be sorted while still keeping the corresponding name and grade together. So now your data structure looks like this:

[('bob', 100), ('pbl', 100)]

instead of like this:

[['bob, 100], ['pbl', 100]]

While both perform the same function, the use of tuples groups them together so that those cannot be changed.

As for getting rid of the '&' character, merely perform a slice to the last character of the string (when you use the .split() method, it makes it a string). So now your assignment looks something like this:

s = line.split()
	name = s[0]
	score = s[1]
	# get rid of the '&' by cutting off the last letter.
	score = score[:-1]
	l1 = [name, score]



The index -1 indicates the last element, and since slices ([]) are exclusive, it cuts all but that off and makes it the new string.
Was This Post Helpful? 0
  • +
  • -

#3 gryphin  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 128
  • Joined: 29-October 05

Re: Need help with python sort and output

Posted 20 January 2010 - 01:37 PM

View PostDogstopper, on 20 Jan, 2010 - 01:20 PM, said:

My first suggestion is to instead of making a list of lists (name, grade), to make a list of tuples (name, grade), so that the original list can be sorted while still keeping the corresponding name and grade together. So now your data structure looks like this:

[('bob', 100), ('pbl', 100)]

instead of like this:

[['bob, 100], ['pbl', 100]]

While both perform the same function, the use of tuples groups them together so that those cannot be changed.

As for getting rid of the '&' character, merely perform a slice to the last character of the string (when you use the .split() method, it makes it a string). So now your assignment looks something like this:

s = line.split()
	name = s[0]
	score = s[1]
	# get rid of the '&' by cutting off the last letter.
	score = score[:-1]
	l1 = [name, score]



The index -1 indicates the last element, and since slices ([]) are exclusive, it cuts all but that off and makes it the new string.


Ok, I did not understand most of that... I have like 3 days experience with python and a couple months with c# and a couple weeks with c++... What is a tuple and how would I use the tuples? I figure one step at a time and that seems like a good spot to start since you listed it first.

Gryphin.
Was This Post Helpful? 0
  • +
  • -

#4 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2871
  • View blog
  • Posts: 11,026
  • Joined: 15-July 08

Re: Need help with python sort and output

Posted 20 January 2010 - 05:24 PM

Alright, let's start at the tuple. It functions like a list but is immutable, which means it cannot be changed after creation. A list can. Stuff stored in a tuple can be referenced and read, but once there, it's there. A list on the other hand can be changed after creation. A tuple is quite useful for keeping things safe from editing...

So, a list of tuples allows for you to sort the tuples by name or age, but it keeps the name and age together, no matter what you do.

Here is an example using the interpreter.
>>> list =[1,2,3]
>>> print list
[1, 2, 3]
>>> list.append(4)
>>> print list
[1, 2, 3, 4]
>>> print list[1:3]
[2, 3]


As you can see, with a list, you can add elements and access the locations.

Here is a tuple:
>>> tuple = (2,5,9)
>>> tuple.append(4)
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
	tuple.append(4)
AttributeError: 'tuple' object has no attribute 'append'
>>> tuple[1:3]
(5, 9)



As you can see, you can still reference the elements the tuple contains, but you cannot change them.

So, an array of tuples allows for you to sort these tuples, but keep the data together.

Edit:
Here is a resource of which I urge you to read: http://www.sthurlow....ython/lesson06/

This post has been edited by Dogstopper: 20 January 2010 - 05:39 PM

Was This Post Helpful? 0
  • +
  • -

#5 gryphin  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 128
  • Joined: 29-October 05

Re: Need help with python sort and output

Posted 20 January 2010 - 06:04 PM

Ok, so I changed the source code a little so it no longer need the remove the $ command (apparently that is not a requirement and some confusion was had because of poor communication)... So the $ will not show up in the input and so it will not need removed in the output. So I just need to know how to get the input info sorted into highest to lowest, then put the 3 highest into an output. So here is what I have now:

f = open("Input_test_scores.txt", 'r')
f2 = open("best_scores.txt", 'w')

l = []

for line in f:
	s = line.split()
	name = s[0]
	score = int(s[1]) 
	#gets rid of the $ at end of file - added by Brian Casey
	#score = score[:-1]
	
	l1 = [name, score]
	#print name

	l.append(l1)


def mycmp(x,y):
	if x[1] < y[1]:
		#print "less\n"
		return -1
	elif x[1]>y[1]:
		#print "more\n"
		return 1
	else:
		return 0   

l.sort(mycmp) 

for i in l:
	
	#print i
	f2.write(i[0]+" "+str(i[1])+"\n")
	

f.close()
f2.close()




This code will put the whole list from input into the output in order of lowest score to highest. How do I make it so it puts it in order highest to lowest? And how would I make it so it just outputs the 3 highest scores?

Gryphin.
Was This Post Helpful? 0
  • +
  • -

#6 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5800
  • View blog
  • Posts: 12,636
  • Joined: 16-October 07

Re: Need help with python sort and output

Posted 20 January 2010 - 06:43 PM

You know what, I'm going to show you how to get your list. With comments. Maybe you can take it from there.

Fire up the python interpreter.
# First pass, load all the lines of the file in
>>> data = [ line for line in open("Input_test_scores.txt", 'r') ]

# Show what we got
>>> data
['bob 23$\n', 'jill 78$\n', 'bill 100$\n', 'george 99$\n', 'mary 98$\n', 'tim 45$\n']

# Grab a line
>>> line = data[0]
>>> line
'bob 23$\n'

# test some string functions, 
>>> line.index('$')
6

# trim to that position
>>> line[:line.index('$')]
'bob 23'

# trim then split
>>> line[:line.index('$')].split()
['bob', '23']

# what happens if the string doesn't exist?
>>> line.index('4')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

# is there a better a method?
>>> line.find('4')
-1

# ok, we've done the testing we need.  Can we do it in one?
>>> data = [ line[:line.index('$')].split() for line in open("Input_test_scores.txt", 'r') if not line.find('$')==-1 ]
>>> data
[['bob', '23'], ['jill', '78'], ['bill', '100'], ['george', '99'], ['mary', '98'], ['tim', '45']]

# looks good, we're there



From here it's pretty easy. You can find the largest. Take that one out of the list. Then find the largest again. You're done.

Hope this helps.
Was This Post Helpful? 0
  • +
  • -

#7 gryphin  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 128
  • Joined: 29-October 05

Re: Need help with python sort and output

Posted 20 January 2010 - 10:05 PM

Thank you. I will be able to test it tomorrow and let you all know how well I got the conepts. I appreciate the help.

Gryphin.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1