Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
No Safe Word
Feb 26, 2005

JoeNotCharles posted:

Fixed your variable name for you.

l = list("1234") is easier and clearer.

Argh, don't do this either :p (I'm sounding like the crotchety old man in this thread). If you want to use a single-letter variable name for a list, use L instead of l. l is a bad variable name in any language because it looks too much like 1 in fixed-width fonts.

Adbot
ADBOT LOVES YOU

hey mom its 420
May 12, 2007

lst :science:

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

No Safe Word posted:

Argh, don't do this either :p (I'm sounding like the crotchety old man in this thread). If you want to use a single-letter variable name for a list, use L instead of l. l is a bad variable name in any language because it looks too much like 1 in fixed-width fonts.

Not if you're using a good coding font. Fonts should not affect how you code.

bitprophet
Jul 22, 2004
Taco Defender

deimos posted:

Not if you're using a good coding font. Fonts should not affect how you code.

Except for the myriad of places that code is seen outside of your preferred editor, such as on pastebin websites. It's silly to do things (or rather, to not do them) which require a particular editor/font choice/keyboard layout/etc, when it's just as easy to do the right thing which won't break everywhere else.

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.

deimos posted:

Not if you're using a good coding font. Fonts should not affect how you code.

PEP 8 posted:

Prescriptive: Naming Conventions

Names to Avoid

Never use the characters `l' (lowercase letter el), `O' (uppercase
letter oh), or `I' (uppercase letter eye) as single character variable
names.

In some fonts, these characters are indistinguishable from the numerals
one and zero. When tempted to use `l', use `L' instead.

tehk
Mar 10, 2006

[-4] Flaw: Heart Broken - Tehk is extremely lonely. The Gay Empire's ultimate weapon finds it hard to have time for love.
I think the only time I had an issue with 'l' was when I committed some code to a project with a fairly strict(for a python project) coding style and I broke some naming conventions by naming a method(that required a L/l as its first letter) with a uppercase L to avoid misreading. Someone submitted a 'fix' later that day.

chutwig
May 28, 2001

BURLAP SATCHEL OF CRACKERJACKS

Is the smtplib module not thread-safe or something? I have a little monitor script set up to monitor some SQL servers and send out an e-mail if there's a long-running query that's taking up too much time on the server. Everything works fine, but when I added smtplib into the mix, everything went all wrong. As soon as the monitor thread sends an e-mail, the script just seems to stop execution shortly after the server.quit(). It sends that e-mail fine (with some formatting issues, but I'll fix that poo poo later) and I see all the debug output on the terminal from set_debuglevel(), and I see it print "E-mail successful" as well (because I added that after the server.quit() to see if it was hanging on waiting for the connection to time out or something), but it never exits the enclosing elif. It's not using any CPU time or anything... it just doesn't do anything. Here's the relevant code:
code:
for k in new_current_pid_dict:
    if new_current_pid_dict[k][2]:
        pass
    elif (new_current_pid_dict[k][1] - new_current_pid_dict[k][0]) > 15: #3h
        from_addr = "pgmonitor@blah"
        to_addr = "me@blah"
        subject = "Database process",k
        warning_text = "Database process",k,"has been running for more than three hours.\r\n \
        Please review this process and terminate it if necessary with 'kill -SIGINT",k,"."
        msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % (from_addr,to_addr,subject,warning_text)

        print "SENDING EMAIL",k
        server = smtplib.SMTP('localhost')
        server.set_debuglevel(1)
        server.sendmail(from_addr,to_addr,msg)
        server.quit()
        print "E-mail successful"
        new_current_pid_dict[k][2] = True
If I just have it print a string or something, no problem, the script continues as normal. smtplib's presence here is loving things up in some way.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!
Chutwig Regarding smtplib - did you look at this thread on c.l.p?

http://groups.google.com/group/comp...a1de3ed29133546

chutwig
May 28, 2001

BURLAP SATCHEL OF CRACKERJACKS

m0nk3yz posted:

Chutwig Regarding smtplib - did you look at this thread on c.l.p?

http://groups.google.com/group/comp...a1de3ed29133546

After I posted, I went back and googled some more and found that discussion. I'll probably just write another script external to this one to handle e-mailing and invoke it through subprocess, or just invoke sendmail directly, or something.

ashgromnies
Jun 19, 2004
How do I make python print out where it's getting its lib path from? Somehow both 2.5.1 and 2.5.2 got installed on my Macbook Pro and 2.5.2 is pointing to a different lib path from 2.5.1 and I want to know where it's pointing at and how to change it. I tried googling but maybe I didn't look up the right thing? ("python change lib path")


edit: ahh, the PYTHONPATH environment variable

ashgromnies fucked around with this message at 21:24 on Apr 9, 2008

No Safe Word
Feb 26, 2005

Anyone used any of the numerous python text parsing libraries out there? I'm playing around with pyparsing and having a bit of a time with it and was wondering: a) are there better options, or b) does anyone know pyparsing well enough that I should post questions here? I don't have anything specific yet, but it might be nice to know who has used what.

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.

No Safe Word posted:

Anyone used any of the numerous python text parsing libraries out there? I'm playing around with pyparsing and having a bit of a time with it and was wondering: a) are there better options, or b) does anyone know pyparsing well enough that I should post questions here? I don't have anything specific yet, but it might be nice to know who has used what.

I like pyparsing the best out of all of the python text parsers I've seen. I'm definitely not the best, but I can try to help you with problems. I've been working with for a little over a year. It's pretty slow, though, so you shouldn't use it if speed is a concern. I use it for lexing wiki pages, and it's fast enough to work with caching, but it definitely wouldn't work if the page was lexed every time it was loaded.

Habnabit fucked around with this message at 04:43 on Apr 10, 2008

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
Just found this article, well worth the stupid free registration, it's an awesome decorator explanation: http://www.linux-mag.com/id/5377

deimos fucked around with this message at 07:08 on Apr 10, 2008

No Safe Word
Feb 26, 2005

Habnabit posted:

I like pyparsing the best out of all of the python text parsers I've seen. I'm definitely not the best, but I can try to help you with problems. I've been working with for a little over a year. It's pretty slow, though, so you shouldn't use it if speed is a concern. I use it for lexing wiki pages, and it's fast enough to work with caching, but it definitely wouldn't work if the page was lexed every time it was loaded.

Okay, well I guess this qualifies as a short question and the thread isn't exactly busting with other questions so here goes.

I'm trying to write a stat file parser for TF2 (I guess I'm a statwhore :byewhore: ), but it uses some funky JSON-like syntax that should be easy to write a parser for using pyparsing but I'm having a bitch of a time understanding why some of it doesn't work. Here's a cut-down sample file:

code:
<!-- dmx encoding keyvalues2 1 format dmx 1 -->
"PlayerStats"
{
	"id" "elementid" "076a075f-a605-42d9-a8b1-2478c0f008c5"
	"aClassStats" "element_array" 
	[
		"ClassStats_t"
		{
			"id" "elementid" "ab132a4c-0e10-49c1-8ee4-811b090568a4"
			"accumulated" "RoundStats_t"
			{
				"id" "elementid" "eb9b2473-2189-4dcd-b7b3-c15ff7500d39"
				"iBackstabs" "int" "0"
				"iBuildingsBuilt" "int" "0"
				<snip>
			}
			"comment: classname" "string" "Scout"
			"iNumberOfRounds" "int" "1609"
			"iPlayerClass" "int" "1"
			"max" "RoundStats_t"
			{
				"id" "elementid" "8de50328-cb14-4fc0-b458-f29c0329c8cf"
				"iBackstabs" "int" "0"
				"iBuildingsBuilt" "int" "0"
				"iSentryKills" "int" "0"
				<snip>
			}
		},
		"ClassStats_t"
		{
			"id" "elementid" "fa0703bc-08b8-4964-934b-18bfad54372c"
			"accumulated" "RoundStats_t"
			{
				"id" "elementid" "f3bf5f05-db8d-4542-8c8a-6f2ba43ce307"
				"iBackstabs" "int" "0"
				"iBuildingsBuilt" "int" "0"
				<snip>
			}
			"comment: classname" "string" "Sniper"
			"iNumberOfRounds" "int" "859"
			"iPlayerClass" "int" "2"
			"max" "RoundStats_t"
			{
				"id" "elementid" "178ae1d7-abd1-4e6d-98a3-616f2729c5b3"
				"iBackstabs" "int" "0"
				"iBuildingsBuilt" "int" "0"
				<snip>
			}
		}
	]
	"iTimestamp" "int" "236806956"
	"iVersion" "int" "0"
	"SteamID" "int" "30350757"
}
I <snip>'ed repetitive portions and cut some other stuff for brevity of course.

So, the pseudo-BNF I worked up looks like:

code:
item :=  <name>  <datatype>  <value>
list :=  <name>  [<datatype>]  "["  (<object>,)+  "]"
object := <name>  [<datatype>]  "{" (<item>|<list>)+ "}"
Where name, datatype, and value are really all just double-quoted strings, [] means optional, and + means one or more. So, here's the pyparsing code I came up with:

code:
statComment = htmlComment
statValue = dblQuotedString
statName = dblQuotedString
statDataType = dblQuotedString

statObject = Forward()
statItem = statName + statDataType + statValue
statList = statName + Optional(statDataType) + delimitedList(statObject)
statObject << statName + Optional(statDataType) + \
    Literal("{") + OneOrMore(statItem | statList) + Literal("}")
statFile = statComment + statObject
But when I try and do a statFile.parse on that data I always get:
pyparsing.ParseException: Expected "}" (at char 132), (line:5, col:5), which refers to the line that starts with "aClassStats". It's like the failure is in the OR'ing of the statItem and statList, though I'm going to try parsing each individual line with all the objects and see if it matches where I expect. But if anything is glaringly wrong let me know.

mightygerm
Jun 29, 2002



does python not have a do ... while looping structure?
If not, is there a way I can emulate it without having to write my code blocks twice?

Git
Aug 21, 2004

Mighty Germ posted:

does python not have a do ... while looping structure?
If not, is there a way I can emulate it without having to write my code blocks twice?

It doesn't have one as far as I'm aware, but PEP 315 proposes one.

I guess the equivalent would be:

code:
while 1:
    ...
    if not condition:
        break

Git fucked around with this message at 20:11 on Apr 10, 2008

other people
Jun 27, 2004
Associate Christ
I have a list that I want to sort. The list would look something likee this:
[python]
[['/mnt/Local/laura', 'IMG_0001.JPG', 1207277478.0], ['/mnt/Local/laura', 'IMG_0002.JPG', 1207277490.0], ['/mnt/Local/laura', 'IMG_0006.JPG', 1207277830.0], ['/mnt/Local/laura', 'IMG_0005.JPG', 1207277795.0], ['/mnt/Local/laura', 'IMG_0004.JPG', 1207277782.0]]
[/python]

I want the list sorted by the third value in each item. I know I can do list.sort() with a flat list, but these are lists within lists, and I have no clue how to proceed.

Maybe this is just highlighting my lack of skill with python, but I find the documentation much harder to understand than, for example, php.

No Safe Word
Feb 26, 2005

Kaluza-Klein posted:

I have a list that I want to sort. The list would look something likee this:
[python]
[['/mnt/Local/laura', 'IMG_0001.JPG', 1207277478.0], ['/mnt/Local/laura', 'IMG_0002.JPG', 1207277490.0], ['/mnt/Local/laura', 'IMG_0006.JPG', 1207277830.0], ['/mnt/Local/laura', 'IMG_0005.JPG', 1207277795.0], ['/mnt/Local/laura', 'IMG_0004.JPG', 1207277782.0]]
[/python]

I want the list sorted by the third value in each item. I know I can do list.sort() with a flat list, but these are lists within lists, and I have no clue how to proceed.

Maybe this is just highlighting my lack of skill with python, but I find the documentation much harder to understand than, for example, php.

code:
In [7]: random.shuffle(L)

In [8]: L
Out[8]:
[['/mnt/Local/laura', 'IMG_0006.JPG', 1207277830.0],
 ['/mnt/Local/laura', 'IMG_0001.JPG', 1207277478.0],
 ['/mnt/Local/laura', 'IMG_0005.JPG', 1207277795.0],
 ['/mnt/Local/laura', 'IMG_0002.JPG', 1207277490.0],
 ['/mnt/Local/laura', 'IMG_0004.JPG', 1207277782.0]]

In [9]: L.sort(lambda x,y: cmp(x[2], y[2]))

In [10]: L
Out[10]:
[['/mnt/Local/laura', 'IMG_0001.JPG', 1207277478.0],
 ['/mnt/Local/laura', 'IMG_0002.JPG', 1207277490.0],
 ['/mnt/Local/laura', 'IMG_0004.JPG', 1207277782.0],
 ['/mnt/Local/laura', 'IMG_0005.JPG', 1207277795.0],
 ['/mnt/Local/laura', 'IMG_0006.JPG', 1207277830.0]]
