Re: [Tutor] Python regular expression
On Dec 3, 2004, at 21:34, Rick Muller wrote: The file type you mention is also called an INI file, and is used for Windows initialization scripts, among other things. There's a nice recipe on this in the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65334 This will read your file in as a dictionary. You can then do searches through lists of the keys: mydict = LoadConfig(file.ini) for key in mydict.keys(): if re.search(key,"_at"): do_something(mydict[key]) Given the size of the file, I don't think that's a good idea... -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accuracy of time.sleep()
On Dec 4, 2004, at 14:24, Dave S wrote: OK I may be pushing it, ;-) I need a script to sleep from any point to 8:05AM when in needs to re-start. So I calculate the number of seconds with the following IMO, instead of doing this you should use cron to make your script start at 08:05. It's probably cleaner. (and yes, there are some versions of cron for Windows -- I don't know where they can be found, but I used one called nnCron Lite at my job this summer) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple RPN calculator
On Dec 4, 2004, at 23:30, Alan Gauld wrote: to make it request for input(s) of say a simple math like "1 2 3 4 5 + - * /". Look at raw_input() But if you are that much of a beginner you need to take several steps back and try one of the tutorials, they all cover raw_input fairly early on... And finally doesn't RPN put the operators first? Or is it me thats getting confused fromtoo much Lisping recently?... Nope, RPN calculators (such as the HP48GX, IMHO the best calculator ever made) require you to input the operands first, then the operators. It's both easier to implement and more intuitive (not to mention way faster to both input and compute) once you've gotten the hang of it. You can probably do a very basic RPN calculator in less than a hundred lines of code, using raw_input() and a stack (well, a list's append() and pop() methods). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hello.py: line 1: print: command not found
On Dec 5, 2004, at 00:53, Cullen Newsom wrote: Hello List, Here is my Error: hello.py: line 1: print: command not found Here is my cat hello.py: [EMAIL PROTECTED]:~> cat hello.py #!/usr/bin/python print "Hello, world!" [EMAIL PROTECTED]:~> I know this is a Linux question (or SuSE question) as much as a python question, but I do not think there is a more appropriate place to ask this question, and hopefully it will help save someone some time and frustration, especially since a person new to Python might well believe it to be a problem with Python. Anyone know the proper thing to set, or change? Thanks. Cullen How are you running your script? Are you doing a basic "python Hello.py", or have you set Hello.py to +x and are you relying on the first line to tell the script where the Python interpreter is? If it's answer #2, you should try replacing your first line with "#!/usr/bin/env python" , and see what happens. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple RPN calculator
On Dec 5, 2004, at 05:31, Liam Clarke wrote: RPN calculator, with operators and operands separate? Sounds counter-intuitive to me. What's the advantage I'm missing? Well, the best way to explain is to take an example. Let's say you want to calculate ((2 + 5) * 3 - (4 / 6)) * ((8 - 2 * 3) / 9 + (10 - 1)) Using a conventional calculator, you'd input the entire expression as above. Considering you have a good calculator (i.e. the parens are not shifted), that's at least 34 keystrokes, you have to get the parens right, and the calculator, which is idling as you type the expression, requires some extra processing time as soon as you hit "enter" to turn it into something it can understand. Now, with a RPN calculator, you input your expression as a tree, where the leaves are the operands and the nodes are the operators, in the order where they have to be processed. In other words, if you were using a HP48, here's what you'd be inputting: 2 5 + 3 * 4 6 / 8 2 3 * - 9 / 10 1 - + * What happens, is that every time you enter an operand (in our case, a number), it's pushed in a stack (which is visible on the screen). And every time you enter an operator, it is applied to the last two operands you entered (they get popped out of the stack) and the result is pushed back in. The economy in keystrokes (32 in that case, given that you have to hit enter after each operand, but operators can be set up so that you don't) is marginal. However: 1) You don't need parentheses any more. You don't have to worry about forgetting to close one, or closing one at the wrong place. In fact, you don't even need to remember the operator priorities. 2) The calculator is working as you type: when you enter an operator, it knows it can compute an operation, unambiguously -- so it does. As a result, RPN calculators often "feel" faster. And since your keystrokes are buffered, you don't even have to worry about slow elementary operations. 3) Not only does the calculator feel faster, it also is faster. Traditional calculators have to parse the algebraic expression to actually convert it to a RPN-like format that can then be evaluated. RPN calculators don't have to. Most RPN calculators also include an algebraic mode to allow you to see the difference; in the case of the HP48 series, using said algebraic mode immediately makes you feel the calculator's main weakness: its processor is ridiculously slow (4 MHz 4-bit Saturn CPU). But when using the calculator in RPN mode, it takes a TI-92 (which sports a 10 MHz 68000) to beat it. Not too bad for a machine that dates back to 1990. All of this, combined to a powerful programming language (RPL -- Reverse Polish Lisp) and a few other interesting features (the most noticeable being almost out-of-the-box Assembly programming capabilities) gave the HP48 somewhat of a cult following, and an incredible game development community: by the time mine gave up the ghost about 6 years ago, there were perfect conversions of Lemmings and Civilization, Dune 2 was well on its way, artists were displaying pictures in 16-greyscale on a screen that has a depth of 1 bit, playing PCM sound on the shittiest buzzer in the world, and people were using the IR data capabilities of the 48 to turn it into a TV remote. But I digress ;) In any case, it takes a while to get used to RPN, but once you get the hang of it, you feel frustrated when you come back to regular algebraic notation. Although as far as pocket calculators are concerned, you don't have a choice anymore -- HP stopped producing calculators a few years ago, having basically done nothing in 15 years to improve the design of the 48/49 series. A shame, really. I call it the "Commodore effect". P.S. Nice Shodan quote Max ;) Hehe... Thanks. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Removing/Handing large blocks of text
On Dec 8, 2004, at 14:42, Jesse Noller wrote: Hello, I'm trying to do some text processing with python on a farily large text file (actually, XML, but I am handling it as plaintext as all I need to do is find/replace/move) and I am having problems with trying to identify two lines in the text file, and remove everything in between those two lines (but not the two lines) and then write the file back (I know the file IO part). Okay, here are some hints: you need to identify when you enter a block and when you exit a block, keeping in mind that this may happen on the same line (e.g. blah). The rest is trivial. The rest of your message is included as a spoiler space if you want to find the solution by yourself -- however, a 17-line program that does that is included at the end of this message. It prints the resulting file to the standard out, for added flexibility: if you want the result to be in a file, just redirect stdout (python blah.py > out.txt). Oh, one last thing: don't use readlines(), it uses up a lot of memory (especially with big files), and you don't need it since you're reading the file sequentially. Use the file iterator instead. I'm trying to do this with the re module - the two tags looks like: ... a bunch of text (~1500 lines) ... I need to identify the first tag, and the second, and unconditionally strip out everything in between those two tags, making it look like: I'm familiar with using read/readlines to pull the file into memory and alter the contents via string.replace(str, newstr) but I am not sure where to begin with this other than the typical open/readlines. I'd start with something like: re1 = re.compile('^\') re2 = re.compile('^\<\/foo\>') f = open('foobar.txt', 'r') for lines in f.readlines() match = re.match(re1, line) But I'm lost after this point really, as I can identify the two lines, but I am not sure how to do the processing. thank you -jesse ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor #!/usr/bin/env python import sre reStart = sre.compile('^\s*\') reEnd = sre.compile('\\s*$') inBlock = False fileSource = open('foobar.txt') for line in fileSource: if reStart.match(line): inBlock = True if not inBlock: print line if reEnd.match(line): inBlock = False fileSource.close() -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "TypeError: 'int' object is not callable"??
On Dec 8, 2004, at 17:01, Dick Moores wrote: I got this error msg for this line of code: n = -(2(a**3.0)/27.0 - a*b/3.0 + c) (where a = 1, b = 2, c = 3) And was baffled until I realized the line should be n = -(2*(a**3.0)/27.0 - a*b/3.0 + c) But I still don't understand what "callable" means. Can someone help? Basically, when you try to execute your first line, the program tries to call the function 2 on the argument (a**3.0). Which of course fails, because 2 is an int, not a "callable" object (function, method, lambda or class). Hence "'int' object is not callable". -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] AttributeError: instance has no __call__ method
On Dec 16, 2004, at 03:56, Marc Gartler wrote: Hi everybody, Prior to this chunk of code 'glass' has been chosen from a list of colors via user input, and I now want to have that choice connect to one of several possible classes: def glass_type(glasstype): if glasstype == 'Red': myglass = RedGlassCost() elif glasstype == 'Blue': myglass = BlueGlassCost() elif glasstype == 'Yellow': myglass = YellowGlassCost() return myglass glasschoice = glass_type(glass) myglass = glasschoice() I've tried various approaches and keep getting different errors. But this one seems closest to my goal, as I know it is at least passing 'glass' into the function: AttributeError: RedGlassCost instance has no __call__ method What is this trying to tell me? Or is that irrelevant as I would be better off trying some other approach altogether? Can we see your code for the *GlassCost classes? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" -- maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] AttributeError: instance has no __call__ method
On Dec 16, 2004, at 04:20, Max Noel wrote: def glass_type(glasstype): if glasstype == 'Red': myglass = RedGlassCost() elif glasstype == 'Blue': myglass = BlueGlassCost() elif glasstype == 'Yellow': myglass = YellowGlassCost() return myglass glasschoice = glass_type(glass) myglass = glasschoice() Can we see your code for the *GlassCost classes? Nevermind, I just figured out the problem. RedGlassCost() returns an instance of the RedGlassCost class, whereas RedGlassCost is the class itself. Thus, you need to remove the parentheses either in the def_glasstype function (you then return a class, affect it to glasschoice and then create an instance of it by instanciating glasschoice) or in your last line (glass_type returns an instance of the class you want). -- Max ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regexp Not Matching on Numbers?
On Dec 14, 2004, at 18:15, Gooch, John wrote: This is weird. I have a script that checks walks through directories, checks to see if their name matches a certain format ( regular expression ), and then prints out what it finds. However, it refuses to ever match on numbers unless the regexp is ".*". So far I have tried the following regular expressions: "\d+" "\d*" "\W+" "\W*" "[1-9]+" and more... I think you have to escape the backslashes. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Printing two elements in a list
On Dec 19, 2004, at 06:16, Jacob S. wrote: Would this work for you? a = ['Name = stuff','CGTATAGCTAGCTA','Name = stuff','CGATATGCCGGCTA'] for index,thing in enumerate(a): if "Name=" in thing: del a[index] I know, that it might be slow, but I thought that maybe it would hold its own because it doesn't have to import the re module, everything's builtin, etc. HTH, Jacob A faster way to do this would be to use something like: if thing.beginswith("Name"): del a[index] -- Max -- maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Popen? or something else
On Dec 22, 2004, at 22:24, Israel C. Evans wrote: Fun! testo = [line for line in commands.getoutput('ls -la').split('\n')] for line in testo: print line spits out nicely formatted ls data. It's Shelly! I haven't tried it, but the above code looks like it could be simplified to: for line in commands.getoutput('ls -la').split('\n'): print line Or, of course, the obvious: print commands.getoutput('ls -la') -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Am I storeing up problems ?
On Jan 2, 2005, at 23:00, Danny Yoo wrote: (Aside: one nonobvious example where copying can be avoided is in Conway's Game of Life: when we calculate what cells live and die in the next generation, we can actually use the 'Command' design pattern to avoid making a temporary copy of the world. We can talk about this in more detail if anyone is interested.) I am. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lottery simulation
On Jan 5, 2005, at 16:33, ümit tezcan wrote: Are there any starting ideas for me to get going on this project either thru the tutor or searching for snippets already created by fellow programmers?? That's probably obvious, but you should proceed as follows: - Generate a number for each person. - For each week, generate a random number (the draw) and compare it to each person's number. - If there is a match, do something. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: The Game of Life
First of all, thanks for answering our questions, Danny! And sorry for the lag before my reply, but I was rather busy over the last few days (moving "back" to the UK). On Jan 6, 2005, at 20:05, Brian van den Broek wrote: I am having a hard time figuring out how to efficiently snip and comment, so please bear with any organizational issues. I think I will just preserve the parts relevant to what I want to talk/ask about and write at the end. And I hereby massively SNIP whatever remained of it. :D I gave some thought (though produced no code) to the question of how to do a life game before you posted your code. My naive approach differs a bit, and it seems to me better. I'd like to know why I am wrong ;-) So, relying on your code unless differences specified (and, like you, not making it OOP, so having more passing of the world than I'd like, but I'm only just now groking the OOP way), I would have done something like the following. (Please be tolerant of any syntactic slips; I think and hope my aim is clear, if not the execution.): 1) Define world by filling an M by N matrix with True and False. Otherwise, as your step (1). 2) Define a print function which goes through the matrix, printing one thing for each True cell and another for each False cell. 3) Define the count_live_neighbours() roughly as you did. (The actual code below assumes your count function, modulo the change to it that you define a LIVE name and I am just using True.) 4) Define a "will be changed function" roughly as the untested code: 5) Define a get_changed_cells_list function (again, untested): 6) Define update_world function (again, untested): I hope the fragmentary nature of this makes my intent clear. Anyway, as I see it, this has the following advantages over your posted code: 1) Cell representations done with built-ins seems likely to be quicker. (A minor point, though.) 2) Use of booleans for cell contents makes the change cell procedure simply saying not .> cell_contents # as in for loop of my update_world(). 3) Neither a copy of the world nor the design pattern is needed. Instead, I make a list of the cells to be changed. In the limit, where ever cell will change, this is no better than a copy of the world, but i) it often is better, and ii) I'm not sure the Life rules can create a world where every cell will change in the next generation, anyway. I don't see any disadvantages, but then I don't see too well ;-) You're wrong in that you're not wrong. I'm not very familiar with design patterns yet, but to me, what you just described looks like another Life implementation using the Command design pattern. It is, however, more efficient and IMO elegant than Danny's. Correct me if I'm wrong (I may be talking out of, er, a certain part of my anatomy that is far from my mouth), but the basic idea of the Command design pattern is to store the changes to be made (instead of the post-change states) in a disposable data structure, then to apply them to the original copy of the world. Which should be more efficient, at least memory-wise. Right? Oh, the Life rules allow a world where every cell will change in the next generation, iff your world is a torus (i.e. the lower row "touches" the upper row as if it were immediately above it, and the right column "touches" the left column as if it were immediately left of it). It is quite trivial: set all cells to LIVE. Next generation they're all DEAD. If your world is a finite rectangle, I think the best you can get is a world where all but four cells (the corners) change next generation (same method). As your rectangle stretches to infinity, obviously, the cells changed/total cells ration converges toward 1. In any case, your point still stands. did you mean make the world a class (and thus avoid the sort of passing the world dict up and down as I did here?) Either way, a quick word or two will be great; I'm not asking for you to take the time to code it up for me :-) Probably, but I don't think that's relevant. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: The Game of Life
On Jan 6, 2005, at 21:20, Brian van den Broek wrote: Oh, the Life rules allow a world where every cell will change in the next generation, iff your world is a torus (i.e. the lower row "touches" the upper row as if it were immediately above it, and the right column "touches" the left column as if it were immediately left of it). It is quite trivial: set all cells to LIVE. Next generation they're all DEAD. Topologist! (That's cheating!) ;-) If we are going that way, you 'iff' seems a bit hasty. Take the 1x1 matrix 'full' of live cells. Well, if the only cell of a 1x1 torus matrix is LIVE, that means it is surrounded by 4 LIVE cells, doesn't it? :D Also, other 'funny' (in the sense that a torus is funny) planes could be defined (say a torus-like structure with more than 1 whole -- cannot recall the general terminology from ill-remembered topology), etc. I meant the claim for a standard non-trivial (i.e. M > 1 and N > 1) MxN euclidean plane matrix, but your correction is both amusing and welcome. Thanks :) However, the main reason why I talked about a torus is that it's one of the two obvious choices when you're implementing Life using a 2D matrix (the other being a finite rectangular plane). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Slightly OT - Python/Java
On Jan 10, 2005, at 00:18, Liam Clarke wrote: Hi all, I've been forcing myself to learn Java, and I was wondering if anyone's used Jython. To clarify - Jython generates Java bytecode? I've also learnt Java in roughly 1 week last autumn, because that's what's used at the University of Leeds. All in all, it's a language I quite like, much superior to C++, although it does lack the elegance of Python and Ruby. I also found that the Swing API (for building GUIs) was remarkably easy to use. I can't compare, though, as I've never written GUI'd Python or Ruby programs (and if I did, I'd probably be using PyObjC or RubyCocoa anyway, so that'd be equivalent to using Objective-C). All that stuff with typing variables - I can understand that you'd want to specify when the compiler needs to reserve 64 bits for a long integer, but beyond that is the typing really necessary for performance reasons? As far as I can tell it's merely so that the compiler can check for errors which could lead to security problems. Very frustrating. As is the true/false checking... Well, it has ups and downs... As you said, strong typing reduces the chances that a security problem will occur, and is slightly faster. Also, Java has something which Python lacks (yet should have): private/protected/public class members. In Python, everything is public, which I consider to be a Bad Thing(TM). (Also very frustrating is having lists that can be comprised only of one variable type.) First things first: don't use lists/arrays. Use Collections instead (classes like ArrayList, HashMap, etc.). They're much more versatile, and akin to lists and dictionaries in Python (sometimes even better). Iterators over them are supported. And while they can indeed only be comprised of one variable type as well, said variable type is Object, from which all classes derive, so that's not a problem (you only have to remember to cast as you get() something from a Collection). (Why can't a non-static method comparison be called from a static reference? What does that mean anyway? Er... What was your code like? (before and after correcting the error) Runtime in Python 17.605 seconds (avg over 10 runs) Runtime in Java 12.302 seoncds (avg over 10 runs) Does runtime in Java include startup? Every time you start a java program, it has to load a BIG runtime in memory (roughly 30 megs of classes -- that's both Java's curse and blessing). Also, this test is not a very good way to measure performance of both languages. Java really shines when you start going haywire with classes and objects -- and the program goes faster as it runs (thanks to the Hotspot JIT compiler, that optimizes and caches stuff in ways I don't really understand) So yes - if Jython compiles to Java bytecode, and gives that 5 seconds faster performance, but I write it in Python, and it gives me that 27 minutes of not messing about counting my braces, I'm in heaven. ( I actually wrote a Python script to count braces.) Oh Ghost. You didn't actually write a Java program using a regular text editor, did you? Go and download Eclipse. Now. It's the best IDE in the world, and probably the main reason why I like Java. It has features you can't live without once you've tried them -- spellchecking with smart correction, auto-completion, pop-up help dialogs... And most importantly, code auto-formatting and automatic brace matching. And of course, it's free (and written in Java). http://www.eclipse.org I'm also told people are currently developing a Python plugin for Eclipse. That'd be the Best Thing Ever(TM). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Modifying game of life
On Jan 10, 2005, at 17:53, Kooser, Ara S wrote: Does anyone have an suggestions, explanations, websites? Thanks. Ara import random perc = raw_input("Please enter a threshold between 0-1. ") raw_input("Press return to make a world") PERSON, EMPTY = '*', '.' def percolation(perc): randval = random.random() PERSON, EMPTY = '*', '.' if randval > perc: EMPTY if randval < perc: PERSON I think the problem is there. The function doesn't return anything. Chances are you should use "return EMPTY" and "return PERSON" instead of what you have right now (have you been using Ruby recently?). Also, the function still doesn't return anything when randwal == perc. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] More and more OT - Python/Java
On Jan 10, 2005, at 22:00, Liam Clarke wrote: Hehe, I'm not up to collections yet... working through Learning Java by O'Reilly. If you already know a bit about OOP, I would recommend that you read bruce Eckel's "Thinking in Java". An excellent book, freely available on-line (do a quick Google search), and it taught me in 1 week all I needed to understand my courses (which dealt with OO analysis and design, Swing GUIs and some ore advanced topics). A good follow-up to that would be McMillan & Wiggleswrorth's "Java Programming - Advanced Topics", through which I'm currently reading. It has some really good stuff, including things about XML parsing with SAX and DOM... I may actually be about to understand how to use SAX and DOM, w00t! (*prepares a bottle of Champagne*) (Why can't a non-static method comparison be called from a static reference? What does that mean anyway? Er... What was your code like? (before and after correcting the error) it was (off top of head here) public class dude { public static void main(String [] args) { System.out.print(args[0]); if (doComp(args[0])); { System.out.println(" is true"); } else { System.out.println(" is false"); } private boolean doComp(String x) { int j = new int(x); #I can't quite remember how I did this precisely. if (j==1) { return True; } else { return False; } } } Okay, I understand the problem, and it's quite logical once you know the reason. Basically, static methods and variables are class methods/variables. That is, they're bound to the class as a whole and not to any instance of it (in fact, they can be used without instanciating the class at all). Non-static members are instance members. They are bound to and act upon specific instances of the class. Thus, you can't use them before instanciating the class first. So, if I have a class called Foo which has the following: public static void bar() public void baz() I can use bar() straight away, by calling Foo.bar(). But if I want to use baz(), I first have to instanciate Foo, with something like Foo blah = new Foo(); and then call blah.baz(), which will then return whatever baz() computes based on blah's state. I guess that if you want your program to be wholly procedural, you need to make all your functions (methods) static, then. But if you're doing that, you're misusing Java. OO programming is where it shines. I have no startup lag really. I stand corrected. But my other point is still valid -- see the Great Language Shootout Benchmarks for "better" (and customizable) language benchmarks. *sigh* I have no net at home at moment, which is very frustrating when I want to d/l documentation & editors. For the mo, it's all Notepad. Ick. I feel your pain. Coding in any language is a chore with Notepad -- it comes down to whichever language requires the least (keyboard) typing being the least unpleasant to use. And Java, unlike Python, requires a lot of typing. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Fwd: [Tutor] Slightly OT - Python/Java
(*bangs head on keyboard* gah, I clicked Reply instead of Reply to All again -- sorry!) Begin forwarded message: From: Max Noel <[EMAIL PROTECTED]> Date: January 11, 2005 00:09:11 GMT To: "Alan Gauld" <[EMAIL PROTECTED]> Subject: Re: [Tutor] Slightly OT - Python/Java On Jan 10, 2005, at 20:04, Alan Gauld wrote: Superior is a relative term. Java has lots of huge restrictions compared to C++ - the lack of operator overloading being maybe the biggest, since it prevents true sub typing of builtins and primitives - thus resulting in extra(and horrible) code. Well, I've very rarely (if ever) used operator overloading, so I can't say I miss it much ;) However, you have a point in that I don't like the fact that everything is not an object in Java. Leftover non-object types from C/C++ (int, float, et al.) stand out like sore thumbs; however I can see how the lack of operator overloading prevents them from disappearing. I'm not sure how it works in Python, though; can you subclass int, list, dict, etc.? Does it have operator overloading, or, missing that, a way to extent operators into classes? And the lack of functionpointers (inner classes not withstanding) is a big hit, and what about multiple inheritance - interfaces suck! True, the lack of function pointers is a problem, at least when working procedurally. When going full-OO, I don't see where this can be a problem (since Class itself is an object, you can create pointers to classes). Also, I agree that interfaces are a bizarre way of adding multiple inheritance. I'm still wondering if there is a better way, though (apart from just allowing multiple inheritance, which I still don't know if it's a good idea or not). Its also much slower - JIT compilers, and even native compilers, notwithstanding. I could go on...but... Of course. I never suggested using Java to write 3D state-of-the-art games. For "standard" applications, though, it beats C/C++ any day of the week (worst-case scenario, you can still extend it in C, can't you? -- not sure about that). And a JIT compiler (HotSpot) is a part of standard Java now, isn't it? So I think it is relevant. (native compilers like GCJ, however, aren't -- they kinda defeat the whole point of Java if you ask me) It is however, a simpler language to learn, and I must admit that having got used to garbage collection in Python going back top C and C++ is a shock... And the large standard library (even if the design is awful in places) is an advantage. Yup. RubyCocoa anyway, so that'd be equivalent to using Objective-C). Have you used Objective C itself? I like it a lot. It combines much of what I like about both C++ and Python. Not yet. I tried learning it by myself last year, but the Cocoa framework, although extremely powerful, was a bit overwhelming to me (especially since I'd never done any real GUI programming). I'll probably give it another shot sometime this year. Also, Java has something which Python lacks (yet should have): private/protected/public class members. In Python, everything is public, which I consider to be a Bad Thing(TM). Why do you think it should have it? Have you run into a lot of problems with inappropriate access in Python programs? This often comes up from ex Java/C++ programmers yet access control like this was not part of any of the earliest OOP languages and nobody ever discussed it much(SMalltalk took one extreme - all data private, and Lisp the other - all public) But I don't recall have any big issues with lack of control, and I don't find it an issue in Python. What exactly do you find to be such a problem with the lack in Python? Well, the fact that everything is public means that if you want a certain form of encapsulation, you have to state in the docstrings what should be used as an "external interface" (stuff like "This is an internal method and may change/disappear in the next version! Don't use it!") and hope that people who use your classes listen to what you say. I like the idea behind encapsulation, that you should be able to use a class as a "black box" with a known interface and not worry about the specifics. The way things are, Python gives you the possibility of shooting yourself in the foot; or to be more accurate they prevent you from preventing others from shooting themselves in the foot when they use your classes. (does what I say make any sense?) A solution would be to do like in Ruby, where class/instance variables have names starting with (respectively) @@ or @. I guess you can do the same in Python (although it'd be __ and _, I suppose), but the language doesn't enforce it. (I know, I know, if I want Ruby, I know where to find it :p ) Does runtime in Java include startup? Every time you start a java program, it has to load a BIG runtime in memory (roughly 3
Re: [Tutor] More and more OT - Python/Java
On Jan 11, 2005, at 01:38, Kent Johnson wrote: Max Noel wrote: A good follow-up to that would be McMillan & Wiggleswrorth's "Java Programming - Advanced Topics", through which I'm currently reading. It has some really good stuff, including things about XML parsing with SAX and DOM... I may actually be about to understand how to use SAX and DOM, w00t! (*prepares a bottle of Champagne*) If you are processing XML with Java you really owe it to yourself to learn about dom4j. Then you won't *have* to understand SAX and DOM, w00t w00t! dom4j? What is it? Is it part of the standard Java distribution? If not, where can it be found? (thanks for the pointer, anyway ^^) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] More and more OT - Python/Java
dom4j? What is it? Is it part of the standard Java distribution? If not, where can it be found? Update: Okay, looks like it's time to go to bed. The link was in bright blue and somehow I didn't see it. D'oh. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] atof error
On Jan 11, 2005, at 20:25, Mike Procario wrote: I got an unexpected error today using string.atof. ValueError: invalid literal for float(): -17,019.797 To me -17,019.797 looks like a perfectly good floating point number. I cannot find documentation on what the allowed range is. The problem is not the range. It's the comma that's right in the middle of the number. Yuck. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Fwd: [Tutor] More and more OT - Python/Java
(yes, forgot to CC the list again -- argh!) Begin forwarded message: From: Max Noel <[EMAIL PROTECTED]> Date: January 11, 2005 23:33:44 GMT To: Liam Clarke <[EMAIL PROTECTED]> Subject: Re: [Tutor] More and more OT - Python/Java On Jan 11, 2005, at 23:15, Liam Clarke wrote: Out of curiousity, having poked around XML while learning about the JScript DOM, what are you using it for? AFAIK, you make up your own tags, and then parse them and display them, and anyone else could create data using your tags. Only thing I've seen that uses XML (remember I'm a n00bie in Python, Java, Jscript and HTML, so I don't see the real indepth stuff) is MSN Messenger for it's logs. And MS IE can parse that XML. I've been curious as to how it's implemented. So yeah, if you want to share your experiences. Regards, Liam Clarke Well, I plan to use it as a data storage format for a university project (crowd simulation in a shopping center -- coded in Java). I hate binary data formats, and XML is a good unified way to store data as ASCII text, so I figured I'd use it. Also, XML files can be parsed without too much work, so I can write scripts that will manipulate my data files, in any language ("any" meaning "Python", there). As a bonus, I've decided to have a look at XSL, which allows me to format a XML file for display in a web browser. It entirely changed my perception of web programming. I intend to program an on-line browser-based game with some friends of mine later in the year (in Python of course -- I converted them), and now that I've seen what XML and XSL can do, we're so going to use them for data output: the data is in dynamically-generated XML, which links to a (static) XSL stylesheet to tell the browser how to render that data. Doing things that way has many advantages: 1) Data is separate from formatting. That's always a Good Thing(TM). If I someday decide that I don't like the way the site looks, I theoretically only need to recreate a stylesheet, without touching anything else. (boom! Instant skins!) 2) Most of the "HTML rendering" is going to be done by the user's browser. This, and the way XSL stylesheets are constructed will prevent many bad HTML issues. 3) For the same reason, it will save bandwidth. The XML data will probably take less space than the fully-formatted stuff I'd have to spit out with "regular" HTML, and the XSL stylesheet can probably be cached by the user's browser. 4) In the same line of reasoning, it'll also save CPU time: XML data, being smaller, is generated faster than the equivalent HTML. Granted, the stylesheet is another server request, but it's static, so it puts virtually no load on a server. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" -- maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] More and more OT - Python/Java
On Jan 12, 2005, at 00:49, Guillermo Fernandez Castellanos wrote: Does that mean that you use XML as a database to store data and make queries, or that you store your information as XML in a database (as MySQL)? Nope, nothing that fancy, I'm afraid. Just your run-off-the-mill "load from XML/save to XML" file operations. I ask that because I'm writting a little program that will make queries over a 1500 entries database, with very simple queries. I need an answer in 1 or 2 seconds. I'm using SQLite now, but i wanted something that depends as little as possible of external dependencies (as a database). You should stick to SQLite. After all, it was designed exactly for what you're doing. Well, AFAIK at least. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] More and more OT - Python/Java
On Jan 12, 2005, at 01:40, Liam Clarke wrote: So, you've got the XML like - You are standing in front of a stump. A path leads north. N and you have a XSL that works like a CSS? descript {font:arial, align:center} exits style:bolder Is that a good paraphrasing? How browser dependent would that be? Do most browsers support XML & XSL? Yup, that'd be the idea. IIRC most browsers support XML and XSL. (not sure, I'll have to check) PS What's SAX DOM? I know what a DOM is, but what's the SAX? I saw it in my Python docs when I was poking XMLParser. If/when I work with XML, would you recommend Python's standard modules for it? SAX is just another way of parsing XML. It's very sequential in nature, so it's not good if you need to re-access a previous node from the document, but since it doesn't load the entire document in memory (doesn't build a tree out of it), it uses less memory than DOM, and scales much better (obviously). I haven't tried Python's XML parsers yet, but I understand Python supports both SAX and DOM, so it should be okay... -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] spaces in print
On Jan 12, 2005, at 17:17, kevin parks wrote: when i print: print '\n','siday_q', key, '.wav'# event i get: siday_q 515 .wav how can you eliminate the spaces to get: siday_q515.wav The quick and dirty way is to do: print '\n' + 'siday_q' + key + '.wav' The elegant way is to do use string formatting: print '\nsiday_q%s.wav' % (key) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List comprehensions
On Jan 13, 2005, at 01:13, Bob Gailer wrote: At 04:48 PM 1/12/2005, Kent Johnson wrote: If you mean for j to be a list of foobar(item) then use j=[foobar(item) for item in x] The first part of the list comp can be any valid expression. Does that mean that there are invalid expressions? I'd enjoy seeing an example. Here's an obvious one: j = [foobar(item)/0 for item in x] -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List comprehensions
On Jan 13, 2005, at 04:13, Bob Gailer wrote: I like Kent's response. foobar(item)/0 is a "valid" expression. It fits the grammar of expressions. The fact that it raises an exception does not make it an invalid expression. Consider foobar(item)/xyz. It is valid. If xyz == 0 then it will also raise an exception. You have a point, I hadn't thought of it that way. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Faster procedure to filter two lists . Please help
On Jan 14, 2005, at 23:28, kumar s wrote: for i in range(len(what)): ele = split(what[i],'\t') cor1 = ele[0] for k in range(len(my_report)): cols = split(my_report[k],'\t') cor = cols[0] if cor1 == cor: print cor+'\t'+ele[1]+'\t'+cols[1]+'\t'+cols[2] 164:623 6649TCATGGCTGACAACCCATCTTGGGA 484:11 6687ATTATCATCACATGCAGCTTCACGC 490:339 6759GAATCCGCCAGAACACAGACA 247:57 6880AGTCCTCGTGGAACTACAACTTCAT 113:623 6901TCATGGGTGTTCGGCATGAAA Okay, so the idea is, the first column of each row is a key, and you want to display only the rows whose key is the first column (key?) of a row in my_report, right? As Danny said, you should use dictionaries for this, with a structure in the lines of: what = {'164:623': '6649TCATGGCTGACAACCCATCTTGGGA', '484:11': '6687 ATTATCATCACATGCAGCTTCACGC', '490:339': '6759GAATCCGCCAGAACACAGACA', } (etc.) Lacking that, as Danny said, nested loops are a huge time sink. Also, you should avoid using C-style for loops -- Python-style for loops (equivalent to Perl's foreach) are much more elegant (and probably faster) in that case. Here's how I would do it with your data structures (warning, untested code, test before use): # First, create a list where each element is one of the keys in my_report # Also, strings have a split() method, which by default splits on any whitespace # (tabs included) headers = [element.split()[0] for element in my_report] for element in what: # Okay, the nested loop is still (more or less) there, but it occurs within a # 'in' operator, and is therefore executed in C -- much faster. if element.split()[0] in headers: print element Also, it's shorter -- 4 lines, comments aside. Nevertheless, as Danny suggested, an approach using dictionaries would blow this away, speed-wise. Hope that helps, -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help
On Jan 10, 2005, at 14:31, john stanley wrote: This is my first attempt at programing and my first program sort of did work hear is the program and if any one can tell me what i did wrong or forgot i would appreciate it a = input("Type in the Grose: ") b = input("type in the Miles: ") print "a * 0.74 / b is" a*0.74/b as you can see it should be realy easy program once it works The first thing to do is to look at the error that was caused, and what caused it. Python is good at it, as it shows you the exact line, and even the exact character where the error happened. Now, this example is trivial, but in the future, when you have such a problem, please include the traceback in your message, thanks. Anyway, the error happens in the last line, just before the last expression (a*0.74/b). Which is logical, because that expression is in no way linked to the string that's before it. I suppose you want to display the result of the expression right after the string, don't you? Then you might want to use the string concatenation operator: + It should be easy to correct, now... -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Objects, persistence & getting
On Jan 16, 2005, at 21:13, Liam Clarke wrote: If I understand correctly, once an object is created, as long as references to it exist, it isn't garbage collected. Correct, more or less (in the exception case where a references b, b references a but nothing else references either, both are GC'd if the implementation is sound). So, if module a.py creates an instance of class foo, can method bar in module b.py access foo without foo being passed directly to bar? Well, if you don't pass at least a reference to what you want the method/function to act on (assuming bar is not a method of Foo, of course -- or else, you should know that splitting the implementation of a class across multiple files, let alone modules, is a Bad Thing(TM)), how do you expect it to know? Does that make sense? So, foo is floating around in the namespace, and bar just wants to grab a field of foo. Can it? I had a poke around the namespace yesterday, and got lost in hordes of methods that look like __this__, which is ugly. Watch out, you seem to be confusing classes and objects, there. What are you trying to achieve there, exactly? Could you give us an example? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Objects & Classes...
On Jan 17, 2005, at 20:51, Jack Cruzan wrote: Ok, so each character has his name, race, his stats, his skills, and his gear. since the name and character is unique there is no need for a class these things. hmmm maybe I am conceptualizing this wrong. would each new character then be a dictonary? Made up of different elements or would the character be a list? Since each character is basically just a list of stats... the stats get modified up and down by race and certain gear... am I conceptulizing this correctly? I've thought about it a few times. Actually, when I learn a language, I often try to design and implement a SR character generator. Then I give up because it's really complicated and I don't have time (other things to do using the aforementioned programming languages, mostly :D ). I'm probably gonna end up making a web-based one at some point, using either mod_python or Ruby on Rails. Gah, so many things to do, and so little time... Anyway, my view of the problem was that at least the following should be classes: - Character - Attribute - Skill (perhaps a subclass: Specialization?) - Augmentation (with subclasses like Cyberware, Bioware, AdeptPower) - GearItem Character would mostly be a container for the other classes, so most of its attributes would be dictionaries, like: class Character: def __init__(): self.attributes = {'Body': Attribute(), 'Quickness': Attribute(), 'Strength': Attribute(), 'Charisma': Attribute(), 'Intelligence': Attribute(), 'Willpower': Attribute()} Ah, things would be so much easier if McMackie would release the NSRCG source code (despite this abomination being written in Visual Basic), wouldn't they? ;) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Objects & Classes...
On Jan 17, 2005, at 22:02, Chad Crabtree wrote: (why would an attri bute need to be a separate class?) So that the points or Karma (depending on the generation system) cost of the Attribute can be calculated without having to resort to procedural programming. You'd be then able to get the Karma cost of all the attributes by using a line such as: return sum([att.getKarmaCost() for att in attributes]) The following is a preliminary Attribute class I dug up from my hard drive, made for the BeCKS creation system. Feel free to use bits of it... #!/usr/bin/env python class Attribute: """Shadowrun character attribute.""" def __init__(self, baseRating = 1, racialMod = 0, augCyber = 0, augMagic = 0): """Create an Attribute.""" # Initialize the class attributes... self._baseRating = 1 self._racialMod = 0 self._augCyber = 0 self._augMagic = 0 self.setBaseRating(baseRating) self.setRacialMod(racialMod) self.setAugCyber(augCyber) self.setAugMagic(augMagic) def getRating(self): """Return the attribute's modified Rating.""" return self._baseRating + self._augCyber + self._augMagic def getBaseRating(self): """Return the attribute's base Rating (unmodified by magic or cyber).""" return self._baseRating def setBaseRating(self, baseRating): """Set the attribute's base Rating. baseRating must be an int equal to or greater than max(1, 1 + racial mod).""" if type(baseRating) != int: raise TypeError, "Attribute rating must be an int." if baseRating < 1: # Attribute rating can't be lower than 1. baseRating = 1 if baseRating < 1 + self._racialMod: # Attribute rating can't be lower than 1 + racial mod. baseRating = 1 + self._racialMod self._baseRating = baseRating def getRacialMod(self): return self._racialMod def setRacialMod(self, racialMod = 0): """Set the racial modifier for the attribute. racialMod must be an int.""" if type(racialMod) != int: raise TypeError, "Racial modifier must be an int." self._racialMod = racialMod # Re-set the base Rating to enforce the racial limits self.setBaseRating(self._baseRating) def getAugCyber(self): return self._augCyber def setAugCyber(self, augCyber): """Set the cyber augmentation(s) for the Attribute. augCyber must be an int.""" if type(augCyber) != int: raise TypeError, "Cyber augmentation must be an int." self._augCyber = augCyber def getAugMagic(self): return self._augMagic def setAugMagic(self, augMagic): """Set the magic augmentation(s) for the Attribute. augMagic must be an int.""" if type(augMagic) != int: raise TypeError, "Magic augmentation must be an int." self._augMagic = augMagic def getKarmaCost(self): """Return the BeCKS Karma cost of the Attribute.""" rating = self.getBaseRating() racialMod = self.getRacialMod() minr = max(1, 1 + racialMod) maxr = 6 + racialMod if rating <= maxr: # Could (will) be optimized for speed, but the formula is much clearer this way cost = sum([2*i for i in range(minr + 1, rating + 1)]) else: cost = sum([2*i for i in range(minr + 1, maxr + 1)]) + sum([3*i for i in range(maxr + 1, rating + 1)]) return cost if __name__ == '__main__': # Run a simple test procedure atr = Attribute() print atr.getRating() atr.setRacialMod(1) print atr.getRating() atr.setAugCyber(1) atr.setAugMagic(1) atr.setBaseRating(3) print atr.getBaseRating(), atr.getRating() print 'Karma total cost', atr.getKarmaCost() del atr -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] COP vs OOP (was: Objects, persistence & getting)
On Jan 17, 2005, at 22:41, Bernard Lebel wrote: Alan Gauld wrote: In fact I usually refer to Java as a Class Oriented Programming rather than Object Oriented. If you allow me a question What is the fundamental difference between the two? To me this is not clear. I thought that a class was basically a programming object with properties and methods, but I never thought a class could not be an object. if you're only using static (class) methods, then your class can't/needn't be instanciated, and then is nothing more than the equivalent of a Python module. I think that's what Alan means by class-oriented programming. However, all the Java programming I've done so far has been true OOP (hopefully; it was for a Uni module called Object-Oriented Software Engineering), and I fail to see what in its design does not encourage this practice. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] COP vs OOP
On Jan 17, 2005, at 23:07, Bernard Lebel wrote: Okay... so if I follow you, a class that has methods not part of itself, it's not a static class...? So should I understand that a class that gets inherited methods can be considered OOP? Not exactly. Basically, object-oriented programming is just that; that is, working with objects, which are instances of classes. Now, class methods/attributes, which I call "static" because that's the C++/Java keyword that triggers them, are methods and attributes that are shared by all the instances of that class, not specific to a particular instance. The class doesn't even have to be instanciated (no objects have to be created) for them to be used. They are effectively part of the class itself, hence the name, class methods (as opposed to instance methods). A common use for class attributes is to keep track of how many times the class has been instanciated (number of objects created). So, if my class only has static methods and attributes, any object I create with that class is empty: it has no attributes of its own, and is impossible to be interacted with. Thus, you could just as well say it doesn't exist, and that the class can't be used to create objects. Therefore, you're using a class to do procedural programming. However, the class has its separate namespace: when you're calling methods from that class from outside its body, the call syntax is Class.method(). Which is exactly the same thing as using a function from Python module. I hope that answers your question... -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Objects & Classes...
On Jan 18, 2005, at 02:59, Jack Cruzan wrote: Wouldn't it though! I haven't checked but doesn't he use xml for his equipment lists - if that was the case it would be worth it to ask him for those files 'eh? Last time I checked, he didn't. I have the DAT files here (extracted them off a Windows installation of the program) and have been trying to write a Python script that would convert them to XML. However, the file format is exotic and inconsistent (just like VB, some would say ;) ), so I haven't found a way yet to write an "universal converter": the script has to be modified for each file. I'm pleased neither with this solution, nor with the way my script looks: it's ugly. At some point, such a converter will have to be written, though, unless you want to go through the extreme pleasure of going through 1 meg of text files by hand. Hmm, I really should try to start working again on this web-based SRCG idea of mine... The whole thing just screams "database". Daaargh, so many things to do, so little time. I suppose no good mod_python tutorials have spawned since last time I asked, right? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Objects & Classes...
On Jan 18, 2005, at 03:46, Liam Clarke wrote: Curious - what's mod_python? A Python module for the Apache web server, that among other things addresses the main shortcoming of CGI: mod_python (and mod_perl, mod_php and mod_ruby, for that matter) keeps the interpreter into memory (and as part of the server, so to speak). The server doesn't need to load and initialize a new interpreter each time a page is requested. This yields a tremendous speed increase (speaking in requests/second there, not in script execution time), and ensures that mod_python scales up *much* better than CGI. http://www.modpython.org/ -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shadowrun programs
On Jan 18, 2005, at 17:52, Jack Cruzan wrote: Greetings! Ok if any of you read my earlier email you would have seen that: A) I am a newbie programmer. B) A Shadowrun gamer. C) In over my head making a SRCG (Shadowrun Character Generator) so with that in mind gave up making my python based SRCG. Instead I am making python Shadowrun utilities! The first of which was a program size and cost calculator for decker's utilities and skillsofts. (I always hated flipping back and forth in the book to figure it out). Thought I would let you see it and maybe critique? Be kind its first original program I have written. (Well thats not php or shell script). Doesn't look bad. However, you should aim to repeat yourself as little as possible, and the "The program's[...]" string is repeated 4 times. You should delay its display until the end of the program, like that: if rating < 4: availability = "2/7" cost = rating * 100 # same for other options... # [skipping to the end of the program] print "The program's Availability is ", availability, " days and costs ", cost Of course, an even better way is to use string formatting in the print line. But that's not really important. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] style question: when to "hide" variable, modules
On Jan 18, 2005, at 22:50, Kent Johnson wrote: Python, instead, lets you change what attribute access means. The way to do this is with 'properties'. This is kind of an advanced topic, here are two references: http://www.python.org/2.2.1/descrintro.html#property http://www.python.org/doc/2.2.3/whatsnew/sect- rellinks.html#SECTION00034 I have to admit, this is brilliant. Thanks for the pointer, Kent. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] A somewhat easier way to parse XML
Hi everyone, I've just spent the last few hours learning how to use the DOM XML API (to be more precise, the one that's in PyXML), instead of revising for my exams :p. My conclusion so far: it sucks (and so does SAX because I can't see a way to use it for OOP or "recursive" XML trees). I'm certain it can be used to do extremely powerful stuff, but as far as usability is concerned, it's ridiculously verbose and naming is inconsistent. I've had a look at Java DOM as well, and it's apparently the same. This afternoon, I read a bit about YAML and its basic philosophy that everything can be represented as a mix of lists, dictionaries and scalars. Now, setting aside the fact that one look at YAML made me want to ditch XML for data storage purposes completely (which I can't do since there's no Java YAML parser that I know of so far), it came to my mind once again that this is the one thing I want to be able to do in XML. Chances are that's all what 9 out of 10 programmers want to do with XML. In fact, I find it appalling that none of the "standard" XML parsers (DOM, SAX) provides an easy way to do that (yeah, I know that's what more or less what the shelve module does, but I want a language-independent way). So, to wrap my head around DOM, I set out to write a little script that does just that. Introducing xmldict.py and the DataNode class. For example, given the following XML file: Body 6 Quickness 9 ...the DataNode class (yeah, I think I may have implemented that in a slightly bizarre fashion) will produce the following dictionary: {u'attribute': [{u'@key': u'BOD', u'name': u'Body', u'rating': u'6'}, {u'@key': u'QCK', u'name': u'Quickness', u'rating': u'9'}]} As you can see, everything is represented in a mix of dictionaries, lists and unicode strings, and can now be used by a normal human being to write a program that uses this data. Comments, criticism, improvements, suggestions, [whatever]... Would be appreciated. Feel free to use it if you wish. Thanks for your attention. xmldict.py Description: Binary data -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?"___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A somewhat easier way to parse XML
On Jan 19, 2005, at 03:58, David Rock wrote: For me, it seems that the way you are supposed to interact with an XML DOM is to already know what you are looking for, and in theory, you _should_ know ;-) Indeed. The problem is, even if I know what I'm looking for, the problem remains that given the following document, baz If I want to get "baz", the command is (assuming a DOM object has been created): doc.documentElement.getElementsByTagName("bar")[0].childNodes[0].nodeVal ue Quoting from memory there, it may not be entirely correct. However, the command has more characters than the document itself. Somehow I feel it'd be a bit more elegant to use: doc["bar"] (or depending on the implementation, doc["foo"]["bar"]) Don't you think? Still, I can't help wishing I had a simple way to create a dict from a DOM. From a Python perspective, that seems more "Pythonic" to me as well. I guess it's just a different way of looking at it. I can't help but think that from the perspective of any other language, that would feel more [language]-ic as well ;) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Importing multiple files as a single module?
Hi everyone, Having learnt OOP with C++, and most of my OOP experience being with Java, I'm used to storing my classes in one file for each class. I find it tidier and easier to read/debug. However, when I try to do the same in Python, each file corresponds to a module with a single class in it. Is there a way to obtain the same result in Python as in Java? That is, I'd like to have the following on my hard drive: foo/ Bar.py Baz.py Where Bar.py and Baz.py each contain a single class (Bar and Baz). Then, from Python, I'd import the foo module (import foo) and then access the classes with foo.Bar and foo.Baz (instead of foo.Bar.Bar and foo.Baz.Baz, which is what I have now). Being able to use Bar in Baz.py would of course be a nice side effect. Any ideas? Or am I trying to do things in a very non-Pythonic way? If so, how am I supposed to organize my OOP code, especially given the absence of a "real" IDE for Python? Thanks for your attention, -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] read line x from a file
On Jan 22, 2005, at 13:53, Kent Johnson wrote: That is the simplest solution. If your file gets bigger and you don't want to read it all at once, you can use enumerate to iterate the lines and pick out the one you want: f = open(...) for i, line in enumerate(f): if i==targetLine: print line # or whatever break f.close() Of course, to do that, you must know the number of lines in the file beforehand. If you're running a UNIX system (Linux, OS X, *BSD...), that's easily done by calling the command "wc -l " (use os.popen to do that). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How would python messure up in performance?
On Jan 23, 2005, at 12:55, Kevin wrote: How well would a multi user texed based game created in just Python run if there were over 300 - 400 players (Just a hypathetical question) Would python be to slow to handle that amount of traffic? It depends... What would be happening in said game? What would it involve, calculation-wise? What would you be running it on? In that kind of program, the core programming itself is rarely a bottleneck (IOW, Python should work just fine). The true elements on which your game's performance depend are: 1) Connection bandwidth and latency 2) Database access (especially if the DB is not on a remote server) 3) File I/O, if any Could you give us a few more specs? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] on the way to find pi
This code gives the number in an unusual format like "3.1415'None'" it has a number part and a string part . I want to seperate these from easc other but I couldn't manage. I mean when I try to turn it into string format then try to use things like [:4] or like that they don't work.Any idea how to seperate this 'None' from the number and make it a real normal number on which I can do operations like +1 -1 or like that :) Regards Well, you should try to have a look at where the "None" is appended to the string representing the number, and use a type check to decide whether or not you're appending/adding/whatever. >>> type("abc") >>> type(123) >>> type(None) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Print record x in a file
On Jan 23, 2005, at 22:08, Liam Clarke wrote: Don't you mean x=random.randint(0, lenoflist) ?? I'm assuming you want an integer. random.randrange() returns an item (which can be a float or whatever, but by default is an int) in the specified range. In that case, an int between 0 and lenoflist. The advantage over random.randint is that you can specify a step. Thus, random.randrange(0, 257, 2) will return an even number between 0 and 256 inclusive. While although this code below does work many times nothing is printed out. import random i = 0 while i < 10: file = open('test.rantxt') listcontents = file.readlines() file.close() lenoflist = len(listcontents)#-1 x = random.randrange(0,lenoflist) print listcontents[x], i i = i +1 Anyway, the problem with this function is that len returns a number of items, but Python, like most good programming languages (and mathematicians), counts starting from 0. Thus, the first element in a list is foo[0]. foo[len(foo)] will raise an IndexError. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How would python messure up in performance?
On Jan 23, 2005, at 23:57, Kevin wrote: Well not sure how to answer that but I will try. For file I/O you would have a seperat file for each character that would store HP/MANA/MOVE points, store items that the character would have on. Areas would be loaded from there own files with all the creatures and items for that area in the same file. Spells would probably have there own seperate file to load from. As far as unning the game it would be run on a redhat linux server. That's a bizarre design choice (for the characters, I mean), this just screams Database, especially since you may find yourself with concurrent write accesses on some files (e.g. a player attacks another while the other is moving). Anyway. This looks like you'll be doing lots of file I/O, with a few calculations inbetween, right? Then unless your server is really shitty, Python should handle this just fine. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ascii encoding
On Jan 24, 2005, at 23:29, Luis N wrote: How would I best turn this string: '2005-01-24 00:00:00.0' into this string: '2005%2D01%2D24%2000%3A00%3A00%2E0' In order to call a URL. I've hunted through the standard library, but nothing seemed to jump out. The pathname2url in urllib seems to do what you want: >>> import urllib >>> urllib.pathname2url('2005-01-24 00:00:00.0') '2005-01-24%2000%3A00%3A00.0' And urllib.url2pathname does the opposite conversion. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sorting a 2 gb file
On Jan 25, 2005, at 23:40, Danny Yoo wrote: In pseudocode, this will look something like: ### hints = identifyDuplicateRecords(filename) displayDuplicateRecords(filename, hints) ### My data set the below is taken from is over 2.4 gb so speed and memory considerations come into play. Are sets more effective than lists for this? Sets or dictionaries make the act of "lookup" of a key fairly cheap. In the two-pass approach, the first pass can use a dictionary to accumulate the number of times a certain record's key has occurred. Note that, because your file is so large, the dictionary probably shouldn't accumulation the whole mass of information that we've seen so far: instead, it's sufficient to record the information we need to recognize a duplicate. However, the first pass will consume a lot of memory. Considering the worst-case scenario where each record only appears once, you'll find yourself with the whole 2GB file loaded into memory. (or do you have a "smarter" way to do this?) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ascii encoding
On Jan 26, 2005, at 00:50, Luis N wrote: Ok, urllib.quote worked just fine, and of course so did urllib.pathname2url. I should have run a dir() on urllib. Those functions don't appear in http://docs.python.org/lib/module-urllib.html Now, how might one go about calculating the New York time off-set from GMT? The server is in the U.S. but time.localtime() is giving me GMT. time.timezone gives you, I think, the offset between your current timezone and GMT. However, being myself in the GMT zone, I don't know exactly if the returned offset is positive or negative (it returns 0 here, which makes sense :D ). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ascii encoding
On Jan 26, 2005, at 02:44, Tony Meyer wrote: time.timezone gives you, I think, the offset between your current timezone and GMT. However, being myself in the GMT zone, I don't know exactly if the returned offset is positive or negative (it returns 0 here, which makes sense :D ). Whether or not it's positive or negative depends on which side of GMT/UTC you are, of course :) Note that the result in is seconds, too: Of course. What I meant was that I didn't know which "side" returns a positive offset (IOW, whether Paris (GMT+1) returns -3600 or +3600 -- it's the former, it seems). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ascii encoding
On Jan 26, 2005, at 02:56, Luis N wrote: In other words I have to do some arithmetic: import time time.timezone 0 The server is located in Dallas, Texas. Which means it's not properly configured. On UNIX systems, to configure the timezone, you must adjust /etc/localtime so that it's a symlink that points to the appropriate timezone in /usr/share/zoneinfo . The exact layout of the /usr/share/zoneinfo folder is probably implementation-specific, but for example, here's how it is on my Mac OS X box: [EMAIL PROTECTED] ~]% ls -l /etc/localtime lrwxr-xr-x 1 root wheel 33 25 Jan 18:58 /etc/localtime -> /usr/share/zoneinfo/Europe/London -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Should this be a list comprehension or something?
On Jan 26, 2005, at 03:17, Terry Carroll wrote: My goal here is not efficiency of the code, but efficiency in my Python thinking; so I'll be thinking, for example, "ah, this should be a list comprehension" instead of a knee-jerk reaction to use a for loop. Comments? The point of the code is to take a sequence of objects, each object representing an amount of water with a given mass and temperature, and to return another object that represents all the water ideally combined. The formulae for the combined mass and temp are respectively: combined mass = M1 + M2 + M3 (duh) combined temp = ((M1*T1) + (M2*T2) + (M3*T3)) / (M1 + M2 + M3) Here's my code: class Water: def __init__(self, WaterMass, WaterTemperature): self.mass = WaterMass self.temperature = WaterTemperature def __repr__(self): return ("%.2f, %.2f" % (self.mass, self.temperature)) def CombineWater(WaterList): totalmass=0 numerator = 0; denominator = 0 for WaterObject in WaterList: totalmass += WaterObject.mass numerator += WaterObject.mass * WaterObject.temperature return Water(totalmass, numerator/totalmass) Well, you can do this with list comprehensions, yeah: totalmass = sum([WaterObject.mass for WaterObject in WaterList]) totaltemp = sum([WaterObject.mass * WaterObject.temp for WaterObject in WaterList]) / totalmass return Water(totalmass, totaltemp) Doesn't seem that much more Pythonic to me. I find it about as readable as your code, but someone who isn't used to list comprehensions will find that weird-looking. However, someone who uses functional programming languages a lot (Lisp, Scheme, Haskell, ML...) will be familiar with that. The actual pros of that method is that it's a functional approach and that it has less lines than your approach (you can even reduce it to a one-liner by adding a third list comprehension, but at that point it starts to look ugly). As for the cons, as I said, it may seem less readable than the original version to the non-experienced; and chances are it's slower than the original version since it has to iterate through 4 lists instead of 2. In any case, when in doubt, do what you think will be easier to maintain. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] New to Python
On Jan 27, 2005, at 02:09, Jason White wrote: I'm curious about good tutorial websites and books to buy. I learned Python (well, the basics thereof -- enough to do useful stuff on my summer job, anyway ^^) in an afternoon using the official tutorial that's found somewhere on http://www.python.org/ . It's very good provided you already have some programming experience (which seems to be your case). I hear that Alan Gauld's tutorial is also very good, but geared more towards people new to programming. You'll find the address in his sig (which itself should be in the post that he sent to the list while I was writing this one, if my predictions are accurate :p ). I also have a development question for anybody who might know. The project I'm working on now to develop my python skills is a prgram to script control another windows program. The program doesn't have a published API so I'll probably need to locate memory addresses data fields and button routines. Am I in way over my head for a Python beginner or does anybody have any advice for where to start poking around in memory and which python classes I should use to do so? Eeh? Peeks and pokes? Are you even allowed to do that? I mean, doesn't Windows have a protected memory mechanism, like any OS should have nowadays? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Safely buffering user input
On Jan 27, 2005, at 18:17, Bill Mill wrote: I've never used buffer(); in fact, I didn't even know it existed, and I've been using python for a while now. Instead of using buffer, just do: sys.argv[1] = sys.argv[1][:255] This says "Set the second element of sys.argv equal to its first 256 characters". Also, I don't think you have to worry about buffer overflows in Python, unless you're using a seriously broken implementation of it. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] carriage return on windows
On Jan 30, 2005, at 02:18, R. Alan Monroe wrote: print "Percent completed:" + str(percent) + "\r" Print forces a newline. Try sys.stdout.write instead. Alan You can also use the following syntax: >>> print "Percent completed:", str(percent), "\r", The trailing comma is NOT a typo, it is intentional. It prevents print from appending a newline. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] carriage return on windows
On Jan 30, 2005, at 02:40, Jacob S. wrote: I don't think that's what he wants. I think he wants to *overwrite* what's in the shell with new output. For example. so that the whole line is overwritten. In my experience, this is not possible and if anyone can show me how to do it, I would be grateful. HTH, Jacob It *is* possible, that's exactly what my code does (well, as long as you don't run it on Mac OS 9). The carriage return (\r, as opposed to the linefeed \n) moves the cursor to the beginning of the *current* line. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Presentation
On Feb 1, 2005, at 16:35, Paul Hartley wrote: When I was a member of the Forth Interest Group in the USA we learned that Forth was used on the buggy that went to mars, that it started life controlling huge radio telescopes which only had 4k (yes 4k) of memory for both language and application. Anything like the above concerning python would be useful. Well, that's probably not as awe-inspiring, but BitTorrent is written entirely in Python (with the wxPython graphical toolkit for the Windows and X11 versions, and PyObjC for the Mac OS X version). Google also use the language extensively, although I don't exactly know why, thanks to their obsession with secrecy. You could point out that Python's greatest strength (aside from its extreme readability -- unlike most people, The Whitespace Thing always struck me as an excellent design decision, although had I been Guido, I'd have forced the use of either tabs or spaces but not allowed both) is the fact that it's multi-paradigm. You can work procedurally, object-orientedly, and even in some cases functionally. And you can mix-and-match those 3 paradigms depending on your needs. This can be very useful. Oh, and make sure you mention iterators and list comprehensions at some point. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Classes
On Feb 1, 2005, at 23:08, Ismael Garrido wrote: Hello. I was just wondering, what magic can you do with classes? I mean, things like "class Name(Exception)" or "class Name(threading.Thread), which other classes are interesting to subclass? I've seen Object too, but I don't understand what it does. Basically, Object is the class all your classes should be deriving from (when you do that, you're using "new-style classes"). It's the root in the class hierarchy of Python. This gives you access to a lot of nifty features for free, such as properties. Oh, and the best classes are those you create yourself, of course :D -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to separate hexadecimal
On Feb 2, 2005, at 10:19, Ewald Ertl wrote: Hi! Using binary operations: a='0x87BE' str(hex(int(a,16) & 0xFF)) '0xbe' str(hex((int(a,16) & 0xFF00) / 0xFF)) '0x87' HTH Ewald Actually, the int conversions aren't even necessary. >>> hex(0x87BE & 0xFF) '0xbe' >>> hex((0x87BE & 0xFF00) / 0xFF) '0x87' -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Are you allowed to shoot camels? [kinda OT]
On Feb 2, 2005, at 23:18, Liam Clarke wrote: 1) I'll use Perl for the regex stuff from now on, Perl is obviously built for this. Actually IIRC Perl *invented* regexes as we know them. The "standard" regex syntax is known as "Perl regex syntax". 2 ) There's More Than One Way To Do It makes debugging hard - i.e. close INFILE; & close (INFILE); are both valid. I like one syntax, cos it's easier to remember. I don't find it that bad. Ruby does it as well, and it's perfectly readable. It's more or less equivalent as if condition: and if(condition): both being valid in Python. 3) Some stuff is counter-intuitive - $lenOfModList = @moddirList is the Perl equivalent of lenofModList = len(moddirList) You sure of that? I was under the impression that len(moddirList) in Perl was $moddirList (@moddirList is the list itself). Also, why doesn't if ( not $d eq "a" && not $d eq "c") evaluate to true for $d = "b" when if (not $d eq "a") evals to true and if ($d ne "a" && $d ne "c") evals true also? What's with that? This probably has to do with operator precedence. It's been lifted from C, so chances are that && has a higher precedence than eq. Use parentheses. 4) WHAT IS WITH THE STUPID SYMBOLS EVERYWHERE LARRY??!! I'm not referring to the $ & @, I can see how they could be useful, although with a list - @dude = (1, 2, 3), to obtain the 2nd value I would expect $d = @dude[1], not $d = $dude[1], that's counterintuitive also. This will be fixed in Perl 6. Then again, Perl 6 is supposed to be pure heaven, as the Parrot virtual machine can theoretically be used with any language and is heavily optimized. Python and Ruby with the speed of Perl, and the possibility to interface your code with CPAN modules. That's really cool. Once Perl 6 is released, of course. Why is the read/write modifier part of the filename??? Why is it a > ? In my opinion, there's only one place a > sign should be, in an inequality test. This is consistent with UNIX redirection. ./foo > bar.txt executes the command foo, and redirects its STDOUT to the file bar.txt. ./foo >> bar.txt does the same, but appends to bar.txt instead f overwriting it. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Are you allowed to shoot camels? [kinda OT]
(damn, forgot to add the main part of my argumentation) I learnt Perl as well, a few years ago. It was the first scripting language I came across (all I knew before that were C, Turbo Pascal, and a few calculator programming languages), so I immediately fell in love with its string manipulation capabilities. I came across PHP a little while after, and while it had some things which I liked (PHP.net being the main one), I preferred Perl. However, I never got the opportunity to really use it, and after a while the inconsistency of the syntax grew on me, and the language itself kept eluding me. I was never able to grok it, and thus systematically reverted to C every time I had to code something. Fast forward to last summer. In the span of 1 week, I discovered both Python and Ruby. Fell in love with both and immediately ditched Perl. I never looked back, even though I know Perl is still the fastest scripting language around. I value debugging time more than CPU time these days. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Are you allowed to shoot camels? [kinda OT]
On Feb 3, 2005, at 00:42, Liam Clarke wrote: I don't find it that bad. Ruby does it as well, and it's perfectly readable. It's more or less equivalent as if condition: and if(condition): both being valid in Python. Yeah, but you'd never call a function foo like this- x = foo in Python. It's just good to be able to say that a function always has . That improves readability (imao). Yes. That, and the fact that you can use function pointers very easily that way. For example, x = foo x() will call foo. Which is cool. I do prefer the Python style as well. Just like variable naming conventions should tell you something about their nature, function calls should have something that explicitly gives them away as such. MyClass MY_CONSTANT myVariable myFunctionCall() @mod = (1,2,3) $mod = 3 $mod[0] = 1 Is inconsistent. Or at least, the logic behind this is not immediately apparent to me. I'm always open to illumination on these things however. Yeah. As with most things in Perl, there is no way to guess it. This is actually what I hate the most about that language, and what makes it write-only. if ( not $d eq "a" && not $d eq "c") = False for $d = "b" if ($d ne "a" && $d ne "c") = True This probably has to do with operator precedence. It's been lifted from C, so chances are that && has a higher precedence than eq. Use parentheses. Ah... Ironic, I got misled by TMTOWTDI. I figured that if not x=="a" and not x == "c" evaled as True in Python, and "if (not $d eq "a")" evaled as True in Perl, that if ( not $d eq "a" && not $d eq "c") would also eval as true. Of course, what's even weirder to me is that if ($d ne "a" && $d ne "c") does eval as True, as far as I can see, '$d ne "a"' is the same as d != "a" in Python, which is the same as 'if not d == "a"', which, logically, would mean that $d ne "a" is the same as 'if(not $d eq "a") in which case both tests should handle the addition of an AND the same. Again, no, because IIRC (it's been a while since I last used Perl) eq and ne are the Perl operators with the lowest precedence. In effect, your last statement is evaluated as if((not $d) eq "a"). Use == and !=, they work on strings as well. Or (and?) use parens. Also, don't forget that Perl, like Python, uses lazy evaluation. Once again, illumination is welcomed, as I have a finally that some subtlety of Boolean logic is eluding me, and a 'x != a' test is different to 'if not x == a' in a small but significant way. Max - the foo > std.txt thing explains it, but what about @dude = , where do the brackets originate from? I have no idea. Somehow I think it makes sense. It's one of the few things that I think make sense in Perl. Couldn't tell you why I think so, though :p This is another issue I'm having with Perl as opposed to Python - Perl is very much written by *nix users for *nix users, it's implementation of *nix conventions shows, including the `` things. Whereas (correct me if I'm wrong), but Python was written by *nix users for everyone. Python seems very non-OS-denominational in it's current incarnation, it may have been very *nix orientated prior. Not really. The thing is, Python in itself does very little. You have to import modules whenever you want to do something that involves the system (aside from file operations). That's an advantage IMO, since the default modules are quite good and allow for some nice cross-platform capabilities. However, if the redirection operators and pipes are what make you think that way, you should know that MS-DOS (and WinNT's DOS shell) does handle pipes and redirection. Perhaps not as powerfully as *NIX, but it does. (however, I would appreciate it if the Python standard distribution came with a "real" XML parser, 'cause DOM and SAX just plain suck -- by the way, thanks guys, I tried dom4j on my Java project and it changed my life) So here comes me, the guy who installed Linux once, failed to see the big deal and uninstalled it. Up until 3 months ago, my comp was used for gaming, pure and simple, me being a certified Day of Defeat freak, and so Windows has always best served my purpose. Now, I want to programme, so I have to learn Unix conventions to use a crossplatform language! It's like asking *nix users to sign a Microsoft EULA!! (Well, not as bad, but still as anathemic.) Well, in Perl's defense, Windows does implement a fairly large part of the POSIX standard. And believe me. I'm a UNIX user (Mac OS X is my primary OS, but I also use Windows and Linux on a fairly regular basis). Perl doesn't make any more sense to me than when I was still a Windows-only guy. How's Ruby? I bookmarked the homepage, but never got around to looking at it. Very, very nice. Cleanest object-orientedness I ever saw in a language (not that I have that much experience -- people like Alan would probably be better judges than me on this). I find it more elegant than Python, however I end up using Python anyway because Ruby has a huge flaw: it's Japanese (AFA
Re: [Tutor] Are you allowed to shoot camels? [kinda OT]
On Feb 3, 2005, at 09:48, Alan Gauld wrote: Pythons lambda feature is a bare minimum (and Guido wants to remove it!). Does he? Damn, just when I was learning functional programming! (in Haskell, if you're curious ^^) Yes the Japanese thing is an issue. THere are a few English books now, and the original one by Thomas and Hunt is free on the web. A little bit outdated, however. Ruby lacks a proper series of O'Reilly books; last time I checked the only one available was "Ruby in a Nutshell", which is a few years old and covers Ruby 1.6 (2 versions behind the current one). What Matz needs to do IMO is to gather a couple of the l33test Ruby hackers in the world in a nice house in the Japanese countryside, pick a cool-looking animal (what about an eastern dragon?), and sit down with them to write a thousand-page "Programming Ruby". is a thing of beauty compared to Perl for OO! In fact I actually don't mind VB OOP at all, especially in its .NET variant which includes inheritance and polymorphism. But Perl OOP is a hideous bodge. I haven't tried VB.NET (and don't intend to, I don't like BASIC-style languages), so I can't comment on this. But unfortunately built very badly as an OOP environment. Its more accurate to call it a class based language since its perfectly possible to build a Java program with no objecs but lots of classes! I'd go so far as to say that if you followed Java's lead on OOP you would pick up some very bad OO habits and write code that was not really very OOP at all! Thats not to say you can't write good OO code in Java just that Java does little to encourage it. You need to read a good OO book, like BRuce Eckels Thinking IN... series) to see how to do it properly! Well, of course, it all depends on how you're learning it. I'm sure there are some C tutorials out there that teach you (and encourage you) to use GOTO statements. :-D Me? I learnt Java by reading Eckel's "Thinking in Java" (and then followed with Wigglesworth/McMillan's "Java Programming: Advanced Topics"). I agree with you: it's an excellent book, that encourages good coding style and proper OOP. And whats worse is that there are few native code compilers for Java. The JVM thing is a big hype factor IMHO. We've been writing C/C++ programs for years that ran on Windows/Unix and IBM boxes with only minor #ifdefs inserted. The performance (and hence costs for servers!) differences are huge! Its no coincidence that 2 of the biggest supporters of Java (IBM and Sun) are hardware vendors! Agreed. I'm no compiler programmer, but it seems to me that they could just have written a nice cross-platform API and then platform-specific compilers, while keeping the specification of the language intact (i.e. platform-independent endian-ness, type sizes, etc.). The reasoning behind the JVM is that you don't need to recompile your code to run it on a different platform. But most existing Java projects have platform-specific versions, if only to make the GUI (try to) look native. You can spot a Java app from a hundred meters away. (then again, the same critic could be made of Python's and Perl's "standard" GUI toolkits) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] got it
On Feb 3, 2005, at 18:17, alieks laouhe wrote: So far I really like python...alot. it's so intuitive I started trying to learn c but it's lack of intuitive string handling made me shudder... so, i tried perl and it was a breath of fresh air after c. then i stumbled upon python. it's the most intuitive yet. C is very good for a number of things (chief among those: speed). But string manipulation is definitely not one of them. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Are you allowed to shoot camels? [kinda OT]
On Feb 3, 2005, at 22:21, Smith, Jeff wrote: Perl and Python both resist the introduction of a switch statement which I (and many others) feel is the most elegant way to express what it does. I echo that. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Are you allowed to shoot camels? [kinda OT]
On Feb 3, 2005, at 23:19, Alan Gauld wrote: Sean, what book/tutor are you using for Haskell? I learned it from "The Haskell School of Expression" which was OK but very graphics focused, I'd be interested in recommended second source on Haskell. I'm not Sean, but I'm using Simon Thompson's "Haskell: The Craft of Functional Programming", which I find quite good. However, it's a bit odd, in that it almost reads like a mathematics book, which is something you may or may not like. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Are you allowed to shoot camels? [kinda OT]
On Feb 3, 2005, at 23:41, Jeff Shannon wrote: (But then, at my job I'm stuck using a horrible Frankenstein's monster of a proprietary language on a daily basis, so I can't help but believe that there's plenty more awful languages around that didn't happen to be "rescued" from oblivion by an accident of history...) Yeah. Sometimes I read a little bit of Wikipedia's "Esoteric Programming Languages" page, and some of them just leave me in awe. Brainfuck (and its variant Ook!) and INTERCAL ("GOTO is considered harmful, so we removed it -- INTERCAL uses COME FROM instead") are already quite impressive, but the very idea of Befunge makes my brain want to explode. Especially that extension to the language that allows one to write N-dimensional programs. :D -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Are you allowed to shoot camels? [kinda OT]
On Feb 3, 2005, at 23:41, Alan Gauld wrote: The reasons for the K&R style of brace winning is to do with the way the brain process structure and despite the subjects stated preference for the 'Pascal' style they still had lower perception scores. Little nit-picking here: if(foo) { bar(); } Is not K&R style, but Allman style. K&R style (also known as One True Brace Style or 1TBS) is this: if(foo) { bar; } -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] This Deletes All my Files
On Feb 4, 2005, at 06:39, Chad Crabtree wrote: I've tried this and I cannot figure out why this does not work. I figure this has something to do with order of operations. I figured someone would know exactly why it doesn't work. Wouldn't this start inside parens then from left to right? open(item,'w').write(open(item,'r').read().replace(' ','')) I tried this on the shell just trying to do some quick text replacement because I could figure out how to get awk to do it, and I didn't want to spend 5 hours RTFM. I got it to work by breaking it up to several statements, but I would like to know. It's quite easy: evaluation starts from left to right. The program opens item for writing (thus deleting it), creating a file object, then executes its write method on the argument in the parens. However, since at that point item is now empty, there is nothing to read from. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Are you allowed to shoot camels? [kinda OT]
On Feb 4, 2005, at 09:09, Alan Gauld wrote: Correct. The style you show (which I called Pascal style) is the one that doesn't work. K&R style if(foo) { bar; } Is the one that won the shootout. With the outsider(which I dont know a name for!) beating both... if (foo) { bar; } According to the Jargon file, this one is called Whitesmiths style. I tend to use Allman style myself, but given the code completion, spellchecking, etc. in modern IDEs, I suspect it's become more a question of personal preference than anything else. A bit like if(foo) versus if (foo), and whether or not to use braces for single-line blocks. (the latter issue being why I think The Whitespace Thing is an instance of Best Thing Ever(TM)) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hex to Str - still an open issue
On Feb 6, 2005, at 08:59, Liam Clarke wrote: Ah, yeah, gotta get me one of those textbooks. (Wait a minute, that would mean, my approach wasn't the textbook approach... /me salvages a little pride.) While I jest somewhat, that highlights a serious deficiency in my education that becomes more and more apparent, which is in maths. Sheesh, if I'd known I wanted to use maths for something I enjoyed, I would've paid attention in class. But the remainder thing - would this be why we read binary the way we do? 4 is 001 (on a continuum of 2^0 to 2^n), but using the above approach we get 100. Regards, Liam Clarke Yes, it is 100. The most significant bit (i.e. the highest power of 2) is on the left, just as the most significant digit (matching the highest power of 10) is on the left when representing base-10 numbers: 415 is 4*10^2 + 1*10^1 + 5*10^0. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept)
On Feb 10, 2005, at 03:07, Ismael Garrido wrote: Danny Yoo wrote: ### def f(a,L=[]): if L==[5]: print 'L==[5] caught' print L print 'resetting L...' L=[] L.append(a) return L ### Now I'm dizzy... I can't understand why there are two "L"! L is a local variable of the function, right? (I can't imagine it being anything else) Then if I reassign L to something, why doesn't it keep that change till next run? At least, it keeps the values in the list.. so it should keep the reassignation, no? I'm completly puzzled :-S It's not L you have to look at but the default value itself. L is local to the function and recreated each time you run it. The default value, however (which has no name, so I'm gonna call it "defVal"), is static (in the Java/C++ sense of the word -- it's only created once). The first time you run the function, defVal is set to [] and then it is assigned to L (as in, L = defVal). Since defVal is a list, L and defVal are actually two names for the same variable. Thus, when you append something to L, it is appended to defVal as well. However, when you do L = [], you're binding the name L to another variable (which you create on the spot). But the name defVal is still bound to the same variable! Thus, when you run the function again, you get defVal as you left it. # Let's consider that defVal == [5] (say, you've already called f(5)) and call f(10): if L == [5]: # L == defVal == [5] (they are the same variable) L = [] # Re-binding the name: a new var is created. L == []; defVal == [5] L.append(a) # L == [10]; defVal == [5]. See what I mean? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hex to Str - still an open issue
On Feb 10, 2005, at 05:43, Johan Geldenhuys wrote: I am not so clued up on the 'base 2' and 'base 8' stuff. Care to explain that a little? Usually, we use base 10 numbers, that is, numbers that can be represented with 10 symbols (0, 1, 2, 3, 4, 5, 6, 7, 8, 9). Binary, or base 2, represents all the numbers with only 2 symbols (0 and 1), whereas octal (base 8) uses 8 (0 to 7) and hexadecimal (base 16) uses 16 (0 to 9 then A to F). In binary, 0b10 = 2, and 0b100 = 4. In octal, 010 = 8 and 0100 = 64. In hexadecimal, 0x10 = 16 and 0x100 = 256. Is that clearer now? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Perl Symbology (was: Are you allowed to shoot camels?)
On Feb 10, 2005, at 19:50, Bill Mill wrote: so "#{} . Here, [symbol] refers to the scope(?) of the variable. See the discussion between me and Alan on this topic a while ago -- the use of these symbols being his main criticism of Ruby. foo is a local variable $foo is a global variable @foo is an instance variable @@foo is a class variable FOO is a constant (which can be modded into global, instance or class with the appropriate use of $, @ or @@) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] calling an external program
On Feb 14, 2005, at 10:37, Lobster wrote: - I am trying to call up an external program with something like a "Shell" command - can not find a way of doing this (in windows) Any hints? What about os.system('your_command_here')? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problems with test cgi script on windows XP/Apache
On Feb 14, 2005, at 22:18, Liam Clarke wrote: Windows, she is a woman, and woman are mysterious in their little quirks. Unfortunately, you cannot divorce her, for she controls your software and you really need DirectX if you want to play Sid Mier's Pirates! Actually, you can find Atari ST and Amiga emulators for pretty much any system nowadays. :-p -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] newbie OSX module path question
On Feb 15, 2005, at 02:38, Mike Hall wrote: Ok, I've got it working. The environment.plist file wants a path beginning with /Users, not /Local_HD. So simple! Thanks everyone. Yeah, the system hard drive on Mac OS X (which is seen as "Macintosh HD", or in your case "Local HD" in the Finder) is mounted as the root of the filesystem. IOW, it's referred to as /, not /Macintosh HD. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] count words
On Feb 15, 2005, at 17:19, Ron Nixon wrote: Thanks to everyone who replied to my post. All of your suggestions seem to work. My thanks Ron Watch out, though, for all of this to work flawlessly you first have to remove all punctuation (either with regexes or with multiple foo.replace('[symbol]', '')), and to remove the case of each word (foo.upper() or foo.lower() will do). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Basic terminology
In a slightly more generic fashion (everybody started dropping examples), the goal of an integer (euclidian) division (say, a / b) is to express an integer as such: a = b * quotient + remainder Where all the numbers used are integers, and 0 <= remainder < b. When you perform integer division in Python, a / b (a // b in 2.4+) gives you the quotient, and a % b gives you the remainder. See the other posts for examples of use :p -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Queued threads
On Feb 16, 2005, at 01:58, Bernard Lebel wrote: Now, I have a list of "jobs", each job being a windows bat file that launches an executable and performs a rendering task. So I have this queue of jobs, and would like to launch one only when the previous one has finished, and in a separate window. So far I have not been having much success with simple stuff: from threading import Thread def mainFunction(): print 'function print' return 1 for i in range( 0, 3 ): oThread = Thread( target=mainFunction ).start() if oThread == 1: print 'sleeping 3 seconds' time.sleep( 3 ) In this example, 'sleeping 3 seconds' not returned, and each thread is started without any waiting. I'm looking at the various threading module details in the library but I have to admit that, well, I'm a bit at loss here. Okay, so basically, what you want to do is: - Start the first bat file. - Wait for it to finish. - Start the second bat file. - Wait for it to finish. - Start the third bat file. - Wait for it to finish. This just begs the following question: why are you even using threads to do that? This is perfectly sequential, with no element of simultaneity whatsoever... -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Queued threads
On Feb 16, 2005, at 02:36, Liam Clarke wrote: I'm sorry, but when does oThread get the value 1? If you're testing for it's existence via a True/False thing, try if oThread: But otherwise, I'm not sure what you're expecting to get. Once again, you hit the spot, Liam. It seems that a Thread object evaluates to False once it's terminated. That's probably what you're looking for, Bernard, my "threads won't be of any use here" argument notwithstanding. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trivia program.
On Feb 16, 2005, at 10:26, . Sm0kin'_Bull wrote: it prints like... John GoodmanJohn GoodmanJohn GoodmanJohn GoodmanJohn Goodman But i want to print it like... John Goodman John Goodman John Goodman John Goodman John Goodman How can I do it? Try replacing the called = name * 5 line with: if not name.endswith(' '): called = ((name + ' ') * 5).strip() else: called = (name * 5).strip() -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problem in making calulator
On Feb 17, 2005, at 23:11, . Sm0kin'_Bull wrote: I wrote this to add 2 numbers... print "Please input data" number1 = int(raw_input(" ")) number2 = int(raw_input("+ ")) total = number1 + number2 print total raw_input("") I want to make output like this... 1 + 1 = 2 But, actually... it looks like this... 1 + 1 2 Do you really need to do it as the user enters the numbers? Aside from being a little bit confusing for him, it'd require playing around with bizarre special terminal control characters to go back one line -- every time the user hits Enter to validate his input, the newline character is echoed to the terminal and the cursor goes down one line. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] killing a thread
On Feb 22, 2005, at 23:08, Bill Mill wrote: If I recall correctly, there is not a direct way. Instead, you're going to want to have your worker thread check a queue it shares with the parent every so often to see if the supervisor thread has sent a "quit" message to it. Peace Bill Mill bill.mill at gmail.com Using "direct" killing methods is not safe, because you never know at which point of its execution you terminate the thread. That's a Bad Thing(TM). So instead, the Right Thing is to implement an end() method in the object you're using as a thread. That end() method just sets a flag (say, isToTerminate) to True. Since the thread is running a loop, all you then have to do is have it check the isToTerminate flag at the beginning of each loop. If it's True, exit the loop (thus terminating the thread as it reaches the end of its run() method). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Fwd: [Tutor] threads
Some day I'm actually going to learn how to hit the "Reply All" button. I swear. Begin forwarded message: From: Max Noel <[EMAIL PROTECTED]> Date: February 23, 2005 18:42:37 GMT To: Shitiz Bansal <[EMAIL PROTECTED]> Subject: Re: [Tutor] threads On Feb 23, 2005, at 17:50, Shitiz Bansal wrote: Hi, I am trying to build a traffic network simulator using python, for my degree project. I need to run at least 5-6000 cars simultaneously.I wanted to run each car in a separate thread. Mmh... Sounds like a bad design decision to me. This doesn't scale up well, slows your system down to a crawl (especially if it's single-CPU), and some vehicles may never get to act if your OS doesn't have an efficient scheduler. Not to mention that due to the way threads are run, you probably won't ever get twice the same result when running a given simulation multiple times with the same parameters. Instead, you should fake it: have one thread running for all the cars. This thread has a for loop that iterates over all the cars and makes each of them "step". Coincidentally, I'm writing something that's more or less similar for my final-year project at Uni: a crowd simulation in a shopping center. I released the code under the GPL on Sourceforge (I've become a CVS addict), which you can find at http://sourceforge.net/projects/gmof/ . It's Java, not Python, but it's well-commented and written in a readable way (or at least I like to think so). Feel free to examine it. What you're looking for, I guess, is the run() method in the Mall class. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" -- maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading from stdin
On Mar 1, 2005, at 22:08, Nick Lunt wrote: The way I did this was to use sys.stdin.readlines() to get the output from the pipe. Here is the program: [code] import sys, glob args = sys.stdin.readlines() # found on the net pat = sys.argv[1] for i in args: if (i.find(pat) != -1): print i, [/code] My question is am I getting the output from the pipe in the correct way ? The way Im doing it works (so far) but should I be doing it another way ? I don't think you are. You're using readlines(), which means your program won't execute until ps terminates. UNIX philosophy is to have programs start acting as soon as possible -- in that case, as soon as the first line is available. You should be reading sys.stdin as an iterator (same thing you'd do for a file): import sys for line in sys.stdin: # do stuff with that line of input -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Make a .exe
On Mar 4, 2005, at 09:26, David Holland wrote: It Completed with these errors :- The following modules appear to be missing {'AppKit', 'Foundation', 'objc'] Now that's really weird. AppKit and Foundation are Mac OS X frameworks, and objc stands for Objective-C, the language in which they're written and which you're supposed to use to develop applications that use them. However, since you're on a Windows box, I have no idea why Python is trying to involve them. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 2d list matrix 7 x 75 problem
On Mar 6, 2005, at 09:49, Dave S wrote: so I thought I would be clever with ... >>> a=[0]*5 >>> a [0, 0, 0, 0, 0] >>> b=[a[:]]*5 same problem. It seems realy simple but how do I generate a 7 x 75 list matrix ? Dave Try this: >>> a = [''] * 5 >>> b = [a[:] for i in range(5)] >>> b [['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', '']] >>> b[0] is b[1] False List comprehensions. Gotta love 'em... ^^ Is there a more elegant solution to if string == 'sun' or string == 'mon' or string == 'tue' or string == 'wed' or string == 'thu' or string == 'fri' or string == 'sat': Yes, there is. if a in ('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'): (also works with a list or a dictionary) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help
On Mar 7, 2005, at 16:46, Kent Johnson wrote: Gregory Sexton wrote: Thanks for the help! Sorry for the trivial questions, but I guess we all have to start somewhere. Beginning python student, OS Windows XP,using Python 2.4. Also novice to programming. I cant get the "/a" command to work. I don't know what the "/a" command is, please give more details. I find it extremely unlikely that Python, even in its Windows incarnation, support a "/a" switch, or any slash switch for that matter. Python is a UNIX program -- its switches start with one or two dashes, as the slash is the directory separator. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HELP: subclass of int
On Mar 8, 2005, at 22:10, Shidai Liu wrote: Hi all, I'll sum up a question as following: def int5(): '''return 5''' return 5 class my_int(int): def __init__(self): self.id = int5() int.__init__(self, self.id) # FIXME: this line doesn't work I'm not absolutely confident with inheritance in Python (nearly all of my serious OO work has been in Java), but shouldn't the call to the superclass's constructor be the very first statement of the subclass's constructor? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Acessing files in Windows 2000
On Mar 8, 2005, at 22:26, John Purser wrote: Try c:\\my documents\\memo.txt John Or even better, c:/My Documents/memo.txt In most programming languages, you can use the slash as a path separator under Windows as well. It'll save you a lot of trouble. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Acessing files in Windows 2000
On Mar 9, 2005, at 01:13, Shitiz Bansal wrote: Whats worse, I had found that the rule is different for different versions of windows.Just proves what we all know...Windows Suxx. The Windows OS sucks! And blows! At the same time! (name the reference, get a cookie ;) ) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Terminology WAS Whats so good about OOP ?
On Mar 13, 2005, at 18:38, Brian van den Broek wrote: Thanks for the explanation, Sean. The reference to grammatical theory here does seem to make sense. But, relying on correspondence between the technical terms in programming/comp. sci. and other fields with similar terminology can get in the way, too. I've a background in formal logic; it took me some effort to stop being upset that in Pythonic programming parlance get_a_random_element is a "function": Where I come from, the output of a function is determined by the input to the function. Well, actually, your being upset at that is the exact point of functional programming languages: in functional programming, the output of a function is determined by its input, and *only* its input. Therefore, there are no side-effects (variables being one) calling a function twice with the same arguments will *always* yield the same result. The only time this paradigm is broken is (of course) when dealing with I/O. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How do you use pydoc?
On Mar 15, 2005, at 00:28, [EMAIL PROTECTED] wrote: I have read but don't under stand how to use pydoc. here what i read can't figer out how to use it. pydoc is more or less a help browser. Think of it as "man for Python". If you need documentation on a module, just type "pydoc [module name]" at a command prompt. For example, if you want to know how the os module works, just type "pydoc os". Even better: if the modules you're writing use docstrings, then calling pydoc on your module will work automagically. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] what is the "path browser" used for?
On Mar 15, 2005, at 00:55, [EMAIL PROTECTED] wrote: What is the path browser for and all the sys.path's for? are these for copying and pasteing to help you on your program? No, sys.path (as explained by pydoc sys ;) ) is the module search path; that is, the list of the folders into which Python looks for a module when you try to import it. Oh, and on an unrelated topic, could you please turn off HTML in your e-mails? Blue text on green background is not very comfortable to read... Thanks! -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creating a tab delimited filename
On Mar 15, 2005, at 03:35, jrlen balane wrote: how am i going to change the filename automaticaly? for example: #every 5 minutes, i am going to create a file based on the data above for i in range(100) output_file = file('c:/output' +.join(i) +'.txt', 'w') #guess this won't work output_file.writelines(lines) output_file.close() I'm not going to give you a complete solution because that'd spoil the fun, but you need to use the os.path.exists function (in the os module), which tells you if a file exists or not (no need to open it -- actually, your loop is dangerous: opening a file with "w" as the mode erases it). As for generating the file name, you've almost got it. Just remove that bizarre call to "join", cause that won't work, and replace your for loop with a while loop, so that you can break out of it when you've found the correct file name, not before or after. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] re.findall vs. re.search and re.match
On Mar 15, 2005, at 16:44, Ron Nixon wrote: Kent: The code is below. Here's the error message. Traceback (most recent call last): File "C:/Python24/reformat.py", line 5, in -toplevel- name = x.group(1) AttributeError: 'list' object has no attribute 'group' re.findall returns a list object (as the error message says). Use name = x[1] instead. (and be careful, numbering starts from 0, so this code may contain a Kenobi error). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] re.findall vs. re.search and re.match
On Mar 15, 2005, at 17:41, Ron Nixon wrote: Max: Thanks that seem to do the trick. One question though, how do you write a tuple out as a list to a new file like the example I have in my code Ron You mean, all the members of the list, separated by commas, with a new line at the end? Well, this may help you: >>> foo = map(str, range(10)) >>> foo ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] >>> print ",".join(foo) + "\n" 0,1,2,3,4,5,6,7,8,9 >>> -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor