Re: Is Python a Zen language?
André wrote: Some purist, like the Academie Francaise (or, apparently Crutcher) seem to believe that one can restrict the meaning of words, or the evolution of language. The rest of us are happy to let language evolution take place to facilitate communication. So instead of Zen of Python, we can also call it Spam of Python ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Optimize flag question
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 ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Temporary Variable
Steven D'Aprano wrote: Just out of curiosity, when do you think is the right time to begin teaching programmers good practice from bad? Before or after they've learnt bad habits? When you have authority over the coding guideline. Naming things is not something limited to programming and most people know the importance of choosing the appropriate ones. If on the other hand some names have been chosen that have actual side effect(in python program), like builtin function names, it is appropriate to point that out, though I don't see that case here. -- http://mail.python.org/mailman/listinfo/python-list
Re: A C-like if statement
Steven D'Aprano wrote: On Thu, 23 Feb 2006 16:49:09 -0800, bonono wrote: Steven D'Aprano wrote: On Thu, 23 Feb 2006 12:04:38 -0700, Bob Greschke wrote: try: i = a.find(3) print It's here: , i except NotFound: print No 3's here Nuts. I guess you're right. It wouldn't be proper. Things are added or proposed every day for Python that I can't even pronounce, but a simple 'if (I = a.find(3)) != -1' isn't allowed. Huh. It might be time to go back to BASIC. :) There are *reasons* why Python discourages functions with side-effects. Side-effects make your code hard to test and harder to debug. test.index(a) Traceback (most recent call last): File pyshell#0, line 1, in -toplevel- test.index(a) ValueError: substring not found test.find(a) -1 Did you have a point? It was about your side-effect talk, if you failed to see it, that is fine. BTW, it seems that the term side-effect of function used is a bit different from my understanding of how it is in general used in this field. -- http://mail.python.org/mailman/listinfo/python-list
Re: A C-like if statement
Steven D'Aprano wrote: On Thu, 23 Feb 2006 12:04:38 -0700, Bob Greschke wrote: try: i = a.find(3) print It's here: , i except NotFound: print No 3's here Nuts. I guess you're right. It wouldn't be proper. Things are added or proposed every day for Python that I can't even pronounce, but a simple 'if (I = a.find(3)) != -1' isn't allowed. Huh. It might be time to go back to BASIC. :) There are *reasons* why Python discourages functions with side-effects. Side-effects make your code hard to test and harder to debug. test.index(a) Traceback (most recent call last): File pyshell#0, line 1, in -toplevel- test.index(a) ValueError: substring not found test.find(a) -1 -- http://mail.python.org/mailman/listinfo/python-list
Re: how to break a for loop?
Giovanni Bajo wrote: [EMAIL PROTECTED] wrote: I need to remove zeros from the begining of list, but I can't :-(. I believe the following is almost a direct translation of the above sentence. import itertools as it a=[0,0,0,1,0] a[:]=it.dropwhile(lambda x: x is 0, a) Usa lambda x: x==0 or simply lambda x: x Using 'is' relies on the interpreter reusing existing instances of the immutable object '0', which is an implementation detail. stand corrected. But I don't think lambda x: x is I want as 0 would be false which would stop the dropwhile right away. For this particular case one can even use operator.not_ directly, which skip the lambda(has some peformance advantage). -- http://mail.python.org/mailman/listinfo/python-list
Re: In need of a virtual filesystem / archive
Steven D'Aprano wrote: I suspect you can pick any two of the following three: 1. single file 2. space used for deleted files is reclaimed 3. fast performance Using a proper database will give you 2 and 3, but at the cost of a lot of overhead, and typically a relational database is not a single file. sqlite can give 1-3, it does have overhead but whether it worths it depends on individual judgement based on features, usage pattern etc.. I think monotone use it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Little tool - but very big size... :-(
11MB is seldom a concern for today's machine. Durumdara wrote: Hi ! I have a problem. I have a little tool that can get data about filesystems and wrote it in python. The main user asked me a GUI for this software. This user is needed a portable program, so I create this kind of the software with Py2Exe. But it have very big size: 11 MB... :-( The dist directory: 2006.02.21. 10:09DIR . 2006.02.21. 10:09DIR .. 2005.09.28. 12:4177 824 bz2.pyd 2006.02.21. 10:09 0 dirlist.txt 2006.02.20. 12:51 611 384 library.zip 2006.02.15. 16:2223 558 main.ico 2004.12.16. 17:22 348 160 MSVCR71.dll 2005.09.28. 12:41 1 867 776 python24.dll 2006.01.11. 12:19 102 400 pywintypes24.dll 2005.09.28. 12:41 405 504 unicodedata.pyd 2005.09.28. 12:41 4 608 w9xpopen.exe 2006.01.11. 12:1973 728 win32api.pyd 2006.01.11. 12:2081 920 win32file.pyd 2006.01.11. 12:26 106 496 win32security.pyd 2006.01.10. 19:09 4 943 872 wxmsw26uh_vc.dll 2006.02.20. 12:5140 960 wxPyHDDirList.exe 2005.09.28. 12:4169 632 zlib.pyd 2006.01.10. 19:13 626 688 _controls_.pyd 2006.01.10. 19:12 696 320 _core_.pyd 2006.01.10. 19:13 364 544 _gdi_.pyd 2006.01.10. 19:13 491 520 _misc_.pyd 2006.01.10. 19:13 548 864 _windows_.pyd 20 file11 485 758 byte I need to have more compressed result. Can I compress dll-s, pyd-s with Py2Exe ? Can I decrease the total size with something ? If not, how to I create an self-unpackager and self-starter program that use an temporary directory in the disk ? With WinRar ? Thanx for help: dd -- http://mail.python.org/mailman/listinfo/python-list
Re: Little tool - but very big size... :-(
I doubt you can do much then as you mentioned you need GUI which is why there is the GUI related dll in the list(takes a large chunk of it), then the necessary python runtime. However, even for USB pen, I don't think 11M is that much a big deal. We have digicam that can produce file size like that so finding a large pen drive is not much of an issue. Worse come to worse, convince him to use a 2.5 USB drive container. It is a bit bigger than USB pen drive but can give you 20G+ without external power, just as convenient as a pen drive. Durumdara wrote: Hi ! Yes, it is. But that tool is designed for USB PenDrive usage. The assessor is collect all tools it needed to see a machine(s) in the checked corporation. He/she needs little programs, because he need to store the results of the checkings too, not the tools only. So I need to minimalize the code size. Thanx for help: dd [EMAIL PROTECTED] wrote: 11MB is seldom a concern for today's machine. Durumdara wrote: Hi ! I have a problem. I have a little tool that can get data about filesystems and wrote it in python. The main user asked me a GUI for this software. This user is needed a portable program, so I create this kind of the software with Py2Exe. But it have very big size: 11 MB... :-( The dist directory: 2006.02.21. 10:09DIR . 2006.02.21. 10:09DIR .. 2005.09.28. 12:4177 824 bz2.pyd 2006.02.21. 10:09 0 dirlist.txt 2006.02.20. 12:51 611 384 library.zip 2006.02.15. 16:2223 558 main.ico 2004.12.16. 17:22 348 160 MSVCR71.dll 2005.09.28. 12:41 1 867 776 python24.dll 2006.01.11. 12:19 102 400 pywintypes24.dll 2005.09.28. 12:41 405 504 unicodedata.pyd 2005.09.28. 12:41 4 608 w9xpopen.exe 2006.01.11. 12:1973 728 win32api.pyd 2006.01.11. 12:2081 920 win32file.pyd 2006.01.11. 12:26 106 496 win32security.pyd 2006.01.10. 19:09 4 943 872 wxmsw26uh_vc.dll 2006.02.20. 12:5140 960 wxPyHDDirList.exe 2005.09.28. 12:4169 632 zlib.pyd 2006.01.10. 19:13 626 688 _controls_.pyd 2006.01.10. 19:12 696 320 _core_.pyd 2006.01.10. 19:13 364 544 _gdi_.pyd 2006.01.10. 19:13 491 520 _misc_.pyd 2006.01.10. 19:13 548 864 _windows_.pyd 20 file11 485 758 byte I need to have more compressed result. Can I compress dll-s, pyd-s with Py2Exe ? Can I decrease the total size with something ? If not, how to I create an self-unpackager and self-starter program that use an temporary directory in the disk ? With WinRar ? Thanx for help: dd -- http://mail.python.org/mailman/listinfo/python-list
Re: how to break a for loop?
[EMAIL PROTECTED] wrote: This time it seems that using itertools gives slower results, this is the test code: Understandable, as dropwhile still needs to go through the whole list and the difference will be larger when the list get longer. Though I still prefer that if the list is not horribly long as it is like a spec. But then, one can always name the fast in place del slice version like dropwhileFast. -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic coin flipper program - logical error help
John Zenger wrote: Also, with the functional programming tools of map, filter, and lambda, this code can be reduced to just six lines: import random flips = map(lambda x: random.randrange(2), xrange(100)) heads = len(filter(lambda x: x is 0, flips)) tails = len(filter(lambda x: x is not 0, flips)) Or a filter/map/lambda free way: heads = sum(random.randrange(2) for x in xrange(100)) tails = 100 - heads -- http://mail.python.org/mailman/listinfo/python-list
Re: Quesion about the proper use of __slots__
Zefria wrote: class Fighter: ... '''Small one man craft that can only harm other fighters on their own.''' ... def __init__(self,statsTuple=(50,5,0,(2,4),1)): ... self.fuel = statsTuple[0] ... self.life = statsTuple[1] ... self.armor = statsTuple[2] ... self.weapon = statsTuple[3] ... self.bulk = statsTuple[4] ... __slots__ = [self.fuel,self.life,self.armor,self.weapon,self.bulk] ... ral = Fighter() ral.rocks = 2 ral.rocks 2 ral.life 5 I was reading the special methods, got to slots (http://docs.python.org/ref/slots.html) and decided that i should use this to save memory in the program because it'll have to support very large numbers of fighers at once. It says that once you define slots then you can't add any variables not listed in slots, but from that example section I just did, so am I doing something wrong or did I read it wrong? Seems that __slots__ in your case is nothing but a 'local variable' to the function __init__. I think you need something like this : class Test(object): __slots__ = ['attr1','attr2'] -- http://mail.python.org/mailman/listinfo/python-list
Re: Quesion about the proper use of __slots__
Peter Otten wrote: Zefria wrote: Also, I don't generally do any optimization at all yet (as a highschool student projects get trashed often enough no to bother over), but in this special case I'm expecting each carrier to have up to 150 fighters, and 3 to 5 carriers for each of the two teams, which comes out to be quite large. However, 'large numbers' are more likely to start (picture me looking out of the window) at 100,000 than 10,000 in this context -- and you are at 750... He could be working on a machine with 1M RAM or some other constraints. -- http://mail.python.org/mailman/listinfo/python-list
Re: Quesion about the proper use of __slots__
Zefria wrote: Well, my computer tends to run at about 497 to 501 out of 504 MB of RAM used once I start up Gnome, XMMS, and a few Firefox tabs, and I'd prefer not to see things slipping into Swap space if I can avoid it, and the fighter data would be only part of a larger program. And as I said, learning how to use __slots__ is important enough to hazard a premature guess this time around. If I mess up, the worst that happens is that I have to write down a new variable name in two places instead of one now. For this particular setup, I don't think it would be a concern given your mentioned size as you are very unlikely to be actively using all the apps at the same time and linux is quite efficient in handling it. However, I don't think attempting to use __slots__ in this case is bad either. Afterall, one of the strength of python is allowing you to quickly test out different approachs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Quesion about the proper use of __slots__
Peter Otten wrote: He could be working on a machine with 1M RAM or some other constraints. I have 256K, by the way. Impressive, curious to know what kind of environment it is as it has been a long time I have seen such limited spec. My first x86(IBM PC) had more than that. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to break a for loop?
Gregory Petrosyan wrote: I need to remove zeros from the begining of list, but I can't :-(. I believe the following is almost a direct translation of the above sentence. import itertools as it a=[0,0,0,1,0] a[:]=it.dropwhile(lambda x: x is 0, a) -- http://mail.python.org/mailman/listinfo/python-list
Re: In need of a virtual filesystem / archive
may be store them in sqlite ? On linux, fuse can also be an interesting option, gmailfs is written in python. Enigma Curry wrote: I need to store a large number of files in an archive. From Python, I need to be able to create an archive, put files into it, modify files that are already in it, and delete files already in it. The easy solution would be to use a zip file or a tar file. Python has good standard modules for accessing those types. However, I would tend to think that modifying or deleting files in the archive would require rewriting the entire archive. Is there any archive format that can allow Python to modify a file in the archive *in place*? That is to say if my archive is 2GB large and I have a small text file in the archive I want to be able to modify that small text file (or delete it) without having to rewrite the entire archive to disk. Does anything like this exist? If nothing exists for Python, is there something written in C maybe that I could wrap (preferably you won't suggest wrapping the ext2 filesystem driver.. ;) ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Augmented assignment
Terry Reedy wrote: Program performance might be noticeable if 'x' is something like a.b.c.d that takes some lookup time. But again, I would use the += form for readability without testing run time. Would x=x + 1 be more readable, regardless of the background(whether being introduced to the += form in some other language like C before) ? -- http://mail.python.org/mailman/listinfo/python-list
Re: number ranges (was Re: Matlab page on scipy wiki)
Tim Hochberg wrote: Colin J. Williams wrote: It would be good if the range and slice could be merged in some way, although the extended slice is rather complicated - I don't understand it. The semantics for an extended slicing are as follows. The primary must evaluate to a mapping object, and it is indexed with a key that is constructed from the slice list, as follows. If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the lone slice item is the key. The conversion of a slice item that is an expression is that expression. The conversion of an ellipsis slice item is the built-in |Ellipsis| object. The conversion of a proper slice is a slice object (see section section 4.2 The standard type hierarchy http://www.network-theory.co.uk/docs/pylang/ref_30.html) whose |start|, |stop| and |step| attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting |None| for missing expressions. [source: http://www.network-theory.co.uk/docs/pylang/ref_60.html] The seems to be a bit of a problem with slicing that needs sorting out. The syntax for a slice list appears to allow multiple slices in a list: extended_slicing ::= primary primaries.html#tok-primary [ slice_list slicings.html#tok-slice_list ] slice_list ::= slice_item slicings.html#tok-slice_item (, slice_item slicings.html#tok-slice_item)* [,] but the current interpreter reports an error: a= range(20) a[slice(3, 9, 2)] [3, 5, 7] a[slice(3, 9, 2), slice(5, 10)] Traceback (most recent call last): File interactive input, line 1, in ? TypeError: list indices must be integers Extended slicing has nothing to do with lists. All that gobbeldy gook is trying to tell you is what the interpreter does with O[1:2:3, 4:5:6] where O is some arbitrary object. What it does is: O[1:2:3, 4:5:6] == O[slice(1,2,3), slice(4,5,6)] == O.__getitem__((slice(1,2,3), slice(4,5,6))) In the case of python lists, __getitem__ doesn't support multiple slice arguments. However, you are free to define your own types which do support multiple slices. That explains it but the current documentation in the reference manual doesn't(I also tried what Colin did when reading that part). And as I mentioned in another post, the current documentation suggests that extended slicing is not supported for sequence type. As it said the primary must be evaluated to mapping object for extended slicing. Though it seems it doesn't matter as all python does now is turn [start:stop:stride] into slice object and pass that to __getitem__, no matter what object it is. -- http://mail.python.org/mailman/listinfo/python-list
Re: getting the line just before or after a pattern searched
[EMAIL PROTECTED] wrote: hi i have a file something like this abcdefgh ijklmnopq 12345678 rstuvwxyz . . . 12345678 . whenever i search the file and reach 12345678, how do i get the line just above and below ( or more than 1 line above/below) the pattern 12345678 and save to variables? thanks I would try something similar to the pairwise recipe here : http://www.python.org/doc/2.4.2/lib/itertools-recipes.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Print a PDF transparently
Daniel Crespo wrote: Yes, I've seen it, but that's it: another program that I have to install, which I want to avoid. I'd be happy if I just do printer.Print(file.pdf/.ps) and walá, the printing just starts (in 98,2000,XP... sounds like a dream), without having another window opened. If it opens, but then closes, it's perfect too. I have done such thing a few years back, just use the file association and the print/printto action. All you need is to have Acrobat installed. You can try it by right click on the desktop on a .PDF file and select print. A modeless dialog would still be visible but would close itself. This was using ancient Acrobat Reader. You need to read the WIN32 API(I faintly remembered about Shell something) that tells you how to do it programmatically(I used C). All this has to be easilly installed (with InnoSetup, for example), because I have to install it on 70 offices. So I can't leave it to another installation process. All of these offices have a dot matrix printers Epson LX-300, which has PostScript level 3 built-in. Where can I find how to send a .ps directly to the printer? Again, in the WIN32 API and unfortunately 98 and NT family has completely different mechanism. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie
This is top posting, i.e. my post is above yours. For this particular response, it seems to be a bit more appropriate to do bottom posting, see below. However, don't take that as a rule or convention that you need to do one or another exclusively, it depends and I believe mature and sincere posters would know when to do which. LittlePython wrote: I have no idea what top-posting or bottom-posting is? This is bottom posting, where people can refer to what I am answering to, right above this line/paragraph. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to cat None
Seems that what you want to do is to create a string in the form of : 55Init=Init\n55First=first\n55Last=Last\n55Alias=None for each dictionary. If that is the case, may be you can try this : \n.join(%s=%s % x for x in user1.iteritems()) Note that you cannot control the ordering of the keys when iterating a dict which may or may not be a concern for you. LittlePython wrote: I found out the hard way that I can not cat None. I get an error. Is there a simple way to cat None without doing some kind of equation ( if this then that). Is there a isNone() somewhere. I am not too sure I know what None really means. I include an example to show what I am talking about in case I am alittle confused. from easygui import * import string msgbox('Starting Program') thisfile = fileopenbox(msg='Choose the correct File', title='Matrix Input File') input = file(thisfile,'r') header = string.split(string.strip(input.readline()),',') header.extend(['55FirstName', '55Intial','55LastName','55Alias',]) all = input.readlines() input.close input = None matrix = {} for user in all: user1 = string.split(string.strip(user),',') user1.extend(['None']*4)-I would like to None or better NULL this instead of string it user1 = dict(zip(header,user1)) matrix[user1['OldNTLogon']] = user1 mychoice = choicebox(choices=matrix.keys()) user1 = matrix[mychoice] alltogether = '' for KeyName in user1.keys(): if alltogether == '': alltogether = KeyName + '=' + ' ' + user1.get(KeyName) + '\n' else: alltogether = alltogether + KeyName + '=' + user1.get(KeyName) + '\n' --- error 'can not cat None with a str' or something like that msgbox(alltogether,'User Matrix for '+ mychoice ) msgbox('The End') -- http://mail.python.org/mailman/listinfo/python-list
Re: how to write a C-style for loop?
John Salerno wrote: for (int i = 0; i 50; i += 5) How would that go in Python, in the simplest and most efficient way? for i in xrange(0,50,5): print i -- http://mail.python.org/mailman/listinfo/python-list
Re: Loop Backwards
[EMAIL PROTECTED] wrote: Dave wrote: This should be simple, but I can't get it: How do you loop backwards through a list? For example, in, say, Javascript: for (var i = list.length - 1; i =0; i--) { do_stuff() } I mean, I could reverse the list, but I don't want to. I want it to stay exactly the same, but I want to start at the end and end at the beginning. Negative indexes start at the opposite end than positive indexes. s = [1,2,3,4,5] for i in range(len(s)): print s[-i-1], 5 4 3 2 1 I thought the python way is to use slice : range(10)[::-1] -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python very slow compared to C
[EMAIL PROTECTED] wrote: Steven D'ApranoVery slow to do what, compared to what? The decay time of the tau meson? 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=alllang=pythonlang2=ocaml This is even more interesting: http://shootout.alioth.debian.org/gp4/benchmark.php?test=alllang=pythonlang2=lua However, to me, the strength of python is the batteries that is included(and there are more and more coming). -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python very slow compared to C
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. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python very slow compared to C
Steven D'Aprano wrote: But, in general, more often than not, Python is fast enough. The extra value of using something like Lua or Ocaml or even C is just not enough to make up for the disadvantages of using those languages. What is the disavantage of Lua comparing with Python ? Or Ocaml comparing with Python ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python very slow compared to C
Steven D'Aprano wrote: Lua appears to be *too* lightweight, without even classes or inheritance, and a single data type where Python has dicts, sets, tuples and lists. I believe Lua does have features to implement class/inheritance. As for the distinction of dict/set/tuple/list or one single table data type(which can be used as either dict or list and implemented as set, not sure about tuple), it is up to debate. Though I have mentioned in another post that the batteries in Python is extremely appealing to solve real world problems as no matter how good a language can be, re-implementing something from scratch is always a pain(and error prone). -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python very slow compared to C
Steven D'Aprano wrote: Programming in Lua Object-Oriented Programming http://www.lua.org/pil/16.html Did you actually bother to read the page you linked to? It describes how you can emulate object-like behaviour for Lua tables. The following page is even more explicit: Lua does not have the concept of class. That means that the object-oriented framework, which you get for free in Python, has to be at least partially handled by the programmer in Lua. Perhaps Lua makes it easy to do, but it is still something that doesn't need to be done in Python because it is already there. Lua does not have a concept of class doesn't mean it doesn't have the concept/framework of OO. It seems to be using a prototype based OO framework similar to javascript. So one can have features like inheritance without class. I can speak the same about Python if I view it from a prototype based perspective, where one get them for free in Lua but need to implement them in Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie
LittlePython wrote: I am very new to python. I have been studying it for only a month or so. I have been using vbscript for about 2-3 yrs and only recently been using it rather heavily the past 9 months or so. I am new very new to oop. My main use will be administrative scripting into the win3k, XP, AD domain, 55exchange and 2003exchange environments. I like to incorp wxpython (GUI) into my scripts instead of HTA's that I have been using with VBS. I am also finding myself being tasked with jobs that are outside the scope of VBS. Well that's a lot to learn and I have a feeling that to many I am just another member of The Ministry of STUPID Questions Out of curiosity, why python ? The new VB.Net seems to be a very interesting one language wise and given that you have a VB experience, it seems to be a natural one to try. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python very slow compared to C
Steven D'Aprano wrote: [EMAIL PROTECTED] wrote: I can speak the same about Python if I view it from a prototype based perspective, where one get them for free in Lua but need to implement them in Python. Sure. And if you need prototypes, then all else being equal that would be a disadvantage of Python compared to Lua. On the other hand, I'd suggest that far more programmers are familiar with classes than prototypes, regardless of any objective advantages or disadvantages of one over the other. Perhaps that's one of the reasons why Lua is lacking the market penetration of Python: programmers may look at it and say No classes? Prototyping? WTF is that? I don't have time to learn something so different, better stick to languages which have a smaller learning curve. The = operator in Python is also quite different from many language people had experience like C or VB etc. And using the same argument, everyone may still be programming in COBOL now. And if we use market penetration as measure, Perl seems to be easier for people ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python very slow compared to C
PA wrote: On Feb 13, 2006, at 06:44, [EMAIL PROTECTED] wrote: And if we use market penetration as measure, Perl seems to be easier for people ? Perl: Shell scripts/awk/sed are not enough like programming languages. Python: Perl is a kludge. What Languages Fix http://www.paulgraham.com/fix.html Cheers Where is the entry for Lua and Haskell, both I found very interesting. -- http://mail.python.org/mailman/listinfo/python-list
Re: functional 0.5 released
Collin Winter wrote: On 10 Feb 2006 19:57:48 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Collin Winter wrote: As always, feedback welcome! Any specific reason flip only flip the first 2 arguments rather than the whole tuple ? That is, I would like to see: assert(f(a,b,c, d) == flip(f)(d, c, b, a)) Because that's what I'm used to from Haskell and other functional languages : ) I'll see what I can do about having it flip all arguments in the next release. Thanks for looking into it. BTW, I do a quick test on the C version(supposed to be faster) and found something interesting: Your partial implementation is slower than new.instancemethod(func, arg, object), may be you would like to have some micro optimization to use that instead for the special case(and I believe over 70% of the case) of : partial(func, arg) Another thing I am wondering is if a compose_m(which means f(*g(*arg,**kw)) ) is desirable as that would give me a choice if I want to expand the result of g(if it is a tuple) to multi-argument rather than single tuple. This is not a problem in Haskell which is fully curried but python in general is not. Another option may be a helper function like unpack in lua. So I can do compose(compose(f, unpack), g) which means f(unpack(g(*arg,**kw))). -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about idioms for clearing a list
Raymond Hettinger wrote: [Alex] So what is the rationale for having list SO much harder to use in such a way, than either set or collections.deque? Sounds like a loaded question ;-) If you're asking why list's don't have a clear() method, the answer is that they already had two ways to do it (slice assignment and slice deletion) and Guido must have valued API compactness over collection polymorphism. The latter is also evidenced by set.add() vs list.append() and by the two pop() methods having a different signatures. Sounds to me that it is a preference(style, whatever), rather than some other posts of this thread argued that del L[:] is better. If you're asking why your specific case looked so painful, I suspect that it only looked hard because the adaptation was force-fit into a lambda (the del-statement or slice assignment won't work as an expression). You would have had similar difficulties embedding try/except logic or a print-statement. Guido, would of course recommend using a plain def-statement: L = list() def L_clearer(L=L): del L[:] for listbunch in buncher(src, '', L, L.append, L_clearer): print listbunch Is that really clearer ? While it is still very localized(just read a few lines up for the definition), buncher(src, '', L.append, L.clear) seems to be clearer to me, especially there are two similar construct on set/dict above, even the Alex's lambda form conveys more info, IMO. Usng the new partial function, may be it can be written as : buncher(src.'', L, L.append, partial(L.__delslice__, 0, sys.maxint)) #assuming list can have at at most maxint items. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about idioms for clearing a list
Magnus Lycka wrote: class BryansList(list): ... add=list.append ... def clear(self): ... del self[:] ... b = BryansList([1,2,3,4,5]) b [1, 2, 3, 4, 5] b.add(6) b.clear() b [] Happy now? You can keep it, I don't need it. :) Most of us consider minimal interfaces a virtue. What kind of performance penalty are we talking about here ? list being such a fundamental thing, no one would like to use a slower version just for the clear/add method. And if it is a use when you really need to, it would make the code harder to understand as it would be sometimes it is BryansList, sometimes it is builtin list. That said, I don't find clear() to be useful as unless one needs to pass around a single copy of list object around and saved them for future use(which can be a source of subtle bug), just lst=[] is usually good enough for localized usage. -- http://mail.python.org/mailman/listinfo/python-list
Re: ordered sets operations on lists..
Amit Khemka wrote: Hello, Is there a *direct* way of doing set operations on lists which preserve the order of the input lists ? For Ex. l1 = [1, 5, 3, 2, 4, 7] l2 = [3, 5, 10] and (l1 intersect l2) returns [5, 3] (and (l2 intersect l1) returns [3, 5]) what do you mean by direct way ? ugly(some said) one liner ? filter(set(l1).intersection(set(l2)).__contains__, l1) filter(set(l1).intersection(set(l2)).__contains__, l2) -- http://mail.python.org/mailman/listinfo/python-list
Re: ordered sets operations on lists..
Raymond Hettinger wrote: The intersection step is unnecessary, so the answer can be simplified a bit: filter(set(l2).__contains__, l1) [5, 3] filter(set(l1).__contains__, l2) [3, 5] stand corrected. -- http://mail.python.org/mailman/listinfo/python-list
Re: functional 0.5 released
Collin Winter wrote: As always, feedback welcome! Any specific reason flip only flip the first 2 arguments rather than the whole tuple ? That is, I would like to see: assert(f(a,b,c, d) == flip(f)(d, c, b, a)) -- http://mail.python.org/mailman/listinfo/python-list
Re: removing characters before writing to file
[EMAIL PROTECTED] wrote: hi i have some output that returns a lines of tuples eg ('sometext1', 1421248118, 1, 'P ') ('sometext2', 1421248338, 2, 'S ') and so on I tried this re.sub(r '() ,'',str(output)) but it only get rid of the ' and not the braces. I need to write the output to a file such that sometext1, 1421248118, 1, P sometext2, 1421248338, 2, S I also tried escaping , re.sub(r '\(\) ,'',str(output)) but also did not work How can i get rid of the braces before writing to file? thanks If it is as uniform as shown, may be you can strip them. ('something', 1234, 1, 'P ').strip( ()) -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about idioms for clearing a list
Fredrik Lundh wrote: Python now has, what, three built-in mutable collections types: lists, dictionaries, and sets. Dicts and sets both have a clear() method and lists do not. dicts and sets are mappings, and lists are not. mappings don't support slicing. lists do. I am confused. Could you explain this ? I was under the impression said above(mapping don't support slicing), until after I read the language reference. I don't think it is slicing as in the list slicing sense but it does use the term extend slicing. http://www.python.org/doc/2.4.2/ref/slicings.html The semantics for an extended slicing are as follows. The primary must evaluate to a mapping object, and it is indexed with a key that is constructed from the slice list, as follows. If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the lone slice item is the key. The conversion of a slice item that is an expression is that expression. The conversion of an ellipsis slice item is the built-in Ellipsis object. The conversion of a proper slice is a slice object (see section 3.2) whose start, stop and step attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting None for missing expressions. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about idioms for clearing a list
Tim Hochberg wrote: [EMAIL PROTECTED] wrote: Fredrik Lundh wrote: Python now has, what, three built-in mutable collections types: lists, dictionaries, and sets. Dicts and sets both have a clear() method and lists do not. dicts and sets are mappings, and lists are not. mappings don't support slicing. lists do. I am confused. Could you explain this ? I was under the impression said above(mapping don't support slicing), until after I read the language reference. I don't think it is slicing as in the list slicing sense but it does use the term extend slicing. http://www.python.org/doc/2.4.2/ref/slicings.html The semantics for an extended slicing are as follows. The primary must evaluate to a mapping object, and it is indexed with a key that is constructed from the slice list, as follows. If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the lone slice item is the key. The conversion of a slice item that is an expression is that expression. The conversion of an ellipsis slice item is the built-in Ellipsis object. The conversion of a proper slice is a slice object (see section 3.2) whose start, stop and step attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting None for missing expressions. This is in place to support multidimensional arrays, such as in numpy. If, for instance, you have a 9x9 array A, then A[3:6,3:6] will extract a 3x3 block from the center of it. A[3:6,3:6] is equivalent to A[(slice(3,6,None), slice(3,6,None))] and the resulting tuple gets passed through the mapping interface, but it is not a mapping in any real sense. I don't think there's anything in core Python that uses this and it's not really relevant to this thread. Thanks. I would say that it is not relevant to the OP's question but the thread has turned to anyone who read the doc should know about slicing and that prompted me to go and read the doc(I don't have the OP's mentioned need in my coding so far and never read about the full pontential of slicing, just use it as the right hand side intuitively) about slicing and found the documentation to be a bit lacking(only a brief mentioning of slicing in the turtorial and this confusing section). Beside, just from reading this page, it seems that a[start:stop:stride] is not a valid construction for sequence object 'a'. To me, reading the doc makes me more confuse about what is slicing. -- http://mail.python.org/mailman/listinfo/python-list
Re: new.instancemethod as a form of partial()
Alex Martelli wrote: Guido has mused about abolishing unbound methods (in 3.0, I guess), so there's hope for the future. But a more complete 'partial' is likely to be acceptable sooner than any fix to bound/unbound methods: I suspect the only ingredient that's missing is a generous helping of irrefutable use cases. So long the new partial() has this case covered, it is fine. As it seems that this recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 also forgot this special case(down to the bottom, the current curry code). -- http://mail.python.org/mailman/listinfo/python-list
new.instancemethod as a form of partial()
I came across this while searching for a way to DIY partial(), until it is available in 2.5 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/229472 However, when trying for the following, it doesn't work and is wondering if it is a bug or intended : import operator import new new.instancemethod(operator.is_,None,object)(None) Traceback (most recent call last): File pyshell#5, line 1, in -toplevel- new.instancemethod(operator.is_,None,object)(None) TypeError: is_ expected 2 arguments, got 1 new.instancemethod(operator.is_,False,object)(False) True So it seems that instancemethod() don't like None as the instance. -- http://mail.python.org/mailman/listinfo/python-list
Re: new.instancemethod as a form of partial()
Alex Martelli wrote: [EMAIL PROTECTED] wrote: ... So it seems that instancemethod() don't like None as the instance. bound methods and unbound methods are instance of the same type, distinguished by one thing: the im_self of an unbound method is None, the im_self of a bound method is anything else. So, when you pass None as the instance, instancemethod likes it just fine... and returns an unbound method as the result, so you haven't actually achieved your goal (you must still pass the first parameter explicitly -- all you've gained by wrapping a function into an unbound method is an implicit typecheck on the first argument, and if, as the class, you're using 'object' as in your example, that's not much use [even in other cases, it's no great shakes;-)]). thanks. So in this special case, None is being treated as a flag rather than just an instance(I just read the doc) like any other instance and the behaviour is intended. Is there any reason why it is designed this way ? -- http://mail.python.org/mailman/listinfo/python-list
Re: list comprehention
Tim Chase wrote: Python beginner here and very much enjoying it. I'm looking for a pythonic way to find how many listmembers are also present in a reference list. Don't count duplicates (eg. if you already found a matching member in the ref list, you can't use the ref member anymore). Example1: ref=[2, 2, 4, 1, 1] list=[2, 3, 4, 5, 3] solution: 2 Example2: ref=[2, 2, 4, 1, 1] list=[2, 2, 5, 2, 4] solution: 3 (note that only the first two 2's count, the third 2 in the list should not be counted) It sounds like you're looking for set operations: (using ell for clarity) from sets import Set a = [2,2,4,1,1] b = [2,3,4,5,3] setA = Set(a) setB = Set(b) results = setA.intersection(setB) results Set([2,4]) intersection = [x for x in results] intersection [2,4] won't set remove duplicates which he wants to preserve ? He is not just looking for the 'values' that is in common, but the occurence as well, if I understand the requirement correctly. I would just build a dict with the value as the key and occurence as the value then loop the list and lookup. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can a simple a==b 'hang' in and endless loop?
Fuzzyman wrote: Claudio Grondi wrote: Steve Holden wrote: [snip..] The problem here is, that I mean, that in Python it makes no sense to talk about a value of an object, because it leads to weird things when trying to give a definition what a value of an object is. You're saying that C and Java get round that problem by sometimes defining value to mean 'the memory address and object is stored at'. That hardly seems to clarify what value *really* means, and can lead to some interesting confusions. Anyway - for the basic datatypes 'value' seems quite clear. It's only not clear what this might mean in user defined classes - where value means whatever you define it to mean. I don't know much about Java but in C, I fail to see any confusion. There is no such thing as user defined classes nor operator overload. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can a simple a==b 'hang' in and endless loop?
Fuzzyman wrote: The above gentleman is asserting that in *Python* the term value has no meaning. I don't know what he meant and don't want to get into that value/reference/object thingy discussion as it would be a never ending thing. I just want to say that '==' in C is very clear to me, whether it is as useful(correct) as in python or C++ or other higher level language is another issue. But what would be the interesting confusion that you envision ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Can a simple a==b 'hang' in and endless loop?
Fuzzyman wrote: Ok... so I'm now assuming that the information about '==' provided by the above gentleman *and* that I understand it correctly. The only confusion in C (which doesn't have classes) is that two list (like) objects can't be tested by value - only identity. In C, they are compared(the '==' operator) byte by byte, I don't know if you interpret that as by value or identity. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can a simple a==b 'hang' in and endless loop?
Claudio Grondi wrote: As also the fact, that when a = [1,2.0,3L] b = [1.0,2,3 ] a==b # gives True even if the objects in the lists are actually different, or when the objects being members of the list redefine __eq__ so, that no matter how different they are, the lists always compare True. Can't you use a is b in this case to test for what you want ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Can a simple a==b 'hang' in and endless loop?
Fuzzyman wrote: I'm not familiar with the C basic datatypes - I assume it has an array or list like object. Would it contain a sequence of poitners to the members ? In which case they would only be equal if the pointers are the same. In this case : a = ['some string'] b = ['somestring'] a == b False (probably) Incorrectly using Python syntax for a C example of course :-) That depends, the C syntax is like this : char *a=hello; char *b=hello; assert(a==b); // true, the compiler knows the two hello are the same and assign the same address(sort of id() in python) to a and b But the following is not char *a=hello; char *b=_hello; char *c=b+1; assert(a==c); //false, even the content they point to are the same However, string in the above are not basic types of C and if you want to compare the value(like comparing integer), you need to use function like strcmp() which again compare byte by byte in the above example and give true. -- http://mail.python.org/mailman/listinfo/python-list
Re: Listing partitions (on win32)
Tim Golden wrote: Claude Henchoz wrote: Is there any way of listing partitions on a (win32) computer without using WMI? Not that this answers your question, but why _don't_ you want to use WMI? TJG import wmi Traceback (most recent call last): File pyshell#0, line 1, in -toplevel- import wmi ImportError: No module named wmi -- http://mail.python.org/mailman/listinfo/python-list
Re: Listing partitions (on win32)
Tim Golden wrote: [EMAIL PROTECTED] wrote: Tim Golden wrote: Claude Henchoz wrote: Is there any way of listing partitions on a (win32) computer without using WMI? Not that this answers your question, but why _don't_ you want to use WMI? TJG import wmi Traceback (most recent call last): File pyshell#0, line 1, in -toplevel- import wmi ImportError: No module named wmi It's quite possible to do WMI in Python without using the wmi module -- all the module does is to hide some slightly messy plumbing. But the OP doesn't suggest that he's unwilling to install anything, merely to *use* WMI. (Unless you _are_ the OP under a different alias). Just to make it plain: it's no skin off my nose at all. I don't get offended because someone doesn't want to use WMI. I'm merely curious as to whether it was because the wmi module was too hard, or whether the machines were Win9x or NT, where you have to go out of your way to install WMI, or whether there was some other reason. I am not him, but just another data point(possibly reason) of why one doesn't want to use it. It is not intended to be a post of wmi suck. In fact, when I first saw the post about wmi module, I immediate tried to query my XP using it but once I saw the above, I gave up. -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 309 (Partial Function Application) Idea
Giovanni Bajo wrote: Ronald Mai wrote: Here is a reference implementation: _ = lambda x: x.pop(0) def partial(func, *args, **keywords): def newfunc(*fargs, **fkeywords): newkeywords = keywords.copy() newkeywords.update(fkeywords) newargs = (lambda seq: tuple([(a == _ and a(seq)) or a for a in args] + seq))(list(fargs)) return func(*newargs, **newkeywords) newfunc.func = func newfunc.args = args newfunc.keywords = keywords return newfunc Here is example of use: def capture(*args): return args partial(capture)() () partial(capture, _)(1) (1,) partial(capture, _, 2)(1) (1, 2) partial(capture, 1)(2) (1, 2) partial(capture, 1, _)(2) (1, 2) partial(capture, 1, _)() IndexError: pop from empty list partial(capture, 1, _, _)(2, 3) (1, 2, 3) Other implementations I have seen (boost::bind comes to mind) use ordered placeholders such as _1, _2, _3, etc to provide more flexibility in adaptation: partial(capture, a, _1, _2)(b, c) (a, b, c) partial(capture, a, _2, _1)(b, c) (a, c, b) I don't see mention of this in the PEP, but it's a nice feature to have IMO. -- Giovanni Bajo Since python has named parameter(and I assume this PEP would support it as well), is it really that useful to have these place holder things ? As when the parameter list gets long, named param should be easier to read. The only case I find it useful is for binary ops where I would like to either bind the left hand side or the right hand side but that can be handled easily with a flip function as in haskell. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to remove subset from a file efficiently?
fynali wrote: [bonono] Have you tried the explicit loop variant with psyco ? Sure I wouldn't mind trying; can you suggest some code snippets along the lines of which I should try...? [fynali] Needless to say, I'm utterly new to python and my programming skills know-how are rudimentary. (-: -- fynali just add : import psyco psyco.full() to the beginning of the code from Fredrik for 2.2(the one using dict and list comprehension). You system may not have the psyco module though. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to remove subset from a file efficiently?
fynali wrote: $ cat cleanup_use_psyco_and_list_compr.py #!/usr/bin/python import psyco psyco.full() postpaid_file = open('/home/sajid/python/wip/stc/2/PSP333') outfile = open('/home/sajid/python/wip/stc/2/PSP-CBR.dat.psyco', 'w') barred = {} for number in open('/home/sajid/python/wip/stc/2/CBR333'): barred[number] = None # just add it as a key outfile.writelines([number for number in postpaid_file if number not in barred]) postpaid_file.close(); outfile.close() -- $ time ./cleanup_use_psyco_and_list_compr.py real0m39.638s user0m5.532s sys 0m0.868s This was run on my machine (w/ Python 2.4.1), can't install psyco on the actual server at the moment. I guess using generators newer Python is indeed faster|better. -- fynali um, strange, so psyco is slower than not using it ? you may try to expand the list comprehension to : for number in postpaid_file: if number not in barred: outfile.writelines(number) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to remove subset from a file efficiently?
fynali wrote: Sorry, pls read that ~15 secs. That is more or less about it. As set() is faster than dict(), about 2x on my machine and I assume a portion of your time is in set/dict creation as it is pretty large data set. -- http://mail.python.org/mailman/listinfo/python-list
Re: flatten a level one list
Peter Otten wrote: [EMAIL PROTECTED] wrote: David Murmann wrote: # New attempts: from itertools import imap def flatten4(x, y): '''D Murman''' l = [] list(imap(l.extend, izip(x, y))) return l well, i would really like to take credit for these, but they're not mine ;) (credit goes to Michael Spencer). i especially like flatten4, even if its not as fast as the phenomenally faster flatten7. Me too. And expand a bit on flatten4, I got this interesting result. [EMAIL PROTECTED]:~/bonobo/psp$ python ~/lib/python2.4/timeit.py -s import itertools; a=zip(xrange(1000),xrange(1000)) l=len(a); li=[None]*l*2;li[::2]=range(1000); li[1::2]=range(1000) 1000 loops, best of 3: 318 usec per loop [EMAIL PROTECTED]:~/bonobo/psp$ python ~/lib/python2.4/timeit.py -s import itertools,psyco; a=zip(xrange(1000),xrange(1000));li=[] filter(li.extend,a) 1000 loops, best of 3: 474 usec per loop For a fair comparison you'd have to time the zip operation. Still 50% slower but it has the advantage that it works on all kinds of sequence as they can be efficiently izip() together. Creating a list via list/map/filter just for the side effect is not only bad taste, ~ $ python -m timeit -s'a = zip([range(1000)]*2)' 'lst=[];ext=lst.extend' 'for i in a: ext(i)' 100 loops, best of 3: 1.23 usec per loop ~ $ python -m timeit -s'a = zip([range(1000)]*2)' 'lst=[];filter(lst.extend, a)' 100 loops, best of 3: 1.63 usec per loop it is also slower than an explicit loop. Don't do it. Hi, but I found this result instead : [EMAIL PROTECTED]:~$ python ~/lib/python2.4/timeit.py -s a=range(1); b=zip(*[a]*2); l=[None]*len(a)*2; e=l.extend l[::2]=b;l[1::2]=b 100 loops, best of 3: 6.22 msec per loop [EMAIL PROTECTED]:~$ python ~/lib/python2.4/timeit.py -s a=range(1); b=zip(*[a]*2); l=[]; e=l.extend filter(e,b) 100 loops, best of 3: 7.25 msec per loop [EMAIL PROTECTED]:~$ python ~/lib/python2.4/timeit.py -s a=range(1); b=zip(*[a]*2); l=[]; e=l.extend for x in b: e(x) 100 loops, best of 3: 10.7 msec per loop [EMAIL PROTECTED]:~$ So it seems to be faster than explicit loop. By localizing the l.extend name binding, its speed is only 20% slower than the fastest method. May be I have done something wrong in the test ? -- http://mail.python.org/mailman/listinfo/python-list
Re: flatten a level one list
Peter Otten wrote: [EMAIL PROTECTED] wrote: David Murmann wrote: # New attempts: from itertools import imap def flatten4(x, y): '''D Murman''' l = [] list(imap(l.extend, izip(x, y))) return l well, i would really like to take credit for these, but they're not mine ;) (credit goes to Michael Spencer). i especially like flatten4, even if its not as fast as the phenomenally faster flatten7. Me too. And expand a bit on flatten4, I got this interesting result. [EMAIL PROTECTED]:~/bonobo/psp$ python ~/lib/python2.4/timeit.py -s import itertools; a=zip(xrange(1000),xrange(1000)) l=len(a); li=[None]*l*2;li[::2]=range(1000); li[1::2]=range(1000) 1000 loops, best of 3: 318 usec per loop [EMAIL PROTECTED]:~/bonobo/psp$ python ~/lib/python2.4/timeit.py -s import itertools,psyco; a=zip(xrange(1000),xrange(1000));li=[] filter(li.extend,a) 1000 loops, best of 3: 474 usec per loop For a fair comparison you'd have to time the zip operation. Still 50% slower but it has the advantage that it works on all kinds of sequence as they can be efficiently izip() together. Creating a list via list/map/filter just for the side effect is not only bad taste, ~ $ python -m timeit -s'a = zip([range(1000)]*2)' 'lst=[];ext=lst.extend' 'for i in a: ext(i)' 100 loops, best of 3: 1.23 usec per loop ~ $ python -m timeit -s'a = zip([range(1000)]*2)' 'lst=[];filter(lst.extend, a)' 100 loops, best of 3: 1.63 usec per loop it is also slower than an explicit loop. Don't do it. ah, stand corrected. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to remove subset from a file efficiently?
fynali wrote: $ cat cleanup_ray.py #!/usr/bin/python import itertools b = set(file('/home/sajid/python/wip/stc/2/CBR333')) file('PSP-CBR.dat,ray','w').writelines(itertools.ifilterfalse(b.__contains__,file('/home/sajid/python/wip/stc/2/PSP333'))) -- $ time ./cleanup_ray.py real0m5.451s user0m4.496s sys 0m0.428s (-: Damn! That saves a bit more time! Bravo! Thanks to you Raymond. Have you tried the explicit loop variant with psyco ? My experience is that psyco is pretty good at optimizing for loop which usually results in faster code than even built-in map/filter variant. Though it would just be 1 or 2 sec difference(given what you already have) so may not be important but could be fun. -- http://mail.python.org/mailman/listinfo/python-list
Re: flatten a level one list
Robin Becker wrote: Paul Rubin wrote: Paul Rubin http://[EMAIL PROTECTED] writes: import operator a=[(1,2),(3,4),(5,6)] reduce(operator.add,a) (1, 2, 3, 4, 5, 6) (Note that the above is probably terrible if the lists are large and you're after speed.) yes, and it is all in C and so could be a contender for the speed champ. I guess what you're saying is that it's doing That is what I thought too but seems that [x for pair in li for x in pair] is the fastest on my machine and what is even stranger is that if I use psyco.full(), I got a 10x speed up for this solution(list comprehension) which is head and shoulder above all the other suggested so far. -- http://mail.python.org/mailman/listinfo/python-list
Re: flatten a level one list
David Murmann wrote: Robin Becker schrieb: # New attempts: from itertools import imap def flatten4(x, y): '''D Murman''' l = [] list(imap(l.extend, izip(x, y))) return l from Tkinter import _flatten def flatten5(x, y): '''D Murman''' return list(_flatten(zip(x, y))) well, i would really like to take credit for these, but they're not mine ;) (credit goes to Michael Spencer). i especially like flatten4, even if its not as fast as the phenomenally faster flatten7. Me too. And expand a bit on flatten4, I got this interesting result. [EMAIL PROTECTED]:~/bonobo/psp$ python ~/lib/python2.4/timeit.py -s import itertools; a=zip(xrange(1000),xrange(1000)) l=len(a); li=[None]*l*2;li[::2]=range(1000); li[1::2]=range(1000) 1000 loops, best of 3: 318 usec per loop [EMAIL PROTECTED]:~/bonobo/psp$ python ~/lib/python2.4/timeit.py -s import itertools,psyco; a=zip(xrange(1000),xrange(1000));li=[] filter(li.extend,a) 1000 loops, best of 3: 474 usec per loop Still 50% slower but it has the advantage that it works on all kinds of sequence as they can be efficiently izip() together. -- http://mail.python.org/mailman/listinfo/python-list
Re: String question - find all possible versions of a person's firstname
Nico Grubert wrote: This sounds like a homework problem. You might try splitting the name at the e's, check the length of the resulting list and do that many nested loops. This was my idea too but I am wondering if there are any scripts for tasks like this. Nico def combine_lol(seq): return reduce(lambda x,y: (a+(b,) for a in x for b in y), seq, [()]) def shuffle(seq, elem): hello,eo - helle,hello,hollo,hollo idx = [i for (i,c) in enumerate(seq) if c in elem] l = 2**len(idx) com = combine_lol([elem]*len(idx)) pos = ( zip(*x) for x in izip([idx]*l, com) ) def replace(s, ki): for i,e in ki: s[i] = e return s r = imap(replace, (list(seq) for x in xrange(l)), pos) if isinstance(seq,basestring): return ( ''.join(x) for x in r) else: return r -- http://mail.python.org/mailman/listinfo/python-list
Re: flatten a level one list
Robin Becker wrote: Is there some smart/fast way to flatten a level one list using the latest iterator/generator idioms. The problem arises in coneverting lists of (x,y) coordinates into a single list of coordinates eg f([(x0,y0),(x1,y1),]) -- [x0,y0,x1,y1,] or g([x0,x1,x2,..],[y0,y1,y2,]) -- [x0,y0,x1,y1,] clearly if f is doable then g can be done using zip. I suppose this is a special case flatten, but can flatten be done fast? The python recipes seem rather slow compared to the builtin functions. how fast is fast ? for this case, is the following good enough ? def flat(li): for x,y in li: yield x yield y -- http://mail.python.org/mailman/listinfo/python-list
Re: Change Gateway Programmatically
Godwin Burby wrote: Dear Pythoneer, I need to toggle the gateway ip of my windows xp machine quite often due to some software requirements. I just want to know whether i could do it programmatically using Python. If so how? I am sure there must be some elegant python way but you may also like to check out netsh.exe, which comes with every XP. -- http://mail.python.org/mailman/listinfo/python-list
Re: Change Gateway Programmatically
Godwin Burby wrote: Well netsh turned out to be the perfect solution for my problem(even though doing it in python would have given me some kicks). I managed it with two .bat files for toggling the gateway ips. Thank you friend. there is os.system/os.open* if you want to put python in the equation ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: is there any lib can split string in this way?
This has been asked not long ago. the shlex module as well as csv module both should be able to handle it. for this simple case shlex.split() seems to be the easiest. Leo Jay wrote: I want to split a string like this: 'abc def this is a test ok' into: ['abc', 'def', 'this is a test', 'ok'] is there any lib meet my need? thanks -- Best Regards, Leo Jay -- http://mail.python.org/mailman/listinfo/python-list
Re: Translate this to python?
Xavier Morel wrote: While xrange does have it's place in Python, it has very few actual uses (yours being one of the few), and is usually more harmful than beneficial. While the deprecation of xrange is not that soon, it is part of the Python 3000 PEP (http://www.python.org/peps/pep-3000.html#id38) along with the deprecation of most FP-facilities of Python (filter, map, reduce). It should also be noted that reimplementing xrange when needed is trivial and can be done with a 5-lines generator for the minimal version (1 argument, 0-n range) and probably less than 10 lines for the full blown version equivalent to the current one (including start, end and step arguments) Seems that xrange() would be deprecated because range() will be the lazy version, so a name change or more like that the current range(), i.e. the one that returns a list will be deprecated, feature wise. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is 'everything' a refrence or isn't it?
Steven D'Aprano wrote: I'll tell you what I say: Python passes objects to functions or assignments. Which in C sense, is a reference(or pointer) to some opaque table maintain by the system, identified by id(). -- http://mail.python.org/mailman/listinfo/python-list
Re: Is 'everything' a refrence or isn't it?
Steven D'Aprano wrote: On Fri, 06 Jan 2006 02:19:29 -0800, bonono wrote: Steven D'Aprano wrote: I'll tell you what I say: Python passes objects to functions or assignments. Which in C sense, is a reference(or pointer) to some opaque table maintain by the system, identified by id(). And that C sense is precisely why people try using C idioms in Python and then are surprised that they don't behave as they would in C. So how about we all agree to stop implying that Python behaves like C, and try to teach people that Python behaves like Python? No one implies Python behaves like C but just trying to explain as close as possible to people speaking that language. passed by object can just as easilly be interpreted as the function received a seperate copy, with the caller's copy untouched. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is 'everything' a refrence or isn't it?
Steven D'Aprano wrote: But in programming, things do work that way. If my class Book contains a reference to Smith's classic work, I can modify it. (Unless the language deliberately restricts my ability to modify certain objects, as Python does with immutable objects.) That's what programmers expect when you talk about references, especially if they come from a C (or Pascal) background. In Python, sometimes that's true, and sometimes it is not, and the only way to tell is by looking at the object itself, not by thinking about Python's high-level behaviour. I believe one can restrict modification to pointer/reference parameter passing to C function, so C programmer shouldn't have problem knowing that reference doesn't not necessary mean you can modify it. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to generate (enumerate) 2**N tuples representing all vertices of unit hypercube in N-dimensional hyperspace ?
Dr. Colombes wrote: I'm looking for a good Python way to generate (enumerate) the 2**N tuples representing all vertices of the unit hypercube in N-dimensional hyperspace. For example, for N=4 the Python code should generate the following 2**N = 16 tuples: (1,1,1,1), (1,1,1,-1), (1,1,-1, 1), (1,1,-1,-1), (1,-1,1,1), (1,-1,1,-1), (1,-1,-1, 1), (1,-1,-1,-1), (-1,1,1,1), (-1,1,1,-1), (-1,1,-1, 1), (-1,1,-1,-1), (-1,-1,1,1), (-1,-1,1,-1), (-1,-1,-1, 1), (-1,-1,-1,-1) Maybe converting each integer in the range(2**N) to binary, then converting to bit string, then applying the tuple function to each bit string? Thanks for your help. Is this just a special case for the list of list combine() function posted not long ago ? def combine_lol(seq): return reduce(lambda x,y: (a+(b,) for a in x for b in y), seq, [()]) list(combine_lol([(1,-1)]*4)) -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools.izip brokeness
But that is exactly the behaviour of python iterator, I don't see what is broken. izip/zip just read from the respectives streams and give back a tuple, if it can get one from each, otherwise stop. And because python iterator can only go in one direction, those consumed do lose in the zip/izip calls. I think you need to use map(None,...) which would not drop anything, just None filled. Though you don't have a relatively lazy version as imap(None,...) doesn't behave like map but a bit like zip. [EMAIL PROTECTED] wrote: The code below should be pretty self-explanatory. I want to read two files in parallel, so that I can print corresponding lines from each, side by side. itertools.izip() seems the obvious way to do this. izip() will stop interating when it reaches the end of the shortest file. I don't know how to tell which file was exhausted so I just try printing them both. The exhausted one will generate a StopInteration, the other will continue to be iterable. The problem is that sometimes, depending on which file is the shorter, a line ends up missing, appearing neither in the izip() output, or in the subsequent direct file iteration. I would guess that it was in izip's buffer when izip terminates due to the exception on the other file. This behavior seems plain out broken, especially because it is dependent on order of izip's arguments, and not documented anywhere I saw. It makes using izip() for iterating files in parallel essentially useless (unless you are lucky enough to have files of the same length). Also, it seems to me that this is likely a problem with any iterables with different lengths. I am hoping I am missing something... #- # Task: print contents of file1 in column 1, and # contents of file2 in column two. iterators and # izip() are the obvious way to do it. from itertools import izip import cStringIO, pdb def prt_files (file1, file2): for line1, line2 in izip (file1, file2): print line1.rstrip(), \t, line2.rstrip() try: for line1 in file1: print line1, except StopIteration: pass try: for line2 in file2: print \t,line2, except StopIteration: pass if __name__ == __main__: # Use StringIO to simulate files. Real files # show the same behavior. f = cStringIO.StringIO print Two files with same number of lines work ok. prt_files (f(abc\nde\nfgh\n), f(xyz\nwv\nstu\n)) print \nFirst file shorter is also ok. prt_files (f(abc\nde\n), f(xyz\nwv\nstu\n)) print \nSecond file shorter is a problem. prt_files (f(abc\nde\nfgh\n), f(xyz\nwv\n)) print What happened to \fgh\ line that should be in column 1? print \nBut only a problem for one line. prt_files (f(abc\nde\nfgh\nijk\nlm\n), f(xyz\nwv\n)) print The line \fgh\ is still missing, but following\n \ line(s) are ok! Looks like izip() ate a line. -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools.izip brokeness
Paul Rubin wrote: I think you need to use map(None,...) which would not drop anything, just None filled. Though you don't have a relatively lazy version as imap(None,...) doesn't behave like map but a bit like zip. I don't understand what you mean by this? None is not callable. zip([1,2,3],[4,5]) gives [(1,4),(2,5)] map(None,[1,2,3],[4,5]) gives [(1,4),(2,5),(3,None)] So the result of map() can be filtered out for special processing. Of course, your empty/sentinel filled version is doing more or less the same thing. How about this (untested): def myzip(iterlist): return zip of smaller and smaller list of iterables as the individual iterators run out sentinel = object() # unique sentinel def sentinel_append(iterable): return itertools.chain(iterable, itertools.repeat(sentinel)) for i in itertools.izip(map(sentinel_append, iterlist)): r = [x for x in i.next() if x is not sentinel] if r: yield r else: break -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools.izip brokeness
Paul Rubin wrote: [EMAIL PROTECTED] writes: map(None,[1,2,3],[4,5]) gives [(1,4),(2,5),(3,None)] I didn't know that until checking the docs just now. Oh man, what a hack! I always thought Python should have a built-in identity function for situations like that. I guess it does the above instead. Thanks. Jeez ;-) Of course, for OP's particular case, I think a specialized func() is even better, as the None are turned into in the process which is needed for string operation. map(lambda *arg: tuple(map(lambda x: x is not None and x or , arg)), [a,b,c],[d,e]) -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools.izip brokeness
Paul Rubin wrote: Any idea how Haskell would deal with this? I don't recall haskell has the map(None,...) behaviour in the standard Prelude. But then, I don't see how the iterator concept would fit into haskell as well. -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools.izip brokeness
[EMAIL PROTECTED] wrote: It is clear that there is a real need for iterating in parallel over multiple iterators to the end of the longest one. Why does something that stops at the shortest get included in the standard library, but one that stops after the longest doesn't? Is there any hope for something like this being included in 2.5? I wonder as well. map(None, ) does what you want, but it is not lazy. imap(None,) for some reason don't do the same thing as map. And if you don't want None as the sentinel, you can just write your own lambda(see my other post). So for non-lazy need, map already supports what you want. The suggestion of unget in iterator is interesting too, as I also once wrote a restartable iterator wrapper using tee() though later scrap it as I found that turning them into list is easier so long I don't need the lazy version. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python article in Free Software Magazine
Steven D'Aprano wrote: On Sat, 31 Dec 2005 14:42:36 -0600, Kirk Strauser wrote: I wrote this article which was published in Free Software Magazine: http://www.freesoftwaremagazine.com/free_issues/issue_09/intro_zope_1/ It's intended as a high-level overview of the language, and therefore glosses over some of the details. For example, I describe its function calling mechanism as pass-by-reference, because that's close enough for newcomers to get the gist of it. Then what you are describing is not Python, it is some mythical language that is almost like Python, but just enough like C to confuse programmers who think they have discovered a bug when the following doesn't work: def increment(n, inc=1): n += inc n = 1 increment(n) assert n == 2 I assume you mean C++, not C. As in C int n=1; void increment(int *n) { n+=1 } assert(n==2); /* this one would fail */ Behave exactly like your sample. I don't want to nit-pick all my way through the article, which is very decent and is worth reading, but I will say one more thing: you describe Python as an expressive, interpreted language. Python is no more interpreted than Java. Like Java, it is compiled into byte-code which is then executed by a virtual machine. It has a separate compilation and execution step. (Amazing how the Java virtual machine is one of the great buzz-word selling features of the language, and yet Python people take it utterly for granted.) We both know that rational people shouldn't care about the difference between compilers and interpreters: it is performance that counts, not how you get it. We know that Python doesn't literally analyse the source code over and over again, and no major interpreted language has done this for probably two decades or more. We can argue about the differences between interpretation, tokenization, compilation and execution, and pedants like me will mention that machine code is interpreted by the CPU. But sadly, many decision makers don't understand these subtleties. To them, compiled languages like C++ and Java are Good, interpreted languages are Bad and doomed to be slow and weak. As soon as you describe Zope/Python as interpreted, you turn off maybe 25% or 50% of the Pointy Haired Bosses who are making the decision of what technologies are used. I don't see that as a problem. In fact, it alarms them the right way. For those who don't care(I met many who don't, so long the technology delivers the end result, they don't want to know the difference or the buzz words), it doesn't matter. For those who knows a little bit(even not the detail) and care, this interpreted term gives them the right reason to ask : 1. would that be slow ? 2. does it mean the source cannot be reasonably seperated from the end product ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python article in Free Software Magazine
Steven D'Aprano wrote: I'm worried about people who pre-judging (as in prejudice) Python negatively on the basis of buzzwords they barely understand. For those with prejudice, it doesn't matter anyway. -- http://mail.python.org/mailman/listinfo/python-list
Re: python coding contest
Steven D'Aprano wrote: I'm reminded of a time I was going for a drive in the country when I drove past an apple orchid. Standing in the orchid was a farmer with a pig. He lifted the pig into the air, and the pig then bit an apple and slowly chewed it. The farmer then carried him over to another branch, and the pig ate another apple. I was so surprised I stopped my car and wandered over to ask the farmer what he was doing. I'm feeding apples to my pig, he replied. Wouldn't it save time to just pick some apples and feed them to the pig? The farmer looked at me like I was an idiot. What's time to a pig? Has anyone studied if farmers like him are in general healthier ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Memoization and encapsulation
Steven D'Aprano wrote: I was playing around with simple memoization and came up with something like this: _cache = {} def func(x): global _cache if _cache.has_key(x): return _cache[x] else: result = x+1 # or a time consuming calculation... _cache[x] = result return result when it hit me if I could somehow bind the cache to the function, I could get rid of that pesky global variable. what would be the problem of the following, other than exposing the cache which the caller may override ? def func(x,_cache={}): -- http://mail.python.org/mailman/listinfo/python-list
Re: recursive function return value problems
[EMAIL PROTECTED] wrote: hi, i have the following recursive function (simplified to demonstrate the problem): def reTest(bool): ... result = [] ... if not bool: ... reTest(True) ... else: ... print YAHHH ... result = [should be the only thing returned] ... print printing result: ... print result ... return result ... reTest(False) YAHHH printing result: ['should be the only thing returned'] printing result: [] [] I don't understand why results are returned twice? is there something special i missed about recursive functions? seems that you want the reTest(True) to be the last and skip the rest. If that is the case, put it as return reTest(True). Otherwise, the last three statements(print, print, return) would happen regardless the boolean value. -- http://mail.python.org/mailman/listinfo/python-list
Re: fetching images from web?
may be using wget/curl but then it is no longer python ;-) [EMAIL PROTECTED] wrote: hi, i want to automate some tasks of gathering photos from web, i tried urllib/urllib2, both ended up without much success (saved gifs with only a border, nothing else).. the code i used was: data = urllib2.urlopen(http://aspn.activestate.com/ASPN/img/komodo_aspn_other.gif;) #was looking through cookbook, so i used that as a sample image data = data.read() file = open(f:/test.gif, w) file.write(data) file.close() can someone suggest a better way (or what's wrong with urllib/urllib2)? thanks alot! -- http://mail.python.org/mailman/listinfo/python-list
Re: help with lists and writing to file in correct order
[EMAIL PROTECTED] wrote: sorry for asking such beginner questions but i tried this and nothing wrote to my text file for food, price, store in bs(food, price, store): out = open(test.txt, 'a') out.write (food + price + store) out.close() while if i write the following without the for i at least get something? out = open(test.txt, 'a') out.write (food + price + store) out.close() pull the open() and close() call out of the loop. And use some other name for the variables as they are very confusing and could be error prone to. -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting with expensive compares?
Dan Stromberg wrote: Hi folks. Python appears to have a good sort method, but when sorting array elements that are very large, and hence have very expensive compares, is there some sort of already-available sort function that will merge like elements into a chain, so that they won't have to be recompared as many times? Thanks! Sounds like DSU time. [a] - [ (hash(a), a) ] -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting with expensive compares?
gene tani wrote: [EMAIL PROTECTED] wrote: Dan Stromberg wrote: Hi folks. Python appears to have a good sort method, but when sorting array elements that are very large, and hence have very expensive compares, is there some sort of already-available sort function that will merge like elements into a chain, so that they won't have to be recompared as many times? Thanks! Sounds like DSU time. [a] - [ (hash(a), a) ] Aha! OR: take a log of the array, e.g. log base 10 or some other monotonic transform and permutation order indexes http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/306862 I may have made a mistaken in that hash(a) should be some function that returns the order of a, rather than the built-in hash() function. -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting with expensive compares?
Dan Stromberg wrote: On Thu, 22 Dec 2005 22:06:42 +, Dan Stromberg wrote: Hi folks. Python appears to have a good sort method, but when sorting array elements that are very large, and hence have very expensive compares, is there some sort of already-available sort function that will merge like elements into a chain, so that they won't have to be recompared as many times? Thanks! I probably should've been more specific. I'm wanting to sort a large number of files, like a bunch of output files from a large series of rsh or ssh outputs on a large series of distinct machines, a music collection in .ogg format (strictly redistributable and legally purchased music), a collection of .iso cdrom images (strictly redistributable and legally purchased software), and so forth. I'm not sorting the content of each file individually. I'm treating each file as a potentially very large string, and sorting the strings. I've been using the following compare function, which in short checks, in order: 1) device number 2) inode number 3) file length 4) the beginning of the file 5) an md5 hash of the entire file 6) the entire file (If #1 and #2 are identical, then the file must be a hardlink to the other file. Also, files that do not have the same length can never be identical. And of course these items are generated on demand, making it frequently possible to avoid doing full-file-length compare on a lot of files) However, my program is still doing more #6 comparisons than seems strictly necessary when I could just toss all the filenames describing identical files into a list, and avoid re-comparing files with identical content over and over - I don't want to compare them to each other again and again), when there are a lot of identical files in the input list. Why would #5 not enough as an indicator that the files are indentical ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Indentation/whitespace
James Tanis wrote: Honestly I wonder how so many coders actually came to be interested in the field -- one that pretty much thrives in part on its neverending ability to vary, grow, and change -- if something so small can warrant so much attention. That is what a cafe type newsgroup is for, nothing but time killing :-) For those who really cannot stand it, they would have moved on to whatever other language that they feel better(or more tolerable in whatever sense). -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido at Google
Alex Martelli wrote: [EMAIL PROTECTED] wrote: Anand wrote: This is very good news. I wish Guido all the best! I wonder if this has got to do something with Microsoft developing IronPython. Incidentellay it is reaching a 1.0 release pretty soon. Perhaps Google has some cards up their sleeve. What other best way to counter this than to hire the big fish himself ? :-) I wonder how high a particular programming language is in the prioirty of either organisations of such size ? Interesting question. I would expect, without any inside knowledge, that Java, for example, is pretty high in the priority of an organization (guess which one?) whose size (number of employees) is, I believe, quite a bit larger than Google's. Microsoft used to have a particular programming language (Visual Basic) in quite a strategic role in their array of products, and although you'd now have to consider a small set instead (including C#) it seems to me they still do. As for Google, well, I believe there is exactly one (1) person you'll find identified on the web as both a Google Fellow AND a Google vice-president, and his page from when he was a professor at UCSB (before he joined Google) is still on the web, too: guess what field his research was in...? But I guess this is about programming languages in general, rather than a particular one (and indeed, neither MS, nor Google, nor the other organization above mentioned, have ever been single-programming-language cultures [net of the very early times when Basic was MS's only product, of course;-)]...). The question was specifically to the previous question it is responsed to and if its context or meaning have been read otherwise(intended or not intended), there isn't much I can do. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido at Google
Gary Herron wrote: You don't appear to understand Open Source very well. Python is the way it is because we, the community, *like* it that way. It evolves in directions that we (all) decide it is to evolve. Guido is our leader in this because we trust him and *choose* to follow his lead. If you want something changed you don't wait and you don't whine, you join the community with a reasoned argument for why your idea would make it a better language in *our* eyes. So how about it... What's your complaint, what's your solution, and why should we listen? Well, this may be the CPython way of open source but I don't know if that is Open source in general. Another way is that if someone(or group) don't like the current state of a project, they fork. I don't know if that is possible in the context of python, and programming language in general. Can it still be called python ? I am not saying that it is a better way(my guess is not) but just that the first sentence seems to be overly generalized. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido at Google
Alex Martelli wrote: [EMAIL PROTECTED] wrote: ... I wonder if this has got to do something with Microsoft developing IronPython. Incidentellay it is reaching a 1.0 release pretty soon. Perhaps Google has some cards up their sleeve. What other best way to counter this than to hire the big fish himself ? :-) ... I wonder how high a particular programming language is in the prioirty of either organisations of such size ? ... Interesting question. I would expect, without any inside knowledge, ... single-programming-language cultures [net of the very early times when Basic was MS's only product, of course;-)]...). The question was specifically to the previous question it is responsed to and if its context or meaning have been read otherwise(intended or not intended), there isn't much I can do. The funny idea that Google would hire Guido to counter Microsoft's hiring of Jim Hugunin 1+ year ago didn't particularly need debunking, but you chose to comment on it with a question which I thought was worth answering, since you chose to phrase it so very generally, and since it appeared to be intended as a rhetorical question hinting at what I consider a wrong idea in the general case. Far from there not being much you can do, if you're interested in avoiding possible misunderstandings you can easily choose to express yourself more precisely and specifically, rather than vaguely and generically... As I said, I cannot do anything in how you want to intepret that and how you can read it as rhetorical question(could be just that it is from me), there really is nothing I can do other changing the mail name which I am intended to. What is your meaning of wrong idea in the general case ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido at Google
Alex Martelli wrote: In the general case, it's pretty general;-). In the specific case of your question above quoted (interpreting the mis-spelled words and grammatical errors to the best of my modest ability), reading it as rhetorical means it's in fact intended as a statement (that a particular programming language cannot have high priority for organizations of size similar to MS's and Google's), and such a statement is incorrect (as I tried showing with several examples displaying particular programming languages having high strategical priorities for organizations with many thousands of employees, including one with more personnel [larger size] than Google's). So exactly how high is python in Google's priority list ? Or in other words, if python is in a stand still as it is now, what would be the impact to Google ? As an outsider, I can only base on public info, like a press release mentioning Guido has been hired. An example of rhetorical question: Do you really think that a specific technology [including a software one, such as a programming language] cannot have, in certain cases, *extremely high* strategic priority for organizations with thousands of employees? In this example, the question is phrased to hint at how silly such an opinion would be, and therefore imply that you can't really think that (and must have ulterior motives for so suggesting, etc etc). Rhetorical questions are a perfectly legitimate style of writing (although, like all stylistic embellishments, they can be overused, and can be made much less effective if murkily or fuzzily phrased), of course. Surprisingly, I don't see this as an rhetorical question at all. It is quite netural to me as a I don't agree with you without indication of silliness, just a style of writing. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido at Google
Cameron Laird wrote: In article [EMAIL PROTECTED], [EMAIL PROTECTED] wrote: . . . Well, this may be the CPython way of open source but I don't know if that is Open source in general. Another way is that if someone(or group) don't like the current state of a project, they fork. I don't know if that is possible in the context of python, and programming language in general. Can it still be called python ? . . . While I don't understand the question, it might be pertinent to observe that, among open-source development projects, Python is unusual for the *large* number of forks or alternative imple- mentations it has supported through the years URL: http://phaseit.net/claird/comp.lang.python/python_varieties.html . The question is, can anyone just fork a new one using the python name, as part of the project, without the permission from the foundation ? Say for example, anyone want to implement java needs permission from Sun(or is it javasoft), if I rememeber correctly. Therefore, the only way to make change to java the language is to convince Sun, very similar to the model of Python. But many open source project is not using this model. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido at Google
Steve Holden wrote: Well the name Python is a trade mark of the Python Software Foundation. So if you invent another language and start calling it Python just to get an audience you should expect to receive a cease-and-desist letter. That is what I expect but don't know to what extend. Can it be called PythonModified like when people enhance vi so there is vim and nvi etc ? What about the copyright in CPython ? Can I someone take the codebase and make modifications then call it Sneak ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido at Google
Carsten Haese wrote: So, if there is something you don't like about Python, you have two choices: 1) Seek consensus with the Python community and have your changes accepted into the official Python version, or 2) Fork Python into something else with a different name. If the different name contains 'Python', you'll probably have to ask PSF for permission. In any case, as outlined above, you have have to state that the fork is based on Python and summarize how it differs from Python. Hope this clears things up, Thanks, though I don't have urgent need(if at all) to see changes in it. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check if a string is an int?
Steven D'Aprano wrote: If you really wanted to waste CPU cycles, you could do this: s = 1579 for c in s: if not c.isdigit(): print Not an integer string break else: # if we get here, we didn't break print Integer %d % int(s) but notice that this is wasteful: first you walk the string, checking each character, and then the int() function has to walk the string again, checking each character for the second time. Wasteful enough that there is a specific built-in function to do just this ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: adding string values to a list?
planetthoughtful wrote: Hi All, Sorry for the influx of newbie questions -- I'm trying to figure these things out on my own before bothering the community, but a lot of bits and pieces are escaping me at the moment. I'm retrieving a result set from an SQLite db (using the APSW module) and I want to add the value from one of the fields in the result set to a list. My current code looks something like: result = [] for name in cursor.execute(SELECT name, address FROM contacts ORDER BY name): result.extend(name) print result For reasons I (obviously) don't understand, the name values get broken up into each individual letter of the values in the name field in the result list. So, if the table contained records: Fred Dave When I print result I get: ['F','r','e','d','D','a','v','e'] What I'm looking for is: ['Fred','Dave'] Can anyone give me some advice on what I'm doing wrong? Many thanks and much warmth, may be you can try result.append() instead of result.extend() and read about their difference in the manual. but for this particular case you may get what you want with list comprehension, or simply limit the columns returned, as you are throwing away the addresses column anyway. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido at Google
Anand wrote: This is very good news. I wish Guido all the best! I wonder if this has got to do something with Microsoft developing IronPython. Incidentellay it is reaching a 1.0 release pretty soon. Perhaps Google has some cards up their sleeve. What other best way to counter this than to hire the big fish himself ? :-) I wonder how high a particular programming language is in the prioirty of either organisations of such size ? -- http://mail.python.org/mailman/listinfo/python-list
Re: how to remove duplicated elements in a list?
Steve Holden wrote: Kevin Yuan wrote: How to remove duplicated elements in a list? eg. [1,2,3,1,2,3,1,2,1,2,1,3] - [1,2,3]? Thanks!! list(set([1,2,3,1,2,3,1,2,1,2,1,3])) [1, 2, 3] Would this have the chance of changing the order ? Don't know if he wants to maintain the order or don't care though. -- http://mail.python.org/mailman/listinfo/python-list
Re: reading files
Johhny wrote: Hello All, I am working my way through learning python as a language. I am having some issues with something that looks right and does not work. I am trying to get myself more familure with reading files. Based on the tutorials at www.python.org This should work. but im not sure what the issue is. ===SNIP=== import string vsftpd=open('vsftpd.conf', 'r') print vsftpd vsftpd.read() vsftpd.readlines() vsftpd.close() ===SNIP=== When I check the permissions to ensure they are correct I get the following. stat vsftpd.conf File: `vsftpd.conf' Size: 4137Blocks: 16 IO Block: 131072 regular file Device: 802h/2050d Inode: 51010 Links: 1 Access: (0644/-rw-r--r--) Uid: ( 1000/ testing) Gid: ( 1000/ testing) Access: 2005-12-19 10:21:04.0 + Modify: 2005-12-16 12:34:00.0 + Change: 2005-12-16 12:34:00.0 + When I run the script I get the following: python reading_file.py open file 'vsftpd.conf', mode 'r' at 0xb7d742a8 Does anyone have any advice on this issue at all. Regards, out of curiosity, what other programming background do you have prior to use python ? -- http://mail.python.org/mailman/listinfo/python-list