You can specify a sorting function that takes two arguments and returns -1, 0, 1 for the proper comparison.

Another better example (since sorting these normally produces the same results):

code:
In [11]: L = [(0, 5), (1, 4), (2, 3), (3, 2), (4, 1), (5, 0)]

In [12]: L.sort(lambda x,y: cmp(x[1], y[1]))

In [13]: L
Out[13]: [(5, 0), (4, 1), (3, 2), (2, 3), (1, 4), (0, 5)]

Git
Aug 21, 2004

Kaluza-Klein posted:

I want the list sorted by the third value in each item.

There may be a better way to do this, but you can do it using your own sort function.

code:
>>> lst1 = ['lol', '1', '3']
>>> lst2 = ['lol', '2', '2']
>>> lst3 = ['lol', '3', '1']
>>> biglist = [lst2,lst1,lst3]
>>> biglist.sort()
>>> biglist
[['lol', '1', '3'], ['lol', '2', '2'], ['lol', '3', '1']]
>>> def asort(x, y):
...     if x[2] > y[2]:
...             return 1
...     elif x[2]==y[2]:
...             return 0
...     else:
...             return -1
...
>>> biglist.sort(asort)
>>> biglist
[['lol', '3', '1'], ['lol', '2', '2'], ['lol', '1', '3']]
This page seems pretty informative on sorting. But yeah, there's probably a better way to do this.

e: damnit.

other people
Jun 27, 2004
Associate Christ

No Safe Word posted:

code:
In [7]: random.shuffle(L)

In [8]: L
Out[8]:
[['/mnt/Local/laura', 'IMG_0006.JPG', 1207277830.0],
 ['/mnt/Local/laura', 'IMG_0001.JPG', 1207277478.0],
 ['/mnt/Local/laura', 'IMG_0005.JPG', 1207277795.0],
 ['/mnt/Local/laura', 'IMG_0002.JPG', 1207277490.0],
 ['/mnt/Local/laura', 'IMG_0004.JPG', 1207277782.0]]

In [9]: L.sort(lambda x,y: cmp(x[2], y[2]))

In [10]: L
Out[10]:
[['/mnt/Local/laura', 'IMG_0001.JPG', 1207277478.0],
 ['/mnt/Local/laura', 'IMG_0002.JPG', 1207277490.0],
 ['/mnt/Local/laura', 'IMG_0004.JPG', 1207277782.0],
 ['/mnt/Local/laura', 'IMG_0005.JPG', 1207277795.0],
 ['/mnt/Local/laura', 'IMG_0006.JPG', 1207277830.0]]
You can specify a sorting function that takes two arguments and returns -1, 0, 1 for the proper comparison.

Another better example (since sorting these normally produces the same results):

code:
In [11]: L = [(0, 5), (1, 4), (2, 3), (3, 2), (4, 1), (5, 0)]

In [12]: L.sort(lambda x,y: cmp(x[1], y[1]))

In [13]: L
Out[13]: [(5, 0), (4, 1), (3, 2), (2, 3), (1, 4), (0, 5)]

Woah, thank you! I never would have figured that out myself.

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.
Writing your own cmp function is depreciated and just plain icky, really. Use a key function, which is much, much cleaner. A key function is passed one parameter multiple times: once for each item in the list to be sorted. The list is then sorted by the returned values.
code:
>>> pprint.pprint(l)
[['/mnt/Local/laura', 'IMG_0001.JPG', 1207277478.0],
 ['/mnt/Local/laura', 'IMG_0002.JPG', 1207277490.0],
 ['/mnt/Local/laura', 'IMG_0006.JPG', 1207277830.0],
 ['/mnt/Local/laura', 'IMG_0005.JPG', 1207277795.0],
 ['/mnt/Local/laura', 'IMG_0004.JPG', 1207277782.0]]

>>> import operator
>>> l.sort(key=operator.itemgetter(2))
>>> pprint.pprint(l)
[['/mnt/Local/laura', 'IMG_0001.JPG', 1207277478.0],
 ['/mnt/Local/laura', 'IMG_0002.JPG', 1207277490.0],
 ['/mnt/Local/laura', 'IMG_0004.JPG', 1207277782.0],
 ['/mnt/Local/laura', 'IMG_0005.JPG', 1207277795.0],
 ['/mnt/Local/laura', 'IMG_0006.JPG', 1207277830.0]]
