Re: [Tutor] Has anyone ever tried to convert the textual output of thedis module to another language
>> Just curious. Googling for 'python "dis module" convert "another >> language" ' only got two hits. So maybe no one is trying it? I was >> just daydreaming about a native python compiler, and wondered how >> feasible it would be. > I hope that your true google search string doesn't contain the two single > quote on the outside... Nope. That was just to set it off from the rest of the sentence in the email. > So basically any website that contains 'dis module', which stands for what > by that way? It's python's included disassembler for its own virtual machine. It's interesting to play around with. Try: import dis dis.dis(name of some function you def'd in your program) Alan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Has anyone ever tried to convert the textual output of thedis module to another language
Just curious. Googling for 'python "dis module" convert "another language" ' only got two hits. So maybe no one is trying it? I was just daydreaming about a native python compiler, and wondered how feasible it would be. Well, from the way I understand the google search works, you would have to hit a website that contains *exactly* 'dis module' and\or *exactly* 'another language' and\or 'python' and\or 'convert' I hope that your true google search string doesn't contain the two single quote on the outside... That would mean the website would need to look for the whole string exactly. So basically any website that contains 'dis module', which stands for what by that way? Maybe you should try that without the quotes becase of this abbreviation that potential hits might not use. I guess what I'm trying to say is, try generalizing the search. Maybe other people call what you're asking for by a different name that you aren't including. Such searches aren't a really good way to judge the statistics of said projects due to the name idea etc. Okay, I'm done. Jacob ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "paused" graphic leaves a 'residue' when returning to game?
Hi Denise, Are you using Pygame?On 4/15/05, D. Hartley <[EMAIL PROTECTED]> wrote: Another quick question:I can pause and unpause the little game I created, and I have agraphic to display over top of the game screen when it is paused,which tells the user which key to press to unpause, right? It's set up the same way as my "game over" graphic. But in any case, when Iunpause, it leaves this "residue" of the "paused" text on the gamescreen. the moving game characters move over it and sort of wipe it out, but I have no idea why it's there or how to clear it!Has anyone else encountered a problem like this before? I can post thespecific code if that would be helpful. I've tried to clear thescreen, refresh, etc., and since the pause screen uses the same code as the game over screen I figured the former should not leave aresidue if the latter does not. Any suggestions for things to tryout, to fix this?Thanks a ton!~Denise___ Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor -- 'There is only one basic human right, and that is to do as you damn well please.And with it comes the only basic human duty, to take the consequences.' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: How can I avoid cut'n'paste in this case?
Nigel Rowe xoxy.net> writes: > >> I have two modules, both define the same set of classes (with differing > >> implementations) and a number of utility functions that use those > >> classes. > >> The utility functions are identical (the differences I need are > >> abstracted in the classes), so they are cut'n'pasted into both files. How about putting all utility functions in a separate module and doing a "from P import *" or "from C import *" at the top of that module, depending on some command line parameter or whatever it is that determines which one should be imported? It's not elegant by any means, but at least you don't have to copy-paste code around any more and the changes to the existing code are minimal. > >> How can I refactor these modules to avoid the code duplication? I would say that the fact that there are two parallel implementations of the same classes with small differences is worrying as well. There should be an ancestor layer in there implementing common behavior. > Maybe I'm going too far, trying to eliminate the cut'n'paste, but I've > always thought it a bad smell. It does indeed smell of a maintenance nightmare waiting to happen :). The bad part is that it tends to get progressively worse. Imagine also what would happen if you'd get even more of those similar modules. Yours, Andrei ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: newbie intro to pickle
Lee Harr hotmail.com> writes: > Now my question is how do you keep people from just loading > the high score file with whatever scores they want? I'd say this is impossible particularly with Python, because cheaters could always look in the source and find out whatever you're doing to the scores and if they can't get around it, they can certainly feed that routine bogus scores and get valid (but cheated) score files. Cheating happens even with closed-source games. The only reliable way of scoring is to have an application which both runs and keeps scores on computers you control (i.e. an online in-browser game), without relying on cookies or any other form of client-side data. If you just want to keep casual tinkerers from playing with a plain text scores file, simple safeguards would suffice, like: - writing a MD5 hash of the scores list along with the scores themselves. If the scores are modified and the MD5 isn't, the two won't match. - implementing some trivial obsfucation (as opposed to real encryption) algorithm which you could apply to the data before writing it. You could for example use the zlib module for this (compress the result of pickle.dumps and decompress the string read from file before feeding it to pickle.loads). The result will look tremendously ugly and scary, plus it will save a few bytes in storage space if you're lucky :). - storing the scores in a bsddb (it can be modified by hand, but it looks quite scary and mistakes might lead to breakage) It's quite obvious though that no method is good enough if you attach any kind of value to high scores, by e.g. posting the highest scores on your webpage. Yours, Andrei ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: How can I avoid cut'n'paste in this case?
Kent Johnson wrote: > Nigel Rowe wrote: >> I have two modules, both define the same set of classes (with differing >> implementations) and a number of utility functions that use those >> classes. >> >> The utility functions are identical (the differences I need are >> abstracted in the classes), so they are cut'n'pasted into both files. >> >> A simplified concrete example (not what I'm doing, but it illustrates the >> point): >> >> -- C.py -- >> |class Comment: >> |def __init__(self, value): >> |self.value = value >> | >> |def __str__(self): >> |return "/* " + self.value + " */" >> | >> |# utility functions >> |import time >> |def stamp(): >> |return Comment(time.asctime()) >> >> >> -- P.py -- >> |class Comment: >> |def __init__(self, value): >> |self.value = value >> | >> |def __str__(self): >> |return "# " + self.value + "\n" >> | >> |# utility functions >> |import time >> |def stamp(): >> |return Comment(time.asctime()) >> >> >> How can I refactor these modules to avoid the code duplication? > > You could make stamp() a classmethod of a common base class like this: > > # CommentBase.py > import time > > class CommentBase(object): > def stamp(cls): # cls will be one of the Comment implementations > return cls(time.asctime()) > > stamp = classmethod(stamp) > > # C.py > from CommentBase import CommentBase > class Comment(CommentBase): > def __init__(self, value): > self.value = value > > > # Client code > from C import Comment > > c = Comment.stamp() # This becomes CommentBase.stamp(Comment) > print type(c), c.value > > > Kent Thanks Kent, that's an approach that wouldn't have occurred to me. Unfortunately it's not going to do the job for me, since it would require extensive changes to the client code. ie. import C as lang lang.stamp() would need to be re-written as import C as lang lang.Comment.stamp() The other problem is that there are a LOT of classes, and some of the utility functions make use of multiple classes. eg. (not real code) class this: ... class that: ... class other: ... class something: ... def utl_1(): x = this() y = other() def utl_2(): z = this() foo = something() def utl_3(): a = something() b = other() (You get the idea.) Maybe I'm going too far, trying to eliminate the cut'n'paste, but I've always thought it a bad smell. -- Nigel Rowe A pox upon the spammers that make me write my address like.. rho (snail) swiftdsl (stop) com (stop) au ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] TKinter and things over Linux
On Sat, Apr 16, 2005, joe_schmoe wrote: >Alberto Troiano wrote: >>Hi everyone >> >>Sorry to bother you again but I don't know where else to go >> >>I recently switch to Linux Red Hat AS 3.0 because I have to make a >>daemon to run in this OS and I'm having a few problems >> >>I've struggle to replace Python 2.2(machine default) to 2.3.4 (tough but >>could) >> >>Now I want to program a GUI with Tkinter but when I put the sentence >>from TKinter import *, it tells me that it doesn't find the module >>Tkinter. I have downloaded Python 2.3.4 from python.org and follow the >>steps. The build process for python will pick up installed libraries for various components (e.g. Berkeley database, Tk, etc.), so if you don't have Tkinter on your system, and you built python yourself, it probably means that you don't have the necessary Tk/TCL development libraries installed on the system. Careful perusal of the output of the build is necessary to see what libraries have been built, and which were skipped. I normally build using ``make 2>&1 | tee makelist'' which puts all the output in the file makelist which I can then examine when the make is complete. >>Secondly I want to know how to run the .py programs and which is the >>extension of a GUI in Linux (I know that for Windows is .pyw but it >>doesn't know what are these in Linux) Python scripts should Just Run(tm) whether they have a .py extension or not on a Linux box. Linux, and most *nix flavours don't depend on the file suffix to determine what type of file it is, but generally look at the first few bytes of the file (if a text file starts with ``#!'' the rest of the line is taken to be the command to run the script. ... Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ When you have an efficient government, you have a dictatorship. -- Harry Truman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] TKinter and things over Linux
Alberto Troiano wrote: Hi everyone Sorry to bother you again but I don't know where else to go I recently switch to Linux Red Hat AS 3.0 because I have to make a daemon to run in this OS and I'm having a few problems I've struggle to replace Python 2.2(machine default) to 2.3.4 (tough but could) Now I want to program a GUI with Tkinter but when I put the sentence from TKinter import *, it tells me that it doesn't find the module Tkinter. I have downloaded Python 2.3.4 from python.org and follow the steps. Secondly I want to know how to run the .py programs and which is the extension of a GUI in Linux (I know that for Windows is .pyw but it doesn't know what are these in Linux) Then is there an IDLE for Linux so I can run the program without having to go to the shell Thanks a lot Regards Alberto Hi everyone I recently switch to Linux Red Hat AS 3.0 because I have to make a daemon to run in this OS and I'm having a few problems I've struggle to replace Python 2.2(machine default) to 2.3.4 (tough but could) Now I want to program a GUI with Tkinter but when I put the sentence from TKinter import *, it tells me that it doesn't find the module Tkinter. I have downloaded Python 2.3.4 from python.org and follow the steps. Secondly I want to know how to run the .py programs and which is the extension of a GUI in Linux (I know that for Windows is .pyw but it doesn't know what are these in Linux) Then is there an IDLE for Linux so I can run the program without having to go to the shell Thanks a lot Regards Alberto Hi Alberto I am curious why you are using RH3.0 - be aware that many of the system calls of later Python releases may expect libraries that aren't part of the distro you are using. I couldn't say for sure, but I'd anticipate some limits to backwards compatibility. Anyway, in answer to your question. To find the Tkinter modules, you should probably enter "whereis tkinter" at the command line and then re-install Python with that in its path, or re-install TKinter with the python installation path. RH has a tendency to Red Hat-ise the file hierarchy somewhat, so it could just be a case that one or the other doesn't know how to find its libraries. I couldn't tell you what the extensions for GUIs are. Perhaps www.python.org might have some clues for that. However, to run python programs from the shell, if you have added the she-bang (the #!/bin/sh part) as the first line of your program, then just enter python my_program.py at the prompt and watch it run!! I think that idle tends to be the native IDE for python, but there are others you could use, some of which might provide you with a GUI IDE so you don't have to use the command line. In the interim however, just enter idle at the command line and a new window will be spawned with the following: = Python 2.4.1 (#1, Apr 6 2005, 09:36:35) [GCC 3.3.4] on linux2 Type "copyright", "credits" or "license()" for more information. Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. IDLE 1.1.1 >>> = To use a text editor just enter ctrl + n in this window and then to run it, save it as *.py and hit F5 to run in the idle window. HtH /j ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: Eceptions
> From: "Brian van den Broek" <[EMAIL PROTECTED]> > To: "Diana Hawksworth" <[EMAIL PROTECTED]> > Cc: > Sent: Saturday, April 16, 2005 3:14 PM > Subject: Re: [Tutor] exceptions > > Diana Hawksworth said unto the world upon 2005-04-15 22:25: > > > Hello list, > > > > > > I have been trying to trap a string entry by raising an exception. The > code follows - but the exception is never raised. What am I doing wrong? > > > > > > TIA Diana > > > > > > try: > > > > > > self.guess = int(self.num_ent.get()) > > > > > > self.num_ent.delete(0,END) > > > self.num_ent.focus_set() > > > > > > > > - Ignored: > > > if self.guess < self.number: > > > message = str(self.guess) + " is too low. You need to > guess higher" > > > > > > if self.guess > self.number: > > > message = str(self.guess) + " is too high. You need to > guess lower" > > > > > > if self.guess == self.number: > > > message = str(self.guess) + " is the correct number!" > > > self.message_txt.config(state = NORMAL) > > > self.message_txt.config(state = DISABLED) > > > > > > self.message_txt.config(state = NORMAL) > > > self.message_txt.delete(0.0, END) > > > self.message_txt.insert(0.0, message) > > > self.message_txt.config(state = DISABLED) > > > > > > > > > except(ValueError): > > > message = str(self.guess) + " is not a number. Please try > again!" > > > > > > > Hi Dianna, > > > > What are you expecting to raise the ValueError? It looks to me like it > > must be the line: > > > > self.guess = int(self.num_ent.get()) > > > > But, if that is so, then the assignment to message in your except > > clause won't work, as self.guess won't have been assigned. > > > > I'm no expert, so I may be missing something, but I wouldn't be > > surprised if your num_ent.get() has details that are pertinent. What > > does that method return? > > > > And, while I'm writing, I'd suggest rewriting your lines like: > > > > message = str(self.guess) + " is the correct number!" > > > > in this form instead: > > > > message = "%s is the correct number!" %self.guess > > > > The almost irrelevant benefit is that it is faster. The big plus is > > string formatting is so handy, that I think it helps a lot to get used > > to using it in most cases, even those that are easy to handle with > > string concatenation as you have done. > > > > Best, > > > > Brian vdB > > > > > Thanks for your reply Brian. The num_ent.get() method returns a number. > Actually, it is an Entry box that returns a string, that I then convert to > an integer. What I would like to do, is, if a user enters a string, to have > the program return an exception. At the moment it just blithely carries on > as if the string that was entered was in fact an integer, and compares that > entered string to a random number! > > Thanks for the hint on string formatting! I had forgotten about that! Been doing > this for a month only!!! > > Thanks again. Diana > > > > - Done. > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How can I avoid cut'n'paste in this case?
Nigel Rowe wrote: I have two modules, both define the same set of classes (with differing implementations) and a number of utility functions that use those classes. The utility functions are identical (the differences I need are abstracted in the classes), so they are cut'n'pasted into both files. A simplified concrete example (not what I'm doing, but it illustrates the point): -- C.py -- |class Comment: |def __init__(self, value): |self.value = value | |def __str__(self): |return "/* " + self.value + " */" | |# utility functions |import time |def stamp(): |return Comment(time.asctime()) -- P.py -- |class Comment: |def __init__(self, value): |self.value = value | |def __str__(self): |return "# " + self.value + "\n" | |# utility functions |import time |def stamp(): |return Comment(time.asctime()) How can I refactor these modules to avoid the code duplication? You could make stamp() a classmethod of a common base class like this: # CommentBase.py import time class CommentBase(object): def stamp(cls): # cls will be one of the Comment implementations return cls(time.asctime()) stamp = classmethod(stamp) # C.py from CommentBase import CommentBase class Comment(CommentBase): def __init__(self, value): self.value = value # Client code from C import Comment c = Comment.stamp() # This becomes CommentBase.stamp(Comment) print type(c), c.value Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Has anyone ever tried to convert the textual output of the dis module to another language
Just curious. Googling for 'python "dis module" convert "another language" ' only got two hits. So maybe no one is trying it? I was just daydreaming about a native python compiler, and wondered how feasible it would be. Alan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How can I avoid cut'n'paste in this case?
Greetings all, I hope someone can help me. I have two modules, both define the same set of classes (with differing implementations) and a number of utility functions that use those classes. The utility functions are identical (the differences I need are abstracted in the classes), so they are cut'n'pasted into both files. A simplified concrete example (not what I'm doing, but it illustrates the point): -- C.py -- |class Comment: |def __init__(self, value): |self.value = value | |def __str__(self): |return "/* " + self.value + " */" | |# utility functions |import time |def stamp(): |return Comment(time.asctime()) -- P.py -- |class Comment: |def __init__(self, value): |self.value = value | |def __str__(self): |return "# " + self.value + "\n" | |# utility functions |import time |def stamp(): |return Comment(time.asctime()) How can I refactor these modules to avoid the code duplication? I tried: |class Comment |... |from utils import * where utils.py contains the functions, but when I try to use C.stamp(), I get: >>> import C as lang >>> lang.stamp() Traceback (most recent call last): File "", line 1, in ? File "utils.py", line 3, in stamp return Comment(time.asctime()) NameError: global name 'Comment' is not defined Any suggestions how I could (for instance) emulate a #include "utils.py" or any other technique to eliminate the dreaded cut'n'paste? Thanks. Nigel -- Nigel Rowe A pox upon the spammers that make me write my address like.. rho (snail) swiftdsl (stop) com (stop) au ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] distutils problem
On Sat, Apr 16, 2005 at 12:58:33PM -0400, Paul Tremblay wrote: > I have written a script that is available at: > > https://sourceforge.net/projects/rtf2xml/ > > This script has gotten about 1600 downloads and I have not got many > bug complaints. However, recently I got the bug complaint listed > below. > > This bug--if it is one--seems to be related to the person't version > and setup of python rather than my script. Can anyone make sense of > it? > > Thanks > > Paul > > forwarded message > = > > I tried to set this up according to the documentation at > > http://rtf2xml.sourceforge.net/docs/installation.html#install-rtf2xml-module > > But when I try to run > >python setup.py install > > (both as user and as root) > > I get > > xps8250:/home/chuck/rtf2xml-1.0a# python setup.py install > > running install > > error: invalid Python installation: unable to open > /usr/lib/python2.3/config/Makefile (No such file or directory) > > According to apt-get, I do have Python correctly installed. I also did > this: > > xps8250:/home/chuck/rtf2xml-1.0a# python > > Python 2.3.5 (#2, Mar 26 2005, 17:32:32) > > [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 > > However, in /usr/lib/python2.3/ there is no subdirectory for > /config/Makefile, nor any Makefile in any python subtree. I've looked > around the Python online documentation, but haven't found any > clues. Any suggestions? > > Okay, I just did a web search (which I should have done before I posted this!) and discovered that the problem is probably due to the user not having the development package of python installed as well. I posted him and will wait to hear from him. Paul -- *Paul Tremblay * [EMAIL PROTECTED]* ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] distutils problem
I think he may need to install python-devel. > I have written a script that is available at: > > https://sourceforge.net/projects/rtf2xml/ > > This script has gotten about 1600 downloads and I have not got many > bug complaints. However, recently I got the bug complaint listed > below. > > This bug--if it is one--seems to be related to the person't version > and setup of python rather than my script. Can anyone make sense of > it? > > Thanks > > Paul > > forwarded message > = > > I tried to set this up according to the documentation at > > > http://rtf2xml.sourceforge.net/docs/installation.html#install-rtf2xml >-module > > But when I try to run > >python setup.py install > > (both as user and as root) > > I get > > xps8250:/home/chuck/rtf2xml-1.0a# python setup.py install > > running install > > error: invalid Python installation: unable to open > /usr/lib/python2.3/config/Makefile (No such file or directory) > > According to apt-get, I do have Python correctly installed. I also > did this: > > xps8250:/home/chuck/rtf2xml-1.0a# python > > Python 2.3.5 (#2, Mar 26 2005, 17:32:32) > > [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 > > However, in /usr/lib/python2.3/ there is no subdirectory for > /config/Makefile, nor any Makefile in any python subtree. I've looked > around the Python online documentation, but haven't found any > clues. Any suggestions? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] distutils problem
I have written a script that is available at: https://sourceforge.net/projects/rtf2xml/ This script has gotten about 1600 downloads and I have not got many bug complaints. However, recently I got the bug complaint listed below. This bug--if it is one--seems to be related to the person't version and setup of python rather than my script. Can anyone make sense of it? Thanks Paul forwarded message = I tried to set this up according to the documentation at http://rtf2xml.sourceforge.net/docs/installation.html#install-rtf2xml-module But when I try to run python setup.py install (both as user and as root) I get xps8250:/home/chuck/rtf2xml-1.0a# python setup.py install running install error: invalid Python installation: unable to open /usr/lib/python2.3/config/Makefile (No such file or directory) According to apt-get, I do have Python correctly installed. I also did this: xps8250:/home/chuck/rtf2xml-1.0a# python Python 2.3.5 (#2, Mar 26 2005, 17:32:32) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 However, in /usr/lib/python2.3/ there is no subdirectory for /config/Makefile, nor any Makefile in any python subtree. I've looked around the Python online documentation, but haven't found any clues. Any suggestions? -- *Paul Tremblay * [EMAIL PROTECTED]* ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] TKinter and things over Linux
Hi everyone Sorry to bother you again but I don't know where else to go I recently switch to Linux Red Hat AS 3.0 because I have to make a daemon to run in this OS and I'm having a few problems I've struggle to replace Python 2.2(machine default) to 2.3.4 (tough but could) Now I want to program a GUI with Tkinter but when I put the sentence from TKinter import *, it tells me that it doesn't find the module Tkinter. I have downloaded Python 2.3.4 from python.org and follow the steps. Secondly I want to know how to run the .py programs and which is the extension of a GUI in Linux (I know that for Windows is .pyw but it doesn't know what are these in Linux) Then is there an IDLE for Linux so I can run the program without having to go to the shell Thanks a lot Regards Alberto Hi everyone I recently switch to Linux Red Hat AS 3.0 because I have to make a daemon to run in this OS and I'm having a few problems I've struggle to replace Python 2.2(machine default) to 2.3.4 (tough but could) Now I want to program a GUI with Tkinter but when I put the sentence from TKinter import *, it tells me that it doesn't find the module Tkinter. I have downloaded Python 2.3.4 from python.org and follow the steps. Secondly I want to know how to run the .py programs and which is the extension of a GUI in Linux (I know that for Windows is .pyw but it doesn't know what are these in Linux) Then is there an IDLE for Linux so I can run the program without having to go to the shell Thanks a lot Regards Alberto ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: newbie intro to pickle
> Now my question is how do you keep people from just loading > the high score file with whatever scores they want? > This is not to disparage a simple (and probably very useful) > high score file. It is just something that I have been thinking > about doing myself for quite a while, but I can never quite get > a grasp on how I would go about it. This is a recurring discussion in a lot of usenet newsgroups. The prevailing wisdom is: don't bother. Any way you come up with to keep it secret can be defeated. Period. Alan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: newbie intro to pickle
Pickling simply converts an object to a string (unpickling does the opposite, convert a string to an object). The dump() function writes the generated string directly to a file, but you can use the dumps() function to get the generated string as such and do something else with it (e.g. put it in a database, send it by mail, whatever). mylist = [1, 2, 34, 4.2, 'abc'] s = pickle.dumps(mylist) s # display the string "(lp0\nI1\naI2\naI34\naF4.2002\naS'abc'\np1\na." pickle.loads(s) [1, 2, 34, 4.2002, 'abc'] ... and just to complete the connection of dumps to dump, you could write the string out to a file yourself ... import pickle mylist = [1, 2, 34, 4.2, 'abc'] s = pickle.dumps(mylist) file_object = file('somefile.pickle', 'w') # I don't think there is a "standard" suffix file_object.write(s) file_object.close() _file_object = file('somefile.pickle') _s = file_object.read() _mylist = pickle.loads(still_s) _mylist [1, 2, 34, 4.2002, 'abc'] Now my question is how do you keep people from just loading the high score file with whatever scores they want? This is not to disparage a simple (and probably very useful) high score file. It is just something that I have been thinking about doing myself for quite a while, but I can never quite get a grasp on how I would go about it. Any thoughts? _ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sort a list into equal sized chunks
Klas Marteleur wrote: Hi I have wrestled with a problem since last weeks knapsack discussion. This is what i want, but i cant get it into a program. I have a sorted list (for example): aList = [10,9,8,7,6,5,4,3,2,1] I have a max value (for example): maxValue=11 I have another list: anotherList=[] After processing "aList" i want my "anotherList" to look like this: anotherList=[[10,1],[9,2],[8,3],[7,4],6,5]] were every element is as close to maxValue as possible. As someone noted, this problem is properly called the bin packing problem. If you google for "bin packing problem" there are a number of interesting references. This one is easy to read: http://www.ams.org/new-in-math/cover/bins1.html Finding the optimal partition is a hard problem. But for your purposes (sorting files onto DVDs) a simple greedy algorithm might be sufficient. Here is a simple implementation of a First Fit Decreasing algorithm: ''' Partition a list into sublists whose sums don't exceed a maximum using a First Fit Decreasing algorithm. See http://www.ams.org/new-in-math/cover/bins1.html for a simple description of the method. ''' class Bin(object): ''' Container for items that keeps a running sum ''' def __init__(self): self.items = [] self.sum = 0 def append(self, item): self.items.append(item) self.sum += item def __str__(self): ''' Printable representation ''' return 'Bin(sum=%d, items=%s)' % (self.sum, str(self.items)) def pack(values, maxValue): values = sorted(values, reverse=True) bins = [] for item in values: # Try to fit item into a bin for bin in bins: if bin.sum + item <= maxValue: #print 'Adding', item, 'to', bin bin.append(item) break else: # item didn't fit into any bin, start a new bin #print 'Making new bin for', item bin = Bin() bin.append(item) bins.append(bin) return bins if __name__ == '__main__': import random def packAndShow(aList, maxValue): ''' Pack a list into bins and show the result ''' print 'List with sum', sum(aList), 'requires at least', (sum(aList)+maxValue-1)/maxValue, 'bins' bins = pack(aList, maxValue) print 'Solution using', len(bins), 'bins:' for bin in bins: print bin print aList = [10,9,8,7,6,5,4,3,2,1] packAndShow(aList, 11) aList = [ random.randint(1, 11) for i in range(100) ] packAndShow(aList, 11) Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] TKinter and things over Linux
Hi everyone I recently switch to Linux Red Hat AS 3.0 because I have to make a daemon to run in this OS and I'm having a few problems I've struggle to replace Python 2.2(machine default) to 2.3.4 (tough but could) Now I want to program a GUI with Tkinter but when I put the sentence from TKinter import *, it tells me that it doesn't find the module Tkinter. I have downloaded Python 2.3.4 from python.org and follow the steps. Secondly I want to know how to run the .py programs and which is the extension of a GUI in Linux (I know that for Windows is .pyw but it doesn't know what are these in Linux) Then is there an IDLE for Linux so I can run the program without having to go to the shell Thanks a lot Regards Alberto ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: newbie intro to pickle
Andrei wrote: Pickling is also very useful when combined with the bsddb module, because you get a fast database which functions very much like a dictionary, and in which you can put anything you like, as long as you pickle it first. import bsddb mydb = bsddb.btopen('game.db') mydb['highscores'] = pickle.dumps(mylist) mydb['highestlevel'] = pickle.dumps(21) mydb['lastplayer'] = pickle.dumps('John Doe') mydb.close() mydb = bsddb.btopen('game.db') pickle.loads(mydb['lastplayer']) 'John Doe' You might be interested in the shelve module which essentially does this for you. With shelve your example would look like this: import shelve d = shelve.open('game.db') d['highscores'] = mylist d['highestlevel'] = 21 d['lastplayer'] = 'John Doe' Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] high score lists
Chris Smith wrote: high = [(1000,"Denise"), (945,"Denise"), (883,"Denise"), (823,"Grant"), (779,"Aaron"), (702,"Pete"), (555,"Tom"), (443,"Tom"), (442,"Robin"), (404,"Pete")] for score, who in high: col1 = str(score).rjust(10) col2 = who.rjust(20).replace(' ', '.') #replace spaces with dots print col1 + col2 ### --the output-- 1000..Denise 945..Denise 883..Denise 823...Grant 779...Aaron 702Pete 555.Tom 443.Tom 442...Robin 404Pete --end output-- Sweet. Note that in Python 2.4 you can write col2 = who.rjust(20, '.') instead of col2 = who.rjust(20).replace(' ', '.') #replace spaces with dots Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Sort a list into equal sized chunks
Hi I have wrestled with a problem since last weeks knapsack discussion. This is what i want, but i cant get it into a program. I have a sorted list (for example): aList = [10,9,8,7,6,5,4,3,2,1] I have a max value (for example): maxValue=11 I have another list: anotherList=[] After processing "aList" i want my "anotherList" to look like this: anotherList=[[10,1],[9,2],[8,3],[7,4],6,5]] were every element is as close to maxValue as possible. Can somebody give me a push in the back? Kind Regards Klas ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: exceptions
Diana Hawksworth optusnet.com.au> writes: > I have been trying to trap a string entry by raising an exception. The code follows - but the exception is > never raised. What am I doing wrong? I've snipped the code that is irrelevant to this question. > try: > self.guess = int(self.num_ent.get()) > except(ValueError): > message = str(self.guess) + " is not a number. Please try again!" Obviously it's hard to determine what's happening since I don't know that that get() returns, nor what you do with the message. Now let's play with that a bit in the interpreter: >>> try: ... guess = int('abc') ... except (ValueError): ... print 'not a number' not a number >>> try: ... guess = int('4') ... except (ValueError): ... print 'not a number' >>> try: ... guess = int('abc') ... except (ValueError): ... message = 'not a number' >>> print message not a number The first run demonstrates that the code is working. The second run shows that if your source doesn't return any invalid data, the exception will not be raised. The third run shows that the exception is triggered, but you will simply not notice it if you don't do anything with message. By the way, the third implementation contains a potential problem: if the message variable does not exist before the try-except and everything goes well, you'll get a NameError if you try to print it. Also if it does exist, it will need to be reset before the try-except, otherwise afterwards you won't know whether its value comes from the last try-except or from some time in the past. On a sidenote: recommended Python style is to use 4 spaces per indentation level. Yours, Andrei ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: newbie intro to pickle
D. Hartley gmail.com> writes: > So the .dump command is, in effect, saving the file, correct? which > takes the object you're saving (in my case it would be > high_scorelist), and ("filename",". what is the "w" ?) Why does > the temp file you're saving into end in .pik? Pickling simply converts an object to a string (unpickling does the opposite, convert a string to an object). The dump() function writes the generated string directly to a file, but you can use the dumps() function to get the generated string as such and do something else with it (e.g. put it in a database, send it by mail, whatever). >>> mylist = [1, 2, 34, 4.2, 'abc'] >>> s = pickle.dumps(mylist) >>> s # display the string "(lp0\nI1\naI2\naI34\naF4.2002\naS'abc'\np1\na." >>> pickle.loads(s) [1, 2, 34, 4.2002, 'abc'] Pickling is also very useful when combined with the bsddb module, because you get a fast database which functions very much like a dictionary, and in which you can put anything you like, as long as you pickle it first. >>> import bsddb >>> mydb = bsddb.btopen('game.db') >>> mydb['highscores'] = pickle.dumps(mylist) >>> mydb['highestlevel'] = pickle.dumps(21) >>> mydb['lastplayer'] = pickle.dumps('John Doe') >>> mydb.close() >>> mydb = bsddb.btopen('game.db') >>> pickle.loads(mydb['lastplayer']) 'John Doe' This is not useful for small amounts of data like the highscores list, but if you have more data (e.g. level data, dialog texts) and you need quick access to it without having to keep everything in memory all the time, bsddb is a comfortable option. Yours, Andrei ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor