Re: Convert string to mathematical function
Em Ter, 2006-08-01 às 18:45 -0700, jeremito escreveu: > I am extending python with C++ and need some help. I would like to > convert a string to a mathematical function and then make this a C++ > function. I may be wrong, but I don't think you can create new C++ functions on-the-fly. At least I had the impression that only VMs could do it (e.g. System.Reflection on .NET/Mono world and, of course, Python). > My one idea (although I don't > know how to implement it, I'm still new at this) is to pass to C++ a > pointer to a (Python) function. Will this work? I think it will, but I can't tell you how =). -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: List comparison help please
20 Aug 2006 14:47:14 -0700, Bucco <[EMAIL PROTECTED]>: > I am trying to compare a list of items to the list of files generated > by os.listdir. I am having trouble getting this to work and think I > may be going down the wrong path. Please let me know if hter is a > better way to do this. THis is what I have for my class so far: > Have you tried using sets? >>> import os >>> os.listdir('/') ['lost+found', 'var', 'etc', 'media', 'cdrom', 'bin', 'boot', 'dev', 'home', 'initrd', 'lib', 'mnt', 'opt', 'proc', 'root', 'sbin', 'srv', 'sys', 'tmp', 'usr', 'initrd.img', 'vmlinuz', 'windows', 'initrd.img.old', 'vmlinuz.old'] >>> s = set(os.listdir('/')) >>> p = set(['opt', 'mnt', 'initrd', 'home', 'tmp', 'lib', 'media', 'boot', 'usr', 'var', 'proc', 'bin', 'sys', 'initrd.img.old', 'cdrom', 'lost+found', 'sbin', 'vmlinuz.old', 'windows']) >>> s - p set(['dev', 'etc', 'vmlinuz', 'srv', 'root', 'initrd.img']) -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to print a file in binary mode
22 Oct 2006 06:33:50 -0700, Lucas <[EMAIL PROTECTED]>: I known how to do it.read() return a string. so1) bytes = read(1) #read the file by bit.2) chrString = ord(bytes) #convert the string to ASCII.3) print numberToBinary(chrString) #convert the ASCII to Binary using my function.4) Loop[numberToBinary(ord(x)) for x in f.read()] ?-- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Event driven server that wastes CPU when threaded doesn't
29 Oct 2006 14:18:02 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid>: > "Nick Vatamaniuc" <[EMAIL PROTECTED]> writes: > > The simplest solution is to change your system and put the DB on the > > same machine thus greatly reducing the time it takes for each DB query > > to complete (avoid the TCP stack completely). > > Since when do any db's let you avoid the TCP stack, even on the same > machine? Since there are Unix sockets? A quick google: http://dev.mysql.com/doc/refman/5.0/en/multiple-unix-servers.html http://archives.postgresql.org/pgsql-hackers/1997-10/msg00568.php -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Open Source Charting Tool
Em Sex, 2006-06-02 às 15:42 -0500, Larry Bates escreveu: > ReportLab Graphics can do 2D and pie charts, but I don't think it does > 3D charts yet. > > www.reporlab.org It does, but I'm not sure if the PNG backend is as good as the PDF one. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Open Source Charting Tool
Em Sex, 2006-06-02 às 16:56 -0400, A.M escreveu: > I can't browse to www.reporlab.org, but I found http://www.reportlab.com/ > which has a commercial charting product. Is that what you referring to? ReportLab (the commercial bussiness thing on .com) is where the main developers of ReportLab (a library freely available on www.reporlab.org) work. So what you want really is .org, but apparently it's having problems right now. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: 10GB XML Blows out Memory, Suggestions?
Em Ter, 2006-06-06 às 13:56 +, Paul McGuire escreveu: > (just can't open it up like a text file) Who'll open a 10 GiB file anyway? -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing PNG with pure Python
Em Sex, 2006-06-09 às 12:30 -0400, Alan Isaac escreveu: > It's your code, so you get to license it. > But if you wish to solicit patches, > a more Pythonic license is IMHO more likely > to prove fruitful. "Pythonic license"? That's new to me. I can figure out what a "Python-like license" is, but I'm clueless about a "Pythonic license". -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Killing a thread
Em Sex, 2006-06-09 às 13:54 -0700, Manish Marathe escreveu: > On 6/9/06, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > Manish Marathe wrote: > > > I am creating threads using my self defined class which > inherits the > > threading.Thread class. I want to know how can I kill the > threads which > > are being created by the object of my self defined class. > > you cannot kill a thread "from the outside"; you have to > design your > thread tasks so they can kill themselves, when asked to do > that. > > Thanks for the reply. So can a thread listen to an event i.e. can we > send an event to the thread indicating to kill itself. A plain simple boolean flag will certainly do the job. For example def run(self): self.running = True while self.running: blah() def stop(self): self.running = False -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: math.pow(x,y)
Em Dom, 2006-06-11 às 11:19 -0700, fl1p-fl0p escreveu: > import math > math.pow(34564323, 456356) > > will give math range error. > > how can i force python to process huge integers without math range > error? Any modules i can use possibly? 34564323**456356 ? -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get the length of a number
Em Dom, 2006-06-11 às 20:10 +, Stan Cook escreveu: > Can anyone tell me how to get the length of a number. I > know len(string) will get the length of a string, but it > doesn't like len(int). I seem to remember something like %s > string. I tried to set a variable = to %s int, but that > doesn't work. Is there a function I've forgotten about to > convert an integer to a string? To convert an integer i to a string: str(i) or "%s" % i To see how many decimal digits it has: import math math.ceil(math.log(i, 10)) -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get the length of a number
Em Dom, 2006-06-11 às 13:17 -0700, Saketh escreveu: > Stan Cook wrote: > > Can anyone tell me how to get the length of a number. I > > know len(string) will get the length of a string, but it > > doesn't like len(int). I seem to remember something like %s > > string. I tried to set a variable = to %s int, but that > > doesn't work. Is there a function I've forgotten about to > > convert an integer to a string? > > > > Regards > > > > Stan > > Use str(int). Then use len(). For example, len(str(12345)) will give > you 5. $ python2.4 -mtimeit -s 'x=12345' 'len(str(x))' 100 loops, best of 3: 1.33 usec per loop $ python2.4 -mtimeit -s 'x=12345;from math import ceil,log' 'ceil(log(x, 10))' 100 loops, best of 3: 1.54 usec per loop $ python2.4 -mtimeit -s 'x=12345**123' 'len(str(x))' 1000 loops, best of 3: 209 usec per loop $ python2.4 -mtimeit -s 'x=12345**123;from math import ceil,log' 'ceil(log(x, 10))' 100 loops, best of 3: 1.55 usec per loop $ python2.4 -mtimeit -s 'x=12345**1234' 'len(str(x))' 100 loops, best of 3: 19.2 msec per loop $ python2.4 -mtimeit -s 'x=12345**1234;from math import ceil,log' 'ceil(log(x, 10))' 100 loops, best of 3: 1.53 usec per loop -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get the length of a number
Em Dom, 2006-06-11 às 22:33 +0200, Sybren Stuvel escreveu: > Felipe Almeida Lessa enlightened us with: > > To see how many decimal digits it has: > > > > import math > > math.ceil(math.log(i, 10)) > > That doesn't work properly. > > >>> import math > >>> math.ceil(math.log(1, 10)) > 4.0 > >>> math.ceil(math.log(10001, 10)) > 5.0 > > But "1" certainly has as much digits as "10001". Hmmm, you're right. math.floor(math.log(x, 10)) + 1 -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: range of int() type.
23 Aug 2006 17:28:48 -0700, KraftDiner <[EMAIL PROTECTED]>: > This is obvious... but how do I crop off the high order bits if > necessary? > a[0]&0x ? min(a[0], 0x) ? -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you want in a new web framework?
2006/8/30, Ben Finney <[EMAIL PROTECTED]>: > re > struct > unicodedata > decimal > random > logging > Queue > urlparse > email operator cStringIO math cmath sets (merged to the language) itertools os + stat time tempfile glob Not that I use them all the time, but they are really useful and usually fulfill my needs. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: GC and security
2006/8/30, Les Schaffer <[EMAIL PROTECTED]>: > is there a best practice way to do this? I'm not a cryptographer, but you should really try the function collect() inside the gc module. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Client-side TCP socket receiving "Address already in use" upon connect
2006/9/3, Alex Martelli <[EMAIL PROTECTED]>: > Reflecting on the OP's use case, since all connections are forever being > made to the same 16 servers, why not tweak thinks a bit to hold those > connections open for longer periods of time, using a connection for many > send/receive "transactions" instead of opening and closing such > connections all of the time? That might well work better... Connecting to 16 differente servers per second gives a very poor performance, right? There's some overhead in creating TCP connections, even on fast networks and computers. Am I right? -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: threading support in python
4 Sep 2006 19:19:24 -0700, Sandra-24 <[EMAIL PROTECTED]>: > If there was a mod_dotnet I wouldn't be using > CPython anymore. I guess you won't be using then: http://www.mono-project.com/Mod_mono -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Higher-level OpenGL modules
5 Sep 2006 03:44:47 -0700, Leon <[EMAIL PROTECTED]>: > Greetings, > > Does anybody know of or is working on any python modules that allow for > a direct but higher-level interface to OpenGL? For example, quick > functions to draw lines, curves, and basic shapes; define hsb color > mode; fill and stroke operations; easy loading of images, svg files, > etc (much like the processing language - > http://www.processing.org/reference/index.html). The closest thing I > could find was devachan - http://www.cesaremarilungo.com/sw/devachan/, > but its very limited. Any response would be greatly appreciated. Soya? I don't know if it fulfill your needs, though. http://home.gna.org/oomadness/en/soya/ -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: python vs java
2006/9/7, Bruno Desthuilliers <[EMAIL PROTECTED]>: > I don't think one could pretend writing a cross-platform application > without testing it on all targeted platforms. E.g: while creating a free software, you may not have an Apple computer but you may want to be *possible* to run your program there. You don't test it, but you *think* it runs there. Not everybody has a spare MacOS X to test apps. Of course, if your software *needs* to run in some particular OS then you have to test on it. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: [ANN] IronPython 1.0 released today!
2006/9/5, Jim Hugunin <[EMAIL PROTECTED]>: > I'm extremely happy to announce that we have released IronPython 1.0 today! > http://www.codeplex.com/IronPython Does IronPython runs Twisted? -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: IronPython 1.0 released today!
7 Sep 2006 16:34:56 -0700, Luis M. González <[EMAIL PROTECTED]>: > People are already porting some of these libraries. > Those that are written in pure python don't need to be ported, but > those that rely on c extensions can be rewritten in c# or any other > .NET language. Or in C that is P/Invoked from the CLR, although this option is somewhat less portable. See http://www.mono-project.com/Interop_with_Native_Libraries -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Best Middle Tier Architechure?
2006/9/7, Butternut Squash <[EMAIL PROTECTED]>: > right now we are using c# and .net remoting in a way that just is not > efficient. > > I want to rewrite a lot of what we do in python. I have seen XML-RPC and > soap. Are there other options? It surely depends on what's going to be on the other sides. If everything is Python, you may use Twisted.Spread. If you have to communicate with different languages and plataforms, maybe CORBA helps. Well, I'm sure a lot of people know more options than I do here. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: best split tokens?
8 Sep 2006 13:41:48 -0700, Jay <[EMAIL PROTECTED]>: > Let's say, for instance, that one was programming a spell checker or > some other function where the contents of a string from a text-editor's > text box needed to be split so that the resulting array has each word > as an element. Is there a shortcut to do this and, if not, what's the > best and most efficient token group for the split function to achieve > this? your_string.split() -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Best Middle Tier Architechure?
2006/9/8, Butternut Squash <[EMAIL PROTECTED]>: > I have to support multiple applications using different schema and > databases. Would like to present as much as a unified interface as > possible. I'd recomend CORBA as it supports multiple platforms and languages. SOAP and XML-RPC can be used as well, but I'm afraid performance can be a problem if a lot of calls are made or big/complex objects are transfered. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: convert loop to list comprehension
8 Sep 2006 17:37:02 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]>: > 1. Using an _ is an interesting way to use a throw-away variable. Never > would I think of that ... but, then, I don't do Perl either :) It's a kind of convention. For example, Pylint complains for all variables you set and don't use unless its name is "_". > 2. Any reason for xrange() instead of range() It's faster. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: convert loop to list comprehension
08 Sep 2006 17:33:20 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid>: > [EMAIL PROTECTED] writes: > > print sum( ([i]*n for i,n in enumerate(seq)), []) > > Wow, I had no idea you could do that. After all the discussion about > summing strings, I'm astonished. Why? You already had the answer: summing *strings*. Everything but strings can be summed by sum(). E.g.: Python 2.4.3 (#2, Apr 27 2006, 14:43:58) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class x(object): ... def __add__(self, other): ... return x(self.a + other.a) ... def __init__(self, a): ... self.a = a ... >>> t = x(10) >>> t.a 10 >>> sum([t, t]) Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for +: 'int' and 'x' >>> sum([t, t], t) <__main__.x object at 0xb7d6752c> >>> _.a 30 >>> sum([t, t], x(0)).a 20 >>> sum([t, t]*1000, t).a 20010 -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: No ValueError for large exponents?
2006/9/6, Robin Becker <[EMAIL PROTECTED]>: > enigmadude wrote: > > As many have heard, IronPython 1.0 was released. When I was looking > > through the listed differences between CPython and IronPython, the > > document mentioned that using large exponents such as 10 ** > > 735293857239475 will cause CPython to hang, whereas IronPython will > > raise a ValueError. Trying this on my own machine, it did indeed seem > > to cause CPython to hang. In cases such as this, should this be > > considered a bug in the CPython implementation that needs to be fixed? > > Or is there a reason for this, such as consideration of future changes > > and language definition vs language implementation, etc.? > > > I suspect the hang may be python actually trying to work out the > 1 followed by 735293857239475 zeroes. Perhaps IronPython has a forward > looking algorithm that knows when to give up early. I think that IronPython does the same as the .Net runtime does. Look at boo's output: $ booish Welcome to booish, an interpreter for the boo programming language. Running boo 0.7.5.2013. The following builtin functions are available: dir(Type): lists the members of a type help(Type): prints detailed information about a type load(string): evals an external boo file globals(): returns the names of all variables known to the interpreter Enter boo code in the prompt below. >>> 10**100 1E+100 >>> 10**100 ∞ >>> 10**735293857239475 ERROR: Error reading from 'input3': 'Value too large or too small.'. >>> (10**100).GetType() System.Double Well, it's a double on boo instead of a very long int as in Python. I don't know if in IronPython it's the same. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Pocoo (bulletin board software) 0.1 beta released
10 Sep 2006 16:17:08 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid>: > So, I think it's not worth thinking about writing yet another BBS > unless it can handle a Slashdot-sized load on a commodity PC. Python is slow. Psyco helps, but you should use C instead. And yes, I am kidding =) -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to stop an [Rpyc] server thread?
7 Sep 2006 23:38:08 -0700, Tal Einat <[EMAIL PROTECTED]>: > > I'm not an expert in socket programming, but I can't see the > > correlation between the "listener socket" being in timeout mode and a > > different behavior the other sockets.. > > Anyhow the main goal is being able to shut down the thread of the rpyc > > server, any other way is an appreciated suggestion. > > Now to the real issue. I've also had such weird problems with socket > timeout in Python. The best workaround I found is to use select() to > check for activity on the socket(s), and use select()'s timeout > mechanism. So far, this has worked without a hitch on both WindowsXP > and Solaris Sparc9 installations. Twisted[1] is the answer. I've never seen a better framework for using sockets, it's painless. I created two versions of the same protocol (both client and server), one using sockets + select, another using Twisted. The sockets version had 2x lines than the Twisted one and lots of bugs. Sockets may fail *anywhere* in your code, and Twisted takes care of all details for you[2]. Simply Sweet. Cheers, [1] http://www.twistedmatrix.com/ [2] Of couse this is just *one* advantage of the Twisted framework... PS.: No, I wasn't paid for this e-mail ;-) -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator cllass hides docstring from doctest?
2006/9/21, Berthold Höllmann <[EMAIL PROTECTED]>: > Saving the following code to a file and running the code through > python does not give the expected error. disableling the "@decor" line > leads to the expected error message. Is this a bug or an overseen > feature? Try the new_decor class described below: >>> class decor(object): ... def __init__(self, f): ... self.f = f ... def __call__(self, *args, **kw): ... return self.f(*args, **kw) ... >>> class new_decor(object): ... def __init__(self, f): ... self.f = f ... self.__doc__ = f.__doc__ ... self.__name__ = f.__name__ ... def __call__(self, *args, **kw): ... return self.f(*args, **kw) ... >>> def f(a, b): ... ''' ... >>> f(1, 2) ... False ... >>> f(2, 2) ... False ... ''' ... return a == b ... >>> f.__doc__ '\n\t>>> f(1, 2)\n\tFalse\n\t>>> f(2, 2)\n\tFalse\n\t' >>> decor(f).__doc__ == f.__doc__ False >>> new_decor(f).__doc__ == f.__doc__ True -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the best way to "get" a web page?
24 Sep 2006 10:09:16 -0700, Rainy <[EMAIL PROTECTED]>: > Functionally they are the same, but third line included in Firefox. > Opera View Source command produces the same result as Python. [snip] It's better to compare with the result of a downloader-only (instead of a parser), like wget on Unix. That way you'll get exactly the same bytes (assuming the page is static). -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: does anybody earn a living programming in python?
2006/9/25, Robert Kern <[EMAIL PROTECTED]>: > walterbyrd wrote: > > If so, I doubt there are many. > > > > I wonder why that is? > > Well I do. So do the other dozen or so developers at my company. We're looking > to hire a few more, in fact. And there are also those ReportLab guys: www.reportlab.com -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: QOTW (was Re: does anybody earn a living programming in python?)
2006/9/26, Sybren Stuvel <[EMAIL PROTECTED]>: > Aahz enlightened us with: > > Fredrik Lundh <[EMAIL PROTECTED]> wrote: > >> > >>well, if you're only watching mtv, it's easy to think that there's > >>obviously not much demand for country singers, blues musicians, > >>British hard rock bands, or melodic death metal acts. > > > > Any other votes for this being QOTW? > > +1 here > +1 here, too -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: PATCH: Speed up direct string concatenation by 20+%!
28 Sep 2006 19:07:23 -0700, Larry Hastings <[EMAIL PROTECTED]>: > THE BENCHMARKS > > Benchmark 1: > def add(a, b, c, ... t): return a + b + c + ... + t > for i in range(1000): add("aaa", "bbb", "ccc", ..., "ttt") [snip] What about "a + b"? Or "a + b + c"? Does it have a large overhead on small string concatenations? -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: What are python closures realy like?
On 12/1/06, Karl Kofnarson <[EMAIL PROTECTED]> wrote: [snip] > def fun_basket(f): > common_var = [0] > def f1(): > print common_var[0] > common_var[0]=1 > def f2(): > print common_var[0] > common_var[0]=2 > if f == 1: > return f1 > if f == 2: > return f2 Everytime you call fun_basket you create another common_var. > However, calling f1=fun_basket(1); f2 = fun_basket(2) and > then f1(); f2() returns 0 and 0. Two calls to fun_basket, two different common_var's, two f1's and two f2's. Each f1/f2 pair have access to a different common_var, so it's working as expected. To work as you expected, fun_basket should be on the same block common_var is defined. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: global name 'self' is not defined
On 2 Dec 2006 10:42:28 -0800, Evan <[EMAIL PROTECTED]> wrote: > Why is it that the first call works fine, but the second tells me > 'global name 'self' is not defined'? What I want is to have the > dictionary 'estoc' available in my calling script. Well, you have not posted the code that is causing the problem, nowhere in your mail there's a reference to "self". -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Async callback in python
On 4 Dec 2006 20:18:22 -0800, Linan <[EMAIL PROTECTED]> wrote: > 3, If not, where to get the real one(s)? After reading Calvin's mail, you may want to see http://twistedmatrix.com/ . It's an assynchronous library built around the concept of deferreds (think of callbacks). You may like it =). Cya, -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: BeautifulSoup vs. loose & chars
On 26 Dec 2006 04:22:38 -0800, placid <[EMAIL PROTECTED]> wrote: > So do you want to remove "&" or replace them with "&" ? If you want > to replace it try the following; I think he wants to replace them, but just the invalid ones. I.e., This & this & that would become This & this & that No, i don't know how to do this efficiently. =/... I think some kind of regex could do it. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Are all classes new-style classes in 2.4+?
On 31 Dec 2006 03:57:04 -0800, Isaac Rodriguez <[EMAIL PROTECTED]> wrote: > I am using Python 2.4, and I was wondering if by default, all > classes are assumed to be derived from "object". This won't tell you advantages or disadvantages, but will show you that the default still is the old-style: >>> class old: ... pass ... >>> type(old()) >>> dir(old()) ['__doc__', '__module__'] >>> >>> class new(object): ... pass ... >>> type(new()) >>> dir(new()) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] In general, even if you don't understand the differences, it's better to use new-style (they're new ;-). Anyway, see http://effbot.org/pyref/new-style-and-classic-classes.htm for a little more information. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: A question about unicode() function
On 31 Dec 2006 05:20:10 -0800, JTree <[EMAIL PROTECTED]> wrote: > def funUrlFetch(url): > lambda url:urllib.urlopen(url).read() This function only creates a lambda function (that is not used or assigned anywhere), nothing more, nothing less. Thus, it returns None (sort of "void") no matter what is its argument. Probably you meant something like def funUrlFetch(url): return urllib.urlopen(url).read() or funUrlFetch = lambda url:urllib.urlopen(url).read() > objUrl = raw_input('Enter the Url:') > content = funUrlFetch(objUrl) content gets assigned None. Try putting "print content" before the unicode line. > content = unicode(content,"gbk") This, equivalent to unicode(None, "gbk"), leads to > TypeError: coercing to Unicode: need string or buffer, NoneType found None's are not strings nor buffers, so unicode() complains. See ya, -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: A python library to convert RTF into PDF ?
On 3 Jan 2007 10:52:02 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > I have tried to > convert them to tex using OpenOffice, but the result is ugly as hell. Why not use OO.org to convert DOC to PDF? It does so natively, IIRC. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: static object
On 1/3/07, meelab <[EMAIL PROTECTED]> wrote: > I am looking for a way to create a "static object" or a "static class" - > terms might be inappropriate - having for instance: An example will speak better than me: class Card(object): __cards = {} def __init__(self, number, suit): self.number, self.suit = number, suit def __new__(cls, number, suit): try: return cls.__cards[(number, suit)] except KeyError: obj = object.__new__(cls, number, suit) cls.__cartas[(number, suit)] = obj return obj -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Packaging up a Python/Twisted Matrix application...
On 1/4/07, Chaz Ginger <[EMAIL PROTECTED]> wrote: > I have a rather large Python/Twisted Matrix application that will be run > on Windows, Linux and perhaps Macs. I was wondering if there are any > tools that can be used to create an installer that will bring in Python, > Twisted Matrix, my application libraries and anything else I need? I haven't tried with Twisted, but I had success in using py2exe + Inno Setup on a program dependent on Python + ReportLab + pygtk. As both ReportLab and pygtk got even C extensions, I don't see why this setup wouldn't work with Twisted. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why less emphasis on private data?
On 07 Jan 2007 02:01:44 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Dennis Lee Bieber <[EMAIL PROTECTED]> writes: > > __ (two leading underscores) results in name-mangling. This /may/ be > > used to specify "private" data, but is really more useful when one is > > designing with multiple super classes: > > Trouble with this is you can have two classes with the same name, > perhaps because they were defined in different modules, and then the > name mangling fails to tell them apart. What is the chance of having to inherit from two classes from different modules but with exactly the same name *and* the same instance variable name? Of course you're being very pessimistic or extremely unlucky. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to find the longst element list of lists
On 1/7/07, Michael M. <[EMAIL PROTECTED]> wrote: > How to find the longst element list of lists? s1 = ["q", "e", "d"] s2 = ["a", "b"] s3 = ["a", "b", "c", "d"] s = [s1, s2, s3] s.sort(key=len, reverse=True) print s[0] is s3 print s[1] is s1 print s[2] is s2 sx1, sx2, sx3 = s print 'sx1:', sx1 print 'sx2:', sx2 print 'sx3:', sx3 -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Suitability for long-running text processing?
On 1/8/07, tsuraan <[EMAIL PROTECTED]> wrote: [snip] > The loop is deep enough that I always interrupt it once python's size is > around 250 MB. Once the gc.collect() call is finished, python's size has > not changed a bit. [snip] > This has been tried under python 2.4.3 in gentoo linux and python 2.3 under > OS X.3. Any suggestions/work arounds would be much appreciated. I just tried on my system (Python is using 2.9 MiB) >>> a = ['a' * (1 << 20) for i in xrange(300)] (Python is using 304.1 MiB) >>> del a (Python is using 2.9 MiB -- as before) And I didn't even need to tell the garbage collector to do its job. Some info: $ cat /etc/issue Ubuntu 6.10 \n \l $ uname -r 2.6.19-ck2 $ python -V Python 2.4.4c1 -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Suitability for long-running text processing?
On 1/8/07, tsuraan <[EMAIL PROTECTED]> wrote: > > > > I just tried on my system > > > > (Python is using 2.9 MiB) > > >>> a = ['a' * (1 << 20) for i in xrange(300)] > > (Python is using 304.1 MiB) > > >>> del a > > (Python is using 2.9 MiB -- as before) > > > > And I didn't even need to tell the garbage collector to do its job. Some > info: > > It looks like the big difference between our two programs is that you have > one huge string repeated 300 times, whereas I have thousands of > four-character strings. Are small strings ever collected by python? In my test there are 300 strings of 1 MiB, not a huge string repeated. However: $ python Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> # Python is using 2.7 MiB ... a = ['1234' for i in xrange(10 << 20)] >>> # Python is using 42.9 MiB ... del a >>> # Python is using 2.9 MiB With 10,485,760 strings of 4 chars, it still works as expected. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine an object is a subclass of another
On 9 Jan 2007 07:01:31 -0800, abcd <[EMAIL PROTECTED]> wrote: > anyways, is there a way to check without having an instance of the > class? In [1]: class A: ...: pass ...: In [2]: class B(A): ...: pass ...: In [3]: issubclass(B, A) Out[3]: True In [4]: isinstance(B(), B) Out[4]: True In [5]: isinstance(B(), A) Out[5]: True -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Clearing the screen
Em Sáb, 2006-02-11 às 12:04 -0800, mwt escreveu: > I'm doing some python programming for a linux terminal (just learning). > When I want to completely redraw the screen, I've been using > os.system("clear") > This command works when using python in terminal mode, and in IDLE. > However, when running a little .py file containing that command, the > screen doesn't clear. > > What to do? There's one escape sequence that does what you want. I am *not* sure if this solution is the correct one, but: $ clear | hd 1b 5b 48 1b 5b 32 4a |.[H.[2J| 0007 $ python Python 2.3.5 (#2, Nov 20 2005, 16:40:39) [GCC 4.0.3 2005 (prerelease) (Debian 4.0.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print chr(0x1b)+chr(0x5b)+chr(0x48)+chr(0x1b)+chr(0x5b)+chr(0x32)+chr(0x4a), >>> # Clears the screen! -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: simple math question
Em Sáb, 2006-02-11 às 14:52 -0500, John Salerno escreveu: > Hi all. I'm just starting out with Python, so I'm a little slow right > now. :) > > Can someone explain to me why the expression 5 / -2 evaluates to -3, > especially considering that -2 * -3 evaluates to 6? > > I'm sure it has something to do with the negative number and the current > way that the / operator is implemented, but why doesn't it evaluate to > -2 instead? It has to do with floating point operations. If you evaluate 5 / -2.0 or 5.0 / -2 you will have -2.5. It gives you -3 because of rounding to integers. Look: >>> round(-2.5) -3.0 >>> round(+2.5) 3.0 This behavior is because -round(x) should be equal to round(-x). Cya, Felipe. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
itertools examples
Hi, IMHO, on http://www.python.org/doc/current/lib/itertools-example.html , shouldn't the part >>> for k, g in groupby(enumerate(data), lambda (i,x):i-x): ... print map(operator.itemgetter(1), g) be >>> for k, g in groupby(enumerate(data), lambda (i, x): i-x): ... print [i[1] for i in g] ? AFAIK, list comprehensions are more preferable than map's as they're clearer. Or am I wrong? Cya, Felipe. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools examples
Em Sáb, 2006-02-11 às 20:16 -0800, Raymond Hettinger escreveu: > Both work just fine. It's a personal choice when to use map() and when > to use a list comprehension. Since many itertools have the flavor of > map/filter, its use is not out of place in the itertools docs. I know both work in the same way, but IIRC I heard someone (GvR?) saying list comprehensions should be used when possible to substitute map, filter and/or reduce. > Also, the use of map() provided an opportunity to demonstrate > operator.itemgetter(). While not essential to this example, it is > helpful with several other tools (especially those with a key= > argument). Itertools provide a kind of iterator algebra and > itemgetter() is an essential part of that algebra; hence, it is > appropriate that it be included in itertool examples. > > If your taste says otherwise, that's okay. Program however you want. > If reading the examples helped you understand the toolset, then the > docs accomplished their goal. IMO at a first glance the it's much easier to read and understand the list comprehension, but I have to admit that if I didn't see the operator.itemgetter(1) there I would probably never known it existed. Well, so let's just leave it there, but I'll surely program with the list comprehensions ;-). Thanks for your attention, Felipe. > > Raymond > -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python very slow compared to C
Em Dom, 2006-02-12 às 03:03 -0800, [EMAIL PROTECTED] escreveu: > Probably every answer I can give you is wrong for you, so answering is > almost useless... In this thread we have already given the most > pertinent answers to the original question from Diffuse. > I can show you this page, but I think this is useless too for you: > http://shootout.alioth.debian.org/gp4/benchmark.php?test=all〈=python&lang2=ocaml What they were saying is that at most of the times your program is going to sit and wait for things like network, hard drive, user input, etc., and these cannot be changed by any language. Those benchmarks test only raw CPU performance. Yes, sometimes you *need* raw CPU power, but nobody said that in this case Python is good for you. Python is good at making your life as a programmer easier, and every Python programmer knows that. I wanted to see PyRex or C modules versions of that benchmarks, it would be really nice. This is the approach used to create fast CPU-bound algorithms in Python, and as such should be tested as thoroughly as those Python-only counterparts. And if it matters for you: Google says Python is fast for them, what else do you want? Cya, Felipe. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python very slow compared to C
Em Dom, 2006-02-12 às 03:20 -0800, [EMAIL PROTECTED] escreveu: > However, to me, the strength of python is the batteries that is > included(and there are more and more coming). So .NET is as good as Python? Hmmm... I think the language itself is the best part of Python, its library is just a complement (a very good and relevant one, though). -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python very slow compared to C
Em Dom, 2006-02-12 às 04:33 -0800, [EMAIL PROTECTED] escreveu: > Felipe Almeida Lessa wrote: > > Em Dom, 2006-02-12 às 03:20 -0800, [EMAIL PROTECTED] escreveu: > > > However, to me, the strength of python is the batteries that is > > > included(and there are more and more coming). > > > > So .NET is as good as Python? Hmmm... I think the language itself is the > > best part of Python, its library is just a complement (a very good and > > relevant one, though). > .NET is not a language, IMO. You talked about "batteries included", and that isn't related to the language. I said .NET in reference to what you said. The part about the language is my own opinion, I just didn't want to say anything about C#, Boo, J#, Nemerle or any other language that targets the .NET framework. In the case of Python, as well as Java, the language has the same name as the framework, and this may have lead you to mistake me. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Tracking down memory leaks?
Em Dom, 2006-02-12 às 05:11 -0800, MKoool escreveu: > I have an application with one function called "compute", which given a > filename, goes through that file and performs various statistical > analyses. It uses arrays extensively and loops alot. it prints the > results of it's statistical significance tests to standard out. Since > the compute function returns and I think no variables of global scope > are being used, I would think that when it does, all memory returns > back to the operating system. > > Instead, what I see is that every iteration uses several megs more. > For example, python uses 52 megs when starting out, it goes through > several iterations and I'm suddenly using more than 500 megs of ram. > > Does anyone have any pointers on how to figure out what I'm doing > wrong? Have you tried to force a garbage collection? Try, for example, running gc.collect() everytime the function returns. See http://www.python.org/doc/current/lib/module-gc.html for more details. > Thanks, > mohan Cya, Felipe. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Another n00b: Removing the space in "print 'text', var"
Em Dom, 2006-02-12 às 22:11 +, HappyHippy escreveu: > More of a minor niggle than anything but how would I remove the > aforementioned space? > > eg. > strName = 'World' > print 'Hello', strName, ', how are you today?' > > comes out as "Hello World , how are you today?" strname = 'World' print 'Hello %s, how are you today?' % strname -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Questions for BitTorrent's Author, Bram Cohen
Em Dom, 2006-02-12 às 20:10 -0500, Steve Holden escreveu: > I'd like the questions to be representative of as broad a cross-section > of the Python community as possible. If you have a question you'd like > to hear Bram answer please let me know and I'll try to include them. Something I think lots of people want to know: why Python, and not anything else? > regards > Steve Cheers, Felipe. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: ordered sets operations on lists..
Em Dom, 2006-02-12 às 23:15 -0500, Steve Holden escreveu: > Given that Python 2.4 doesn't even perform simple constant folding for > arithmetic expressions > [snip] May I ask why doesn't it perform such optimization? Is there any special difficulties in doing so with the Python compiler? Also, IIRC Psyco does optimize these constant expressions. Or am I wrong? Cheers, Felipe. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: ordered sets operations on lists..
Em Dom, 2006-02-12 às 23:51 -0500, Steve Holden escreveu: > The basic answer is that so far no developer has felt it worthwhile to > expend time on adding these optimizations. I always thought these small optimizations could lead Python to be faster overall. I remember about this every time I see CPython vs. IronPython benchmarks (.NET and Mono do some nice optimizations at compile and run times). > > Also, IIRC Psyco does optimize these constant expressions. Or am I > > wrong? > > > Psyco does some very advanced things, but it does them all at run-time. > Unless I misunderstand (not unheard of), there are no circumstances > under which Psyco will improve run-time for a piece of code that is only > executed once. Sorry, I think I should have been clearer. Yes, Psyco only helps at runtime (when the function is called), but those constant folds only practically help on parts of the code that are called many times anyway, right? -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Loop Backwards
Em Ter, 2006-02-14 às 10:08 +0100, bruno at modulix escreveu: > for item in reversed(alist): > do_something_with(item) > > or (more perlish at first sight): > > for item in alist[::-1]: > do_something_with(item) No "or" here. The [::-1] version creates a whole new list in memory, it's silly to believe both will behave equally (well, strictly speaking they will, but one will use twice more memory than the other). -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie
Em Qua, 2006-02-15 às 00:30 +, LittlePython escreveu: > I really do not wish to limit myself to MS. My bread and butter is MS but I > am a BSD fan at heart. I wanted to learn something I can use in both. Please start by not top-posting ;-). Also, see http://www.mono-project.com/VisualBasic.NET_support . -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie
Em Ter, 2006-02-14 às 19:54 -0500, Ken Stevens escreveu: > Some people or group of people decided bottom posting was better and it > MUST be that way. To me that even goes against one of the main > philosophies of Linux which is that of choice. So, to any who think, > otherwise... there is absolutely NOTHING wrong or incorrect about TOP > posting. OK, rant mode off. I feel better now! I got that off my chest! I don't want to start another discussion about this (the ck mailing list had one these days), but this has nothing to do about choice: it's a convention. And I don't think you want even to try to send a patch to Linus with code conventions he doesn't like. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Soduku
Em Ter, 2006-02-14 às 17:32 -0800, Jonathan Gardner escreveu: > So, one more story on why Python is really good. I think, at least with > 2.4, we should start bragging about Python's speed. I mean, it beats > Java AND perl! Maybe the other implementations also have errors? Well, I'm not saying Python is worse than them, I'm just trying to be fair. Besides, puzzles can't say if one is better than the other, they're completely out of the reality of most programs. Just my two cents, Felipe. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Which is faster? (if not b in m) or (if m.count(b) > 0)
Em Ter, 2006-02-14 às 20:14 -0800, Farel escreveu: > Which is Faster in Python and Why? > > jc = {}; m = [] > x = [ [1,2,3,4,5,6,7,8,9],[..],...] # upwards of 1 entries > def binm() > for item in x: > b = item[:]; b.sort(); bc = 0 > for bitem in b: bc += int(bitem) > try: m = jc[bc] > except: m = [] > if not b in m: > m.append(b); jc[bc]=m Why do you copy the list and sort it if you're just summing its elements? Instead of b = item[:]; b.sort(); bc = 0 for bitem in b: bc += int(bitem) you can do just bc = sum(int(i) for i in item) or, if the order *really* matters, what is very strange, you can do bc = sum(int(i) for i in sorted(item)) Another thing, if you want to have in the values of the dictionary jc only unique elements, you can use sets: >>> a = set() >>> print a set([]) >>> a.add(10) >>> print a set([10]) >>> a.add(10) >>> print a set([10]) >>> a.add(10) >>> print a set([10]) So, the final example would be (assuming that you don't need to sum in order): def binm(): for item in x: bc = sum(int(i) for i in item) try: jc[bc].add(b) except KeyError: jc[bc] = set([b]) Looks prettier, have less statements and is (or should be) faster. This only works in Python 2.4, but you can adapt it to run on other versions, too. Cheers, Felipe. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: [ANN] Movable python Trial Version
Em Sáb, 2006-02-18 às 04:24 -0800, Fuzzyman escreveu: > It is set to expire on the 22nd May, and displays a nag screen on > startup. Other than that, it is the full version. Have fun. Attached is the cracked version with no expiration limit and my own bitmap on the startup. Enjoy! > Fuzzyman > http://www.voidspace.org.uk/python/index.shtml Just kidding ;-), Felipe. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Should we still be learning this?
Em Sáb, 2006-02-18 às 14:38 +0200, Max escreveu: > On monday I start a semester course in Python (the alternative was > Java). I was looking through the course outline and noticed the following: > > 1) UserDict is used. This is deprecated, right? LOL... it's the first time I see someone talking about this module. /me checks the documentation. Yep, looks like this module is deprecated since Python 2.2. > 2) There is no mention of list comprehensions, but map and filter are > taught early and then revisited later. I don't think this is good: list > comprehensions are, IMO, one of Python's great features, Psyco prefers > them, they're more pythonic, and map and filter seem to be going out the > window for Python 3000. Urgh. This sucks. Did they mention generators, at least? Sometimes list comprehensions are even faster (I didn't check, but I think this one can be an example of this: [i*2+2 for i in iterator] vs. map(lambda x: x*2 +2, iterator)). They should have taught both. > What do you think? I wonder if they need some updating. > --Max Just my two cents, Felipe. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: share function argument between subsequent calls but not between class instances!
Em Sáb, 2006-02-18 às 17:42 +0100, K. Jansma escreveu: > How can I avoid this without using eg. self.L in an __init__? Why not use it? That's how it's meant to be done! > Thanks in advance, > Karel. Cya, Felipe. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: share function argument between subsequent calls but not between class instances!
Em Sáb, 2006-02-18 às 16:50 +, Duncan Booth escreveu: > marker = object() > > class Test(object): > def __init__(self): > self.L = [] > > def f(self,a, L=marker): > if L is marker: > L = self.L > L.append(a) > return L As hasattr(None, "append") == False, you could also do: class Test(object): def __init__(self): self.L = [] def f(self, a, L=None): if L is None: L = self.L L.append(a) return L -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: define loop statement?
Em Sáb, 2006-02-18 às 20:04 +, Jeffrey Schwab escreveu: > if __name__ == '__main__': > loop = Loop(10) > while loop: > print "OK" Maybe: while Loop(10)(): print "OK" Looks rather ugly but requires one less line ;-). -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: define loop statement?
Em Dom, 2006-02-19 às 11:08 +1100, Nigel Rowe escreveu: > Felipe Almeida Lessa wrote: > > > Em Sáb, 2006-02-18 às 20:04 +, Jeffrey Schwab escreveu: > >> if __name__ == '__main__': > >> loop = Loop(10) > >> while loop: > >> print "OK" > > > > Maybe: > > > > while Loop(10)(): > > print "OK" > > > > Looks rather ugly but requires one less line ;-). > > > Doesn't work. You get a NEW Loop(10) instance on each pass through the > 'while'. This is just an expensive way to make an endless loop. Oh, sorry, ignore me on that one. Now I think I should sleep =S... -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Should we still be learning this?
Em Sáb, 2006-02-18 às 15:13 +0200, Max escreveu: > > I wonder if they need some updating. > > > > And so does Dive Into Python (our textbook, diveintopython.org) which > has the same deficiencies in its outline. Are they being *paid* for teaching? Then they should overcome this issue of Dive Into Python by either using their own material our by improving Dive Into Python and giving it back to the community. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Is inifinite loop not a good practice?
Em Seg, 2006-02-20 às 17:01 -0500, Roy Smith escreveu: > In article <[EMAIL PROTECTED]>, > "Terry Reedy" <[EMAIL PROTECTED]> wrote: > > def fact(n): > > res = 1 > > while n != 0: > > res *= n > > n -= 1 > > return res > > > > fact(-1) > > Could be worse. You could have written: > > def fact(n): >if n == 0: > return 1 >else: > return n * fact (n-1) > > then you would have not only gotten zonked on CPU charges, but on memory > charges as well :-) This is not worse. Sometime in the future the function will raise a RuntimeError with "maximum recursion depth exceeded" and free all system resources, but the other one (without recursive calls) will only grow and grow and grow... -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Little tool - but very big size... :-(
Em Qua, 2006-02-22 às 21:38 +0100, Gerhard Häring escreveu: > A Tkinter hello weights here 1,95 MB (2.049.264 Bytes) > > compared to the small wxPython tool that I compressed recently: 2,80 MB > (2.942.543 Bytes) What about PyGtk? Does anybody have any figures? I can't test here =(... -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: time.sleep(1) sometimes runs for 200 seconds under windows
Em Qui, 2006-02-23 às 15:26 -0600, Paul Probert escreveu: >My app runs in a loop looking for changes in a database, and like a > good boy I call time.sleep(1) inside the loop. Unfortunately this > sometimes runs for 200 seconds or so, presumably while my OS is calling > Bill Gates to tell him what I've been doing. This happens under NT4, > W2k, and XP. What do people do to fix this? Thanks! What about the interpreter? Have you tried sleeping there? -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with Property
Em Sáb, 2006-02-25 às 09:14 -0500, Steve Holden escreveu: > It seems particularly odd to want to put getters and setters behind > property access. What does the extra layer buy you? I can only think of some kind of debugging. Maybe? > regards > Steve Cya, Felipe. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Optimize flag question
Em Sáb, 2006-02-25 às 17:56 -0800, [EMAIL PROTECTED] escreveu: > Steve Holden wrote: > > > Some other functions rely on the AssertionError exception to indicate to > > > the user that something went wrong instead of using a user defined > > > exception. > > > > > > > The real problem here is that you appear to be using AssertionError in > > an inappropriate way. If some caller passes an incorrect argument to > > your function, raise a ValueError. If you are passed the wrong type of > > data, raise a TypeError. And so on. Or, as you imply you thought about, > > raise a user-defined error. > > > > Generally speaking you should reserve assert for circumstances where you > > expect some invariant condition to be true. Otherwise use an "if" > > statement and raise some other exception if the condition is True. > > > What would be the occasion that AssertionError be the right exception > to raise then ? IMHO, assertions should be used in places where things are obvious. For example, you can check if a object is of a given type to avoid using it on a bad context. *But*, those checks are just to help you while coding, not at runtime. If you want those checks at runtime, you should be using if's. Using other words, assertions should be used only when you know a priori that the assertion should *never* fail in a production system. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 354: Enumerations in Python
Em Seg, 2006-02-27 às 00:43 -0800, Paul Rubin escreveu: > def print_members(header, e): # print header, then members of enum e > print header > for m in e: > print '\t', str(m) > > months_longer_than_february = enum('jan', 'mar', 'apr', ) # etc > months_shorter_than_february = enum() > > print_members('shorter:', months_shorter_than_february) > print_members('longer:', months_longer_than_february) IMHO, you should be using sets, not enums. Something like: def print_members(header, e): print header from m in e: print '\t', str(e) months = enum('jan', 'fev', 'mar' ...) months_longer_than_february = frozenset(months.jan, months.mar, months.apr ...) months_shorter_than_february = frozenset() print_members('shorter:', months_shorter_than_february) print_members('longer:', months_longer_than_february) -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 354: Enumerations in Python
Em Seg, 2006-02-27 às 02:42 -0800, Paul Rubin escreveu: > Felipe Almeida Lessa <[EMAIL PROTECTED]> writes: > > IMHO, you should be using sets, not enums. Something like: > > If enums aren't supposed to work in that construction then the PEP > shouldn't specify that they work that way. Sorry, but where do they say that? -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread Question
Em Ter, 2006-02-28 às 20:24 +, Grant Edwards escreveu: > > I have seen examples that used classes, and other examples > > that just called one thread start command - when should you > > use one over another? > > I'm not sure what you mean by "use classes" vs. "calling a > thread start command". My example above uses a class > (threading.Thread) to create a thread object, and then calls > its start method. # He meant calling direct vs. subclassing. In your example you called the Thread class directly, but you could have subclassed it. # In your case, Edwards, I'd prefer subclassing because then you could put some states in the class. A (bad) example: class Foo(Thread): def __init__(self): Thread.__init__(self) self.alive = False self.running = True def run(self): while self.running: self.alive = ping('myhost') sleep(10) def stop(self): self.running = False # Then you could: a = Foo() do_something() print a.alive do_something_more() print a.alive finish_everything() print a.alive a.stop() # quit -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: comple list slices
Em Ter, 2006-02-28 às 09:10 -0800, [EMAIL PROTECTED] escreveu: > Although I don't know if this is faster or more efficient than your > current solution, it does look cooler: [snip] > print [x for x in grouper] This is not cool. Do print list(grouper) -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread Question
Em Ter, 2006-02-28 às 20:38 +, Grant Edwards escreveu: > On 2006-02-28, D <[EMAIL PROTECTED]> wrote: > > > Thanks, Grant. I apologize for not being clear on what I > > meant by using "classes". This is an example of what I was > > referring to: > > http://www.wellho.net/solutions/python-python-threads-a-first-example.html > > Ah, I see. I had forgotten that people subclass Thread like > that. It's mostly just a matter of style. There aren't any > practical differences that I can think of. Within a class you can maintain lots of internal states and make it easily changable by other threads. Sure, you could archive this with functions, but IMHO it's not pythonic. But for simple cases both would suffice. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Make staticmethod objects callable?
Em Ter, 2006-02-28 às 15:17 -0500, Nicolas Fleury escreveu: > class A: > @staticmethod > def foo(): pass > bar = foo() # Why not: def foo(): pass class A: bar = foo() foo = staticmethod(foo) -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Rounding up to the nearest exact logarithmic decade
Em Ter, 2006-02-28 às 17:47 -0500, [EMAIL PROTECTED] escreveu: > Quoting Derek Basch <[EMAIL PROTECTED]>: > > > Given a value (x) that is within the range (1e-1, 1e7) how do I round > > (x) up to the closest exact logarithmic decade? For instance: > > How about this: > > def roundup(x): > if x < 1: > return 1 > else: > return '1' + ('0' * len(str(int(x No dice. First, it returns an int for some cases and a string for the others. Second, casting from str to int and vice-versa and concatenating strings won't perform any good. I wouldn't like this hack on my code. My 2¢, Felipe. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 354: Enumerations in Python
Em Seg, 2006-02-27 às 17:10 -0800, Paul Rubin escreveu: > Ben Finney <[EMAIL PROTECTED]> writes: > > If an enumeration object were to be derived from, I would think it > > just as likely to want to have *fewer* values in the derived > > enumeration. Subclassing would not appear to offer a simple way to do > > that. > > pentium_instructions = enum('add', 'sub', 'mul', ) # etc > > athlon64_instructions = enum('add64', 'sub64', # etc > base_enum=pentium_instructions) > > # 386 has no floating point unit > i386_instructions = enum(base_enum=pentium_instructions, > remove=('addf', 'subf', 'mulf',)) # etc Or maybe just... i386_instructions = enum('add', 'sub', 'mul', ...) pentium_instructions = enum(i386_instructions, 'addf', 'subf', 'mulf', ...) athlon64_instructions = enum(pentium_instructions, 'add64', 'sub64', ...) myprocessor_instructions = enum('foo', 'bar', 'baz', ...) all_instructions = enum(athlon64_instructions, myprocessor_instructions) ...and it could infer from the type that it's another enum to be included. Also... (i386_instructions.add == pentium_instructions.add == athlon64_instructions.add == all_instructions.add) == True ...and so on. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: How much does Python optimize?
Em Sex, 2006-03-03 às 10:26 +0100, Blackbird escreveu: > However, range(10) in the command interpreter obviously returns a list. Is > this list optimized away in the code above, or is it actually constructed > internally? (With, say, CPython in one of the recent versions.) It's constructed. That's why you should use xrange. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: object's list index
Em Sex, 2006-03-03 às 12:48 +, William Meyer escreveu: > Kent Johnson kentsjohnson.com> writes: > > > In either case enumerate() is your friend. To find an > > item by identity: > > > > def index_by_id(lst, o): > >for i, item in enumerate(lst): > > if item is o: > >return i > >raise ValueError, "%s not in list" % o > > > > If you just want the index available inside the loop, this replaces your > > original loop: > > for i, object in enumerate(lst): > >print i > > > > Kent > > Thanks, both you and Fredrik Lundh suggested enumerate, which seems like the > best solution. I just need the index inside the loop, but thanks again for > both > solutions. You should *always* use enumerate. "list.index" has a high cost and shouldn't be used that way. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: lists: += vs. .append() & oddness with scope of variables
Em Dom, 2006-03-05 às 11:49 +, Sandro Dentella escreveu: > class foo(object): > > def __init__(self): > print "a: ", a > # += does not work if 'a' is global > #a += [1] > a.append(2) > print "a= ", a Try with: a = [0] class foo(object): def __init__(self): global a print "a: ", a a += [1] a.append(2) print "a= ", a foo() -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python object overhead?
On 3/23/07, Bjoern Schliessmann <[EMAIL PROTECTED]> wrote: > (Note that almost everything in Python is an object!) Could you tell me what in Python isn't an object? Are you counting old-style classes and instances as "not object"s? -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: functions, classes, bound, unbound?
On 24 Mar 2007 20:24:36 -0700, 7stud <[EMAIL PROTECTED]> wrote: > Here is some example code that produces an error: [snip] Why do people absolutely *love* to do weird and ugly things with Python? Contests apart, I don't see lots of people trying this kind of things on other (common) languages. Say with me: "Python is powerful, but I'll use that power *only* for beautiful and straightforward code." Further reading: http://www.python.org/doc/Humor.html#zen -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: maximum number of threads
On 1/10/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote: > At Wednesday 10/1/2007 04:38, Paul Sijben wrote: > >Does anyone know what it going on here and how I can ensure that I have > >all the threads I need? > > Simply you can't, as you can't have 1 open files at once. > Computer resources are not infinite. > Do you really need so many threads? Above a certain threshold, the > program total execution time may increase very quickly. Maybe Stackless could help the OP? http://www.stackless.com/ -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: maximum number of threads
On 1/10/07, Laurent Pointal <[EMAIL PROTECTED]> wrote: This is a system configurable limit (up to a maximum). See ulimit man pages. test ulimit -a to see what are the current limits, and try with ulimit -u 2000 to modify the maximum number of user process (AFAIK each thread use a process entry on Linux) I don't think it's only this. --- $ ulimit -a core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited max nice(-e) 20 file size (blocks, -f) unlimited pending signals (-i) unlimited max locked memory (kbytes, -l) unlimited max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size(512 bytes, -p) 8 POSIX message queues (bytes, -q) unlimited max rt priority (-r) unlimited stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) unlimited virtual memory (kbytes, -v) unlimited file locks (-x) unlimited --- Well, unlimited number user processes. But: --- $ python test.py 50 100 150 200 250 300 350 Exception raised: can't start new thread Biggest number of threads: 382 --- The test.py script is attached. -- Felipe. from thread import start_new_thread from time import sleep def sleeper(): try: while 1: sleep(1) except: if running: raise def test(): global running n = 0 running = True try: while 1: start_new_thread(sleeper, ()) n += 1 if not (n % 50): print n except Exception, e: running = False print 'Exception raised:', e print 'Biggest number of threads:', n if __name__ == '__main__': test() -- http://mail.python.org/mailman/listinfo/python-list
Re: help on packet format for tcp/ip programming
On 7 Feb 2007 19:14:13 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> > struct module pack and unpack will only work for fixed size buffer : > pack('>1024sIL', buffer, count. offset) but the buffer size can vary > from one packet to the next :-( Then send the size of the buffer before the buffer, so the recipient can expect that many bytes. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can I reverse eng a .pyc back to .py?
On 2/19/07, Steven W. Orr <[EMAIL PROTECTED]> wrote: > The short story is that someone left, but before he left he checked in a > .pyc and then both the directory was destroyed and the backups all got > shredded (don't ask*). Is there anything that can be extracted? I looked > on the web and the subject seems to get different answers, all old. Only for .pyc's of Python versions upto 2.3: http://packages.debian.org/unstable/python/decompyle -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Uniquifying a list?
Em Ter, 2006-04-18 às 10:31 -0500, Tim Chase escreveu: > Is there an obvious/pythonic way to remove duplicates from a > list (resulting order doesn't matter, or can be sorted > postfacto)? My first-pass hack was something of the form > > >>> myList = [3,1,4,1,5,9,2,6,5,3,5] > >>> uniq = dict([k,None for k in myList).keys() > > or alternatively > > >>> uniq = list(set(myList)) > > However, it seems like there's a fair bit of overhead > here...creating a dictionary just to extract its keys, or > creating a set, just to convert it back to a list. It feels > like there's something obvious I'm missing here, but I can't > put my finger on it. Your list with 11 elements (7 unique): $ python2.4 -mtimeit -s 'x = [3,1,4,1,5,9,2,6,5,3,5]' 'y = dict((k,None) for k in x).keys()' 10 loops, best of 3: 8.01 usec per loop $ python2.4 -mtimeit -s 'x = [3,1,4,1,5,9,2,6,5,3,5]' $'y = []\nfor i in x:\nif i not in y:\ny.append(i)' 10 loops, best of 3: 5.43 usec per loop $ python2.4 -mtimeit -s 'x = [3,1,4,1,5,9,2,6,5,3,5]' 'y = list(set(x))' 10 loops, best of 3: 3.57 usec per loop A list with 100 000 elements (1 000 unique): $ python2.4 -mtimeit -s 'x = range(1000) * 100' $'y = []\nfor i in x:\n if i not in y:\ny.append(i)' 10 loops, best of 3: 2.12 sec per loop $ python2.4 -mtimeit -s 'x = range(1000) * 100' 'y = dict((k,None) for k in x).keys()' 10 loops, best of 3: 32.2 msec per loop $ python2.4 -mtimeit -s 'x = range(1000) * 100' 'y = list(set(x))' 100 loops, best of 3: 6.09 msec per loop "list(set(x))" is the clear winner with almost O(1) performance. *However*, can't you always use "set" or "frozenset" instead of converting back and forth? HTH, -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: extracting a substring
Em Ter, 2006-04-18 às 17:25 -0700, [EMAIL PROTECTED] escreveu: > Hi, > I have a bunch of strings like > a53bc_531.txt > a53bc_2285.txt > ... > a53bc_359.txt > > and I want to extract the numbers 531, 2285, ...,359. Some ways: 1) Regular expressions, as you said: >>> from re import compile >>> find = compile("a53bc_([1-9]*)\\.txt").findall >>> find('a53bc_531.txt\na53bc_2285.txt\na53bc_359.txt') ['531', '2285', '359'] 2) Using ''.split: >>> [x.split('.')[0].split('_')[1] for x in 'a53bc_531.txt \na53bc_2285.txt\na53bc_359.txt'.splitlines()] ['531', '2285', '359'] 3) Using indexes (be careful!): >>> [x[6:-4] for x in 'a53bc_531.txt\na53bc_2285.txt \na53bc_359.txt'.splitlines()] ['531', '2285', '359'] Measuring speeds: $ python2.4 -m timeit -s 'from re import compile; find = compile("a53bc_([1-9]*)\\.txt").findall; s = "a53bc_531.txt \na53bc_2285.txt\na53bc_359.txt"' 'find(s)' 10 loops, best of 3: 3.03 usec per loop $ python2.4 -m timeit -s 's = "a53bc_531.txt\na53bc_2285.txt \na53bc_359.txt\n"[:-1]' "[x.split('.')[0].split('_')[1] for x in s.splitlines()]" 10 loops, best of 3: 7.64 usec per loop $ python2.4 -m timeit -s 's = "a53bc_531.txt\na53bc_2285.txt \na53bc_359.txt\n"[:-1]' "[x[6:-4] for x in s.splitlines()]" 10 loops, best of 3: 2.47 usec per loop $ python2.4 -m timeit -s 'from re import compile; find = compile("a53bc_([1-9]*)\\.txt").findall; s = ("a53bc_531.txt \na53bc_2285.txt\na53bc_359.txt\n"*1000)[:-1]' 'find(s)' 1000 loops, best of 3: 1.95 msec per loop $ python2.4 -m timeit -s 's = ("a53bc_531.txt\na53bc_2285.txt \na53bc_359.txt\n" * 1000)[:-1]' "[x.split('.')[0].split('_')[1] for x in s.splitlines()]" 100 loops, best of 3: 6.51 msec per loop $ python2.4 -m timeit -s 's = ("a53bc_531.txt\na53bc_2285.txt \na53bc_359.txt\n" * 1000)[:-1]' "[x[6:-4] for x in s.splitlines()]" 1000 loops, best of 3: 1.53 msec per loop Summary: using indexes is less powerful than regexps, but faster. HTH, -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Method Call in Exception
Em Qua, 2006-04-19 às 16:54 -0700, mwt escreveu: > This works when I try it, but I feel vaguely uneasy about putting > method calls in exception blocks. What do you put in exception blocks?! > So tell me, Brave Pythoneers, is this > evil sorcery that I will end up regretting, or is it just plain good > ol' Python magic? IMHO, the exception block in Python is used a lot in places where you could use an if-then-else, like your example that could be written as if internet_available(): [...] #doing some internet stuff else: alternate_method_that_doesnt_need_internet() So yes, I think there's no problem there. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyLint results?
Em Sex, 2006-04-21 às 13:49 -0400, Michael Yanowitz escreveu: >I ran the new pylint and my code and I had a few questions on why those > are warnings or what I can do to fix them: You can ignore the warnings you don't like with the --disable-msg option. Also, you can add a header to the file to apply a rule just to it. > 1) W: 0: Too many lines in module (1587) > Why is 1587 considered too many lines? Would there be necessarily be an >advantage to split it up into 2 or 3 files? Can I up the limit? Because Python is terse, and this can be a really large module. Or not. PyLint is not perfect, maybe you should disable this warning. > 2) C: 0: Missing required attribute "__revision__" >What is this? Is that for CVS? I don't use CVS (we use SVN). I have not >seen any sample code which includes this tag yet. But if I include >__revision 1.0 somewhere in the code it will remove that warning? Don't include the variable just to remove the warning -- disable it. > 3) W:230:readDiscreteData: Using the global statement >What is wrong with using the global statement? Your code can get unmaintainable if you abuse of it. If you really need it and know how to use it well, disable the warning. > 4) W:261:getDiscreteData: Catch "Exception" >What is wrong with that? You may catch things you don't want to catch, like KeyboardInterrupt exceptions. > 5) R:547:readDiscreteData: Too many branches (28/12) >Python doesn't have the switch/case statements that C/C++ have. So I >could have a large block if/elif/else statements. >Is there any way to avoid that? Only splitting the method into 2 or more parts. If that's not possible, disable the warning. > 6) R:722:waitDiscretes: Too many local variables (38/15) >That's new to me. What is wrong with too many local variables? >Can anything be done to improve that besides having too many globals? The more local variables you have, the more difficult the code is to read. Or you use less variables, or you split the method into 2 or more parts, or you disable the warning. > 7) W:933:sendStringToSocket: Redefining name 'nPortNumber' from outer scope > (line >What is wrong with using the same variable name in a function that is > used by its caller? You are hiding something. For example, this code fails strangely (I know this example isn't that good, but you get the idea): files = glob('something/*') for file in files: # do_something filename = do_something_with_the_name(file) # do_something_more contents = file(filename).read() # fails here > 8) W:995:sendStringToSocket: Used builtin function 'map' >Is that a problem? Sometimes it's slower than list comprehensions, sometimes it's less legible than list comp. and IIRC GvR doesn't like it, but if you do, disable the warning. HTH, -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: String To Dict Problem
Em Sex, 2006-04-21 às 18:40 -0700, Clodoaldo Pinto escreveu: > Only a small problem when I try to evaluate this: > > safe_eval('True') Change def visitName(self,node, **kw): raise Unsafe_Source_Error("Strings must be quoted", node.name, node) To otherNames = { 'True': True, 'False': False, 'None': None } def visitName(self, node, **kw): name = node.name try: return self.__class__.otherNames[name] except KeyError: raise Unsafe_Source_Error("Strings must be quoted", name, node) -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list