itemgetter returns an object that works like this:
operator.itemgetter(2)(list) -> list[2]

(Working on the pyparsing code, will be up in a minute.)

Habnabit fucked around with this message at 09:03 on Apr 11, 2008

duck monster
Dec 15, 2004

Mighty Germ posted:

does python not have a do ... while looping structure?
If not, is there a way I can emulate it without having to write my code blocks twice?

code:

keep_looping_bitch = true

while keep_looping_bitch:
     #
     # code
     #
     keep_looping_bitch = not (condition)
should emulate
code:
repeat:
     #
     #
     #
until (condition)

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Can anyone who has worked with stackless / threads in general for Python give an evaluation of it? From reading its documentation it seems that they are very small in size and fast yet I rarely hear about anyone using them for projects (sans EVE online).

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
I just found out about dabo it's like django for client applications. It wraps wxPython, making it a bit more pythonic and overall nicer to work with. I haven't done an application in it but I think I have something I want to throw at it.

Juomes
Apr 8, 2008
I remember coming across a 'website game' (where each page is a riddle leading you to the next page) but all the problems were problems to solve in Python.
Anyone know the link?

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Juomes posted:

I remember coming across a 'website game' (where each page is a riddle leading you to the next page) but all the problems were problems to solve in Python.
Anyone know the link?

http://www.pythonchallenge.com/

Juomes
Apr 8, 2008

Thanks. I knew it was going to be something obvious.

Also I'm thankful I remembered about the site because I was out of ideas to practice my newly learned Python knowledge.

the talent deficit
Dec 20, 2003

self-deprecation is a very british trait, and problems can arise when the british attempt to do so with a foreign culture





I'm newish to python, and I've been using TextMate (on OSX) to do most of my editing. However, I'm getting frequent indent errors from code that looks, to my eye, fine. Mostly from code copy/pasted from somewhere. Often I have to delete and whitespace and reinsert the indentation to fix it. Any idea what I'm doing wrong?

Git
Aug 21, 2004

the talent deficit posted:

Any idea what I'm doing wrong?

Tell TextMate to use soft tabs, and set the option to re-indent pasted text in its preferences.

e: Actually, you probably don't need to use soft tabs, if hard tabs are your thing.

Git fucked around with this message at 21:28 on Apr 13, 2008

tehk
Mar 10, 2006

[-4] Flaw: Heart Broken - Tehk is extremely lonely. The Gay Empire's ultimate weapon finds it hard to have time for love.
Like Git said its probably a bad mix of spaces*4 and tabs. I know many editors support an optional convert tabs to spaces function(either realtime or upon save) so you might want to check that out in textmate.

No Safe Word
Feb 26, 2005

Looks like Sun's App Engine/AWS-alike will handle python as well: http://research.sun.com/spotlight/2008/2008-04-09_caroline.html (see the graphic)

:woop:

m0nk3yz
Mar 13, 2002

Behold the power of cheese!
Figured I'd ask - any Boston/Boston Metro area Python people (or people getting into Python) looking around for a Job()?

such a nice boy
Mar 22, 2002

m0nk3yz posted:

Figured I'd ask - any Boston/Boston Metro area Python people (or people getting into Python) looking around for a Job()?

I will move to Boston for a good python job.

Bozart
Oct 28, 2006

Give me the finger.
Hey, I'm a programmer who's looking to pick up Python. I'm an expert at matlab, and proficient in C, C++, and VB. I'm mainly intersted in Python because I'm tired of how crappy Matlab's oo stuff is.

I was thinking of learning python by playing around with Orange and NumPy. Are these good starting points for me (given that I don't care about the web stuff) or should I go for something else like PyGame?

hairacles
Mar 1, 2006

Ba-dunk-a-dunk
I'm making a program for a class where I was told to use the built-in priority queue. However, I was supposed to override the built-in __cmp__ method because because what we are passing into the queue is an array, which python can't compare. The example I was given was:
code:
class HeapItems:
    def __init__(self,name,rank):
        self.name=name
        self.rank=rank
    
    def __cmp__(self,other):
        '''__cmp__ is supposed to return a negative number if self is
        "smaller" than other, 0 if equal, and a positive number if
        "greater."'''
        return  self.rank-other.rank
How could I get it to just compare the [1] item in the array, which would be rank?

mightygerm
Jun 29, 2002



Bozart posted:

Hey, I'm a programmer who's looking to pick up Python. I'm an expert at matlab, and proficient in C, C++, and VB. I'm mainly intersted in Python because I'm tired of how crappy Matlab's oo stuff is.

I was thinking of learning python by playing around with Orange and NumPy. Are these good starting points for me (given that I don't care about the web stuff) or should I go for something else like PyGame?

I was in a similar situation as you (used matlab/shell scripting at work), and just started recently learning Python. I picked up the Programming Python book, along with using the online official Python tutorial and the api for the packages I intended to use. I started converting my old scripts and programs over to Python and got a good grasp of the language.

mightygerm
Jun 29, 2002



hairacles posted:

I'm making a program for a class where I was told to use the built-in priority queue. However, I was supposed to override the built-in __cmp__ method because because what we are passing into the queue is an array, which python can't compare. The example I was given was:
code:
class HeapItems:
    def __init__(self,name,rank):
        self.name=name
        self.rank=rank
    
    def __cmp__(self,other):
        '''__cmp__ is supposed to return a negative number if self is
        "smaller" than other, 0 if equal, and a positive number if
        "greater."'''
        return  self.rank-other.rank
How could I get it to just compare the [1] item in the array, which would be rank?

I don't think I understand your question, can you provide an example input/output of the data you intend you use?

hairacles
Mar 1, 2006

Ba-dunk-a-dunk
Yeah, no problem. The program is for an AI class, and we're doing an intelligent search to quickly find a solution to an 8-puzzle. http://en.wikipedia.org/wiki/8-puzzleSpecifically, A* search. An example of whats being passed in is [2876549, 8], where the first number represents the puzzle being looked at, and the second number is how close the current state is to the solution. So I would be doing heappush(queue, array). So we are supposed to override the __cmp__ so it examines the second item in the array, since the built in heap functions aren't able to recognize what to do when given an array and not a number. The professor never really explained much about how we were supposed to do this, so I might be missing something obvious. What I have so far-
code:
def astar(self, state, heuristic):
    pqueue = []
    heappush(pq, [state, distance to goal])
    while len(pqueue) != 0:
        heappop(pqueue)
        ...stuff...
        for i in children of current satte
        heappush(pqueue, [i, distance of that child to goal]
plus the code I have listed above, which I am a bit confused about.

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.
Well, you've got two problems here. The first is how to override __cmp__ for an array, and the other is what goes in the __cmp__ routine.

The problem is, you can't really override __cmp__ on the "list" class (Python has no separate arrays, you're really using lists) because it's a builtin class and you can't change it. You'll have to make your own class and convert to and from it before you put it on the heap.

code:
class StateArray(list):
  def __cmp__(self, other):
    # cmp code goes here

...

def astar(self, state, heuristic):
  pqueue = []
  heappush(pq, [b]StateArray([/b][state, distance to goal][b])[/b])
  ...
Because StateArray descends from list, it acts just like a regular list except for the __cmp__ method.

Most functions that use compare objects using __cmp__ will take an optional parameter so you can pass a standalone function instead (so you could say def compareStates(a, b): ... heappush(pq, [state, distance to coal], comparseStates)), but heappush doesn't seem to have that, which is an annoying oversight.

Now that you know where to put the __cmp__ function, it should be easy to change the one you were given for HeapItems to use [1] instead of .rank.

...however, this seems pretty roundabout. Are you sure you weren't supposed to just change astar() to use HeapItems instead of an array?

Adbot
ADBOT LOVES YOU

Bozart
Oct 28, 2006

Give me the finger.

Mighty Germ posted:

I was in a similar situation as you (used matlab/shell scripting at work), and just started recently learning Python. I picked up the Programming Python book, along with using the online official Python tutorial and the api for the packages I intended to use. I started converting my old scripts and programs over to Python and got a good grasp of the language.

Alright then, cool. I got Learning Python and read the Tutorial, so I think I am good to go.

The only annoying thing is that the help for built in classes and methods sucks hard after Matlab's great help system. I'll have to spend time bumming around on the python wiki to see if they have better documentation there. Is the Programming Python book significantly better or more in depth than Learning Python? I figure it has a different focus because it has a different animal on the cover!

  • Locked thread