Re: python for loop
On Apr 2, 1:29 am, Steven D'Aprano wrote: > On Wed, 01 Apr 2009 21:58:47 -0700, Lie wrote: > > On Apr 1, 7:06 pm, Steven D'Aprano > > wrote: > > >> There is a major clash between the names of ordinals in human languages > >> and zero-based counting. In human languages, the Nth-ordinal item comes > >> in position N. You can keep that useful convention with zero-based > >> counting by inventing the ugly word "zeroth", but that just leads to > >> bizarro-talk like "the zeroeth item comes first, the first item comes > >> second, and so on". > > > No, there won't be any bizarro-talk. There is no argument: the zeroeth > > item comes zeroeth, the first item comes first, and so on. The index for > > the very zeroeth thing in a list is 0, so to get the zeroeth item you > > use s[0]. While to get the first item you use s[1]. It's very intuitive, > > isn't it? > > No, because "first", "second", "third" etc. have existed in the English > language for hundreds of years and everybody knows them. "Zeroeth" was > probably invented a few decades ago, and is known by maybe 1% of the > English-speaking population. > > Given the list [a, b, c], if you ask even a C programmer *in English* > "what's the first item?", they will almost invariably answer a rather > than b. > > -- > Steven However, if you ask him/er, "What is the item that is 0 items from the start of the list?", what will s/he say? -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
On Apr 1, 9:23 pm, John O'Hagan wrote: > Despite being thoroughly acclimatised to zero-based indexing and having no > wish to change it, I'm starting to see the OP's point. > > Many of the arguments presented in this thread in favour of zero-based > indexing have rather been arguments for half-open intervals, which I don't > think are in dispute. We all want these to be true: > > foo[:n] is the first n items of the sequence foo > foo[:n] + foo[n:] == foo > len(foo[n:m]) == m-n > (foo[n:n]) is an empty sequence > etc. > > and they are true with 0-based indexing if we exclude the last number, or > equally with 1-based indexing if we exclude the first. Unless I'm missing something, wouldn't that mean: range(0,10) -> [1,2,3,4,5,6,7,8,9,10] Even though it's theoretically just another way to line up the open interval, as practical matter it's going to be a lot more confusing. Of course you could exclude the last number with one-based indexing also, but that would be confusing too, since you would have to use something like range(1,len(x)+1) to iterate over the items of x. Given that, I'm going to disagree that a half-open interval is desirable in the case of one-based indexing. Furthermore, I know of no languages that use both one-based indexing and half-open intervals. Do you know of any? > Beyond being part of a conventionally-ordered set of keys, what can an > ordinality of zero actually mean? (That's a sincere question.) I think people were being facetious. To me the first item in the list is x[0]--ordinal does not match cardinal. However, I don't use ordinals much when talking about list items; I'll say item 2, not third item. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Regex trouble
Thanks Andrew. I was also of the same view that perl handled this via some special cases. On Wed, Apr 1, 2009 at 8:32 PM, andrew cooke wrote: > > more exactly, my guess is perl has a special case for this that avoids > doing a search over all possible matchers via the pushdown stack. > > andrew cooke wrote: > > > > ".*?" is a "not greedy" match, which is significantly more difficult to > > handle than a normal ".*". so the performance will depend on quite > > complex details of how the regular expression engine is implemented. it > > wouldn't surprise me if perl was better here, because it comes from a > > background with a much stronger emphasis on regular expressions. > > > > i know that not an exact answer, but unless you find the author of the re > > library i am not sure you will get a much better explanation. it comes > > down to whether the regular expression can be implemented using a > > deterministic finite automaton (rather than an indeterministic one). if > > you look at the table at the bottom of > > http://en.wikipedia.org/wiki/Finite_state_machine then i believe (i am > not > > 100% sure) that the ".*?" match requires at least a pushdown automota, > > while ".*" can be handled with a simple finite automaton. > > > > disclaimer: this is all fairly new to me as i just recently implemented a > > regular expression matcher myself, and i may be wrong on some of the > > details. > > > > andrew > > > > > > akshat agarwal wrote: > >> Hi, > >> > >> I am trying to use the following snippet of code to print a regex match. > >> > >> s = '01234567890123456789x012' > >> > >> pat = r'(.*?x|[^a]+)*y' > >> > >> mo = re.search(pat, s) > >> if mo is not None: > >> print mo.group(0) > >> > >> By adding one character before the 'x' in the input string, the time > >> taken > >> to print the match doubles. This behaviour is not observed in perl. I am > >> curious to know about the difference the in regex implementations of > >> perl > >> and python which causes this. > >> > >> Thanks > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > >> > > > > > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
On Wed, 01 Apr 2009 21:58:47 -0700, Lie wrote: > On Apr 1, 7:06 pm, Steven D'Aprano > wrote: > >> There is a major clash between the names of ordinals in human languages >> and zero-based counting. In human languages, the Nth-ordinal item comes >> in position N. You can keep that useful convention with zero-based >> counting by inventing the ugly word "zeroth", but that just leads to >> bizarro-talk like "the zeroeth item comes first, the first item comes >> second, and so on". > > No, there won't be any bizarro-talk. There is no argument: the zeroeth > item comes zeroeth, the first item comes first, and so on. The index for > the very zeroeth thing in a list is 0, so to get the zeroeth item you > use s[0]. While to get the first item you use s[1]. It's very intuitive, > isn't it? No, because "first", "second", "third" etc. have existed in the English language for hundreds of years and everybody knows them. "Zeroeth" was probably invented a few decades ago, and is known by maybe 1% of the English-speaking population. Given the list [a, b, c], if you ask even a C programmer *in English* "what's the first item?", they will almost invariably answer a rather than b. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
On Thu, 02 Apr 2009 04:23:32 +, John O'Hagan wrote: > Beyond being part of a conventionally-ordered set of keys, what can an > ordinality of zero actually mean? (That's a sincere question.) In set theory, you start by defining the integers like this: 0 is the cardinality (size) of the empty set, the set with nothing in it. 1 is the cardinality of the set of empty sets, that is, the set containing nothing but the empty set. 2 is the cardinality of the set of the empty set plus the set of empty sets. 3 is the cardinality of the set containing the empty set, plus the set of empty sets, plus the set of (the empty set plus the set of empty sets). And so forth, to infinity and beyond. Or to put it another way: 0 = len( {} ) 1 = len( {{}} ) 2 = len( {{}, {{}}} ) 3 = len( {{}, {{}}, {{}, {{}}} ) etc. For non-infinite sets, you can treat ordinal numbers and cardinal numbers as more or less identical. So an ordinality of zero just means the number of elements of something that doesn't exist. How that relates to whether indexing should start at one or zero, I have no idea. Oh, and speaking of... I'm shocked, SHOCKED I say, that nobody has given that quote about the compromise of 0.5. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: A design problem I met again and again.
On Thu, 02 Apr 2009 18:47:29 +1300, Lawrence D'Oliveiro wrote: >>> The question is not how many lines or how many methods, but whether it >>> makes sense to remain as one piece or not. In one previous project, I >>> had one source file with nearly 15,000 lines in it. Did it make sense >>> to split that up? Not really. >> >> What are the average size of source files in your project? If it's >> far lower than 15,000, don't feel it's a little unbalance? > > Why? If you have too much code in one file, it will upset the balance of the spinning hard drive platter, and it will start to wobble and maybe even cause a head-crash. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
On Apr 2, 4:05 pm, Aaron Brady wrote: > On Apr 1, 11:58 pm, Lie wrote: > > > On Apr 1, 7:06 pm, Steven D'Aprano > > > wrote: > > > There is a major clash between the names of ordinals in human languages > > > and zero-based counting. In human languages, the Nth-ordinal item comes > > > in position N. You can keep that useful convention with zero-based > > > counting by inventing the ugly word "zeroth", but that just leads to > > > bizarro-talk like "the zeroeth item comes first, the first item comes > > > second, and so on". > > > No, there won't be any bizarro-talk. There is no argument: the zeroeth > > item comes zeroeth, the first item comes first, and so on. The index > > for the very zeroeth thing in a list is 0, so to get the zeroeth item > > you use s[0]. While to get the first item you use s[1]. It's very > > intuitive, isn't it? > > Robot 1: I won zeroeth place at the contest, honey! > Robot 2: Congratulations! I knew you could do it. That should be Robot 0 and Robot 1. -- http://mail.python.org/mailman/listinfo/python-list
Re: Display directory pyqt4 and Python
On Donnerstag, 2. April 2009, Dunwitch wrote: > for x in (fileList): > self.ui.displayVideo.setText(x) # This only shows the last self.ui.displayVideo.setText('\n'.join(fileList)) but I would go for a solution with QDirModel / QListView http://doc.trolltech.com/4.5/itemviews-dirview.html -- Wolfgang -- http://mail.python.org/mailman/listinfo/python-list
Re: A design problem I met again and again.
In message <158986a9-b2d2-413e-9ca0- c584299f1...@f1g2000prb.googlegroups.com>, 一首诗 wrote: > On Apr 1, 4:55 pm, Lawrence D'Oliveiro central.gen.new_zealand> wrote: > >> In message <48506803-a6b9-432b-acef- >> >> b75f76e90...@v23g2000pro.googlegroups.com>, 一首诗 wrote: >> > Until one day I find service has nearly 100 methods and 6000 lines of >> > code. I don't need to read any programming book to know that it's >> > too big. >> >> The question is not how many lines or how many methods, but whether it >> makes sense to remain as one piece or not. In one previous project, I had >> one source file with nearly 15,000 lines in it. Did it make sense to >> split that up? Not really. > > What are the average size of source files in your project? If it's > far lower than 15,000, don't feel it's a little unbalance? Why? -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
On Apr 1, 11:58 pm, Lie wrote: > On Apr 1, 7:06 pm, Steven D'Aprano > > wrote: > > There is a major clash between the names of ordinals in human languages > > and zero-based counting. In human languages, the Nth-ordinal item comes > > in position N. You can keep that useful convention with zero-based > > counting by inventing the ugly word "zeroth", but that just leads to > > bizarro-talk like "the zeroeth item comes first, the first item comes > > second, and so on". > > No, there won't be any bizarro-talk. There is no argument: the zeroeth > item comes zeroeth, the first item comes first, and so on. The index > for the very zeroeth thing in a list is 0, so to get the zeroeth item > you use s[0]. While to get the first item you use s[1]. It's very > intuitive, isn't it? Robot 1: I won zeroeth place at the contest, honey! Robot 2: Congratulations! I knew you could do it. -- http://mail.python.org/mailman/listinfo/python-list
Re: pygame and socket.recv
On Apr 1, 10:38 pm, Terry Reedy wrote: > Aaron Brady wrote: > > > My game loop looks like this: > > > poll events, get 1 at most > > send to server > > wait for server reply > > render entire frame > > I am very sure that commercial 'real-time' (versus turn-based) > multiplayer games do not operate that way, at least not the ones I have > played. > > I suspect that most do not operate by frames on the server, but rather > sent a more or less continuous series of events. NPC movements come > from the server (and can be given as vectors), other player movements > get echoed as sent to the server. The client uses the most current data > it has when it renders a frame. If the scene it too complex relative to > the client rendering capability, the frames jump and the motion is > choppy. If the info stream is interrupted, the scene may freeze a bit > even as the client continues to re-render to account for player motion. > Hope this helps a bit. I am thinking a couple of things. Take a branch in the reasoning. On arriving at the time to render the next frame, without any announcement from the other side: 1) Side A continues to model Side B as though no change in motion occurred. 2) Side A discontinues its model of Side B until next transmission. In 1, upon receiving the next update from B, it will have to retrace its steps, "unmodel" the changes, and bring them up to date. This can have retroactive cause-and-effect consequences on A as well, including but not limited to, live-or-dead state, position, and velocity. In 2, A's view of B looks jumpy-- B is halting, then jumping ten tiles, then moving smoothly, then halting and jumping. Retroactive changes are regardless possible. This was a the-long-way-'round word search for the word 'retroactive', which I'm glad is a word, incidentally. In either case, every time one player's packets are delayed, every other player's screen will alter state, more or less like they have been sleepwalking and just come to. There is the additional problem of what to do with A's interim actions. Reminds me of a diff-merge in source control! How about king-of-the-hill precedence for contradiction resolution? Then, the player whose packets are delayed has an advantage. B got to make a change to another player's state, as well as proceed with exclusive knowledge of it. B is the only one with an up-to-date model of the game during the lag. This could also apply to B instead, if the game structure makes the others' besides B the valid current model. B is sleepwalking for the length of his/er network delay, and his/er actions are discarded. This may be more what players are accustomed to; the interface goes dead, and issuing or rescinding orders isn't acknowledged or received. Any momentary loss of "visibility" could be mitigated in a low-impact game or simulation of physical motion, since it takes many Gs of acceleration to avert most-- all but glancing-- collisions that are destined in just a few frames. Mine is not such; position and velocity are subject to arbitrary changes. Maybe I just need more clicks per second, to give the user a feeling of accomplishing something, even though the same percentage of actions is successfully transmitted. Is satisfaction a simple decaying proportion? With discontinuities in position and momentum possible, is lockstep frame-for-frame synchronization my best option? Or should I fall back on a sturdier game model, where actions' consequences can't affect other players for several frames? Blue... no! Yellow! -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
On Apr 1, 7:06 pm, Steven D'Aprano wrote: > There is a major clash between the names of ordinals in human languages > and zero-based counting. In human languages, the Nth-ordinal item comes > in position N. You can keep that useful convention with zero-based > counting by inventing the ugly word "zeroth", but that just leads to > bizarro-talk like "the zeroeth item comes first, the first item comes > second, and so on". No, there won't be any bizarro-talk. There is no argument: the zeroeth item comes zeroeth, the first item comes first, and so on. The index for the very zeroeth thing in a list is 0, so to get the zeroeth item you use s[0]. While to get the first item you use s[1]. It's very intuitive, isn't it? -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating huge data in very less time.
Grant Edwards wrote: >On 2009-03-31, Dave Angel wrote: > >> They were added in NTFS, in the Windows 2000 timeframe, to my >> recollection. > >NTFS was added in NT 3.1 (which predates Win2K by 7-8 years). Although that's true, you didn't read his sentence. Sparse file support was not added to NTFS until Windows 2000, exactly as he said. -- Tim Roberts, t...@probo.com Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Sending SMS using python script
hi group, my application needs to send SMS occasionally to all the clients .Is there any library in python that supports in sending SMS. I like to conform few information i gathered in this regard. I can send SMS by two ways 1. Sending SMS using Email clients 2. Using sms gateway to send message(we can implement SMS Gateway API 's ,provided by vendor and ,send SMS -- we will be charged accordingly ) In case of First approach 1. We can make use of libgamil library to send SMS using gmail ( I ref : http://blog.datasingularity.com/?p=63 ) i suppose sending sms through gmail is not supported in India 2. Can we use Skype4py library, In case of second approach 1. Is there any way to send SMS for free inside India ,or ,Any free SMS gateway providers in India Any information regarding this is appreciable Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
On Wed, 1 Apr 2009, Steven D'Aprano wrote: > On Wed, 01 Apr 2009 04:39:26 +0100, Rhodri James wrote: > > Dragging this back to the original topic, you clearly find starting list > > indices from zero unintuitive. To me, with a mathematical background, > > it's not just intuitive, it's correct. All sorts of useful properties > > fall out from that, not the least of which is the fact that > > "a[0:len(a)]" slices the whole of a list. > > But some non-useful properties fall out of that too. > > Want the fifth item? a[5] gives you the *sixth* item, which is weird, so > you have to use a[5-1] to get the fifth item. > > There is a major clash between the names of ordinals in human languages > and zero-based counting. In human languages, the Nth-ordinal item comes > in position N. You can keep that useful convention with zero-based > counting by inventing the ugly word "zeroth", but that just leads to > bizarro-talk like "the zeroeth item comes first, the first item comes > second, and so on". > > a[0:len(a)] is legal, a[0] is legal, but surprisingly a[len(a)] is an > error. > > Despite coming from a Pascal background, I've come to appreciate and > prefer zero-based indexing for programming. But I'm not blind to the > disadvantages. I'll often work out an algorithm using pencil and paper > and counting from one, and then subtract one to get zero-based indexes. [...] Despite being thoroughly acclimatised to zero-based indexing and having no wish to change it, I'm starting to see the OP's point. Many of the arguments presented in this thread in favour of zero-based indexing have rather been arguments for half-open intervals, which I don't think are in dispute. We all want these to be true: foo[:n] is the first n items of the sequence foo foo[:n] + foo[n:] == foo len(foo[n:m]) == m-n (foo[n:n]) is an empty sequence etc. and they are true with 0-based indexing if we exclude the last number, or equally with 1-based indexing if we exclude the first. In a way, Python already has 1-based indexing, in terms of absolute index values when counting backwards: the last element of a sequence is indexed -1, the second-last -2, etc., so that the first element is foo[-len(foo)]. 1-based indexing mirrors this so that foo[len(foo)] is not a surprising error as Steven mentions above, but the last element of foo. Also the other weirdness Steven mentioned goes away: the nth element of foo becomes foo[n], and the OP's issue with an extant element having an ordinality of 0 ("zeroeth") also goes away, i.e. ordinality and cardinality are lined up. Beyond being part of a conventionally-ordered set of keys, what can an ordinality of zero actually mean? (That's a sincere question.) But as long as we need to both count items and measure intervals, we have to deal with these +/-1 adjustments in any case. As an aside, a similar issue arises in music theory, in which intervals are traditionally expressed relative to scale degrees starting from one (counting the notes), or in more modern language, in semitones starting from zero (measuring the interval). This gives rise to similar (minor and short-lived) confusions. +/-1 :) Regards, John -- http://mail.python.org/mailman/listinfo/python-list
Re: pygame and socket.recv
Aaron Brady wrote: My game loop looks like this: poll events, get 1 at most send to server wait for server reply render entire frame I am very sure that commercial 'real-time' (versus turn-based) multiplayer games do not operate that way, at least not the ones I have played. I suspect that most do not operate by frames on the server, but rather sent a more or less continuous series of events. NPC movements come from the server (and can be given as vectors), other player movements get echoed as sent to the server. The client uses the most current data it has when it renders a frame. If the scene it too complex relative to the client rendering capability, the frames jump and the motion is choppy. If the info stream is interrupted, the scene may freeze a bit even as the client continues to re-render to account for player motion. Hope this helps a bit. Yes, I am blocking for the data to come down the network. Unfortunately, if I use any "prediction," I will have to go back and un-render the previous frame, then redraw with the new information. 40 transmissions per second in each way can't be too much to ask, it's just that they have to alternate, up one, down one. I don't understand your solution. I can't picture it for my favorite RTS game or the one I'm writing. Are you saying that the slower machine just jumps ahead, and its user just doesn't have the opportunity to make moves on the omitted frames? I am using TCP, socket.SOCK_STREAM. UDP is a potential solution, but it still doesn't fix my main loop. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Which is more Pythonic?
John Machin wrote: On Apr 2, 2:10 am, John Posner wrote: Dennis Lee Bieber presented a code snippet with two consecutive statements that made me think, "I'd code this differently". So just for fun ... is Dennis's original statement or my "_alt" statement more idiomatically Pythonic? Are there even more Pythonic alternative codings? mrkrs = [b for b in block if b > 127 or b in [ "\r", "\n", "\t" ] ] I'd worry about "correct" before "Pythonic" ... see my responses to Dennis in the original thread. mrkrs_alt1 = filter(lambda b: b > 127 or b in [ "\r", "\n", "\t" ], block) mrkrs_alt2 = filter(lambda b: b > 127 or b in list("\r\n\t"), block) Comprehensions combine map and filter and somewhat, to some people, replace both. Tastes vary. If one has a filter function f already, filter(f,seq) may be faster than (f(i) for i in seq). If one does not, ( for i in seq) will probably be faster than filter(lambda i: imvolving i>, seq) as it avoids a function call, using inlined expression code. So either can be more Pythonic, depending on the context. Try this on and see if it fits: num_bin_chars = sum(b > "\x7f" or b < "\x20" and b not in "\r\n\t" for b in block) However, for just counting, this is even better -- and most Pythonic! In fact, being able to count the number of True values in a stream of True and False by summation is part of the justification of bool being a subclass of int. (Note: Dennis's statement converts a string into a list; mine does not.) What is list("\r\n\t") doing, if it's not (needlessly) converting a string into a list? --- binary = (float(len(mrkrs)) / len(block)) > 0.30 binary_alt = 1.0 * len(mrkrs) / len(block) > 0.30 num_bin_chars > 0.30 * len(block) (no mucking about with float() or 1.0, and it doesn't blow up on a zero-length block) Nice point! Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Thoughts on language-level configuration support?
On Apr 1, 8:56 pm, CTO wrote: > > I just mean that there should be a > > clear and easy way to do it, that it should be considered a basic > > service, and that if the best way to satisfy all the goals is to > > integrate it directly into the language, that shouldn't be shied away > > from. > > Honestly, the programming language and the configuration languages > should never, ever, ever be inseparable. I don't see a reason for > it and I see some great reasons not to do it. I'm not saying the actual end-user configuration language would be tied to the programming language. I'm starting to think a better way to describe this is to play down configuration as a use case, and instead focus on what the actual mechanism is: a way to define points in your program that can have values injected into them at runtime by some external entity, a uniform naming scheme for those points derived from the code, and a way to expose those points to interested consumers. > > The example that I have on my blog post, I consider that 'syntax', > > even though it's implemented as a function, mainly just because it > > digs into the bytecode and modifies the normal way a function is > > evaluated (the function's value is determined by where the output > > would go). > > I don't particularly see why this is needed. It was a stab at the 'uniform naming scheme' - the function fetches a config value based on a key derived from the name of the variable its output will be assigned to. It definitely needs more thought, but at least I got to play around with the bytecode tools :) > To my mind the strongest > argument you are making, by far, is the "discoverable" argument. If > you were able to build a system which permitted other components to > discover configuration options and give configurable levels of > permanence and visibility to them, that would be great. If you were > able to do it and make it easy for a programmer to interact with, you > would most definitely have a module I would use. But I daresay you're > going to have to build it (or at least mock it up) before you're going > to get a lot of folks jumping on the bandwagon, and its a *long* slog > before you hit the level of support and stability you're going to need > to convince folks to trust their precious config files to it. Agreed, and I do intend to do a proper mockup when I get the time; I just wanted to get some initial reactions. Thanks for your feedback. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Goes Mercurial
Lawrence D'Oliveiro wrote: > In message , Tim Daneliuk wrote: > >> ,,, when I suggested that better open source tools existed, they kindly >> explained their complete lack of interest in moving several millions >> of lines of code to anything new. > > What was their explanation? > Their entire internal workflow from development through final release and deployment was built around these ancient/nonstandard toolset. It was economically infeasible to retool both the technology and the processes for millions of lines of code under version control - there just wasn't an ROI for it. This is not uncommon in large legacy environments in my experience. -- Tim Daneliuk tun...@tundraware.com PGP Key: http://www.tundraware.com/PGP/ -- http://mail.python.org/mailman/listinfo/python-list
Display directory pyqt4 and Python
I've looked around for the answer and have decided to ask an expert for the solution. Whats suppose to happen is a user pushes a button and displays the directory content in the text edit window on the gui. Everything works, apart from the fact that it only shows the last file in the directory, not a full listing. Here is the code for reference. Any help would be appreciated, I'm missing something simple. -- Dunwitch # File : Video Search import sys, os, win32net from PyQt4 import QtGui, QtCore from findVideos import Ui_MainWindow # UI Files from QT Designer # New class derived from QMainWindow class TestApp(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Connect the signals andslots QtCore.QObject.connect(self.ui.findFiles,QtCore.SIGNAL("clicked ()"), self.showVideoFiles) #- Code In Question - def showVideoFiles(self): enc7 = ('1.2.3.4\\somefolder') fileList=os.listdir(enc7) for x in (fileList): self.ui.displayVideo.setText(x) # This only shows the last file in the directory? #--- if __name__ == "__main__": app = QtGui.QApplication(sys.argv) window = TestApp() window.show() sys.exit(app.exec_()) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Goes Mercurial
In message <7a1dd0d8-1978-470b- a80d-57478d7f7...@q16g2000yqg.googlegroups.com>, Paul Boddie wrote: > And I've heard stories of "bait and > switch" with Git: "you can do XYZ with Git but not with ..." followed > by the discovery that you can't realistically do XYZ with Git, either. Cite? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Goes Mercurial
In message , Tim Daneliuk wrote: > ,,, when I suggested that better open source tools existed, they kindly > explained their complete lack of interest in moving several millions > of lines of code to anything new. What was their explanation? -- http://mail.python.org/mailman/listinfo/python-list
Re: Thoughts on language-level configuration support?
On Mon, 30 Mar 2009 06:40:00 -0700, jfager wrote: > The basic idea is that a language could offer syntactic support for > declaring configurable points in the program. The language system would > then offer an api to allow the end user to discover a programs > configuration service, as well as a general api for providing > configuration values. Completely coincidentally, a colleague forwarded me this cartoon about exposing program internals as the user interface: http://www.ok-cancel.com/comic/4.html I thought it was amusing, because I've seen programs just like that. Yes, even "GUI applications", where the developer thought that creating a user interface was exposing the values of internal variables to the user to modify directly. How does your proposal differ from that? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Beazley on Generators
Lawrence D'Oliveiro writes: > > However, there are situations when you need thousands of lightweight > > threads of execution ;;; > > The Linux kernel has been tested running hundreds of thousands of threads. Those are still heavyweight threads requiring context switches to switch from one to another. If you look at the multi-threading benchmarks in the Alioth shootout, languages with lightweight threads (such as Erlang or GHC) can switch orders of magnitude faster than those that use kernel threads. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to handle/generate pcap file
On Apr 2, 6:59 am, "Rhodri James" wrote: > On Wed, 01 Apr 2009 14:53:34 +0100, Evan wrote: > > > Hello - > > > I'm trying to decode thepcapfilewhich is packet capture by tcpdump > > or wireshark. Is there a python module that I can use it for this > > problem? > > > Can python-libpcap or pycap or dpkt do that? > > A quick browse of the pypcap website suggests that yes, it can. > > -- > Rhodri James *-* Wildebeeste Herder to the Masses Yap, I found that dpkt can do this, Thanks all. Evan -- http://mail.python.org/mailman/listinfo/python-list
Re: pygame and socket.recv
On Apr 1, 8:28 pm, Tim Wintle wrote: > On Wed, 2009-04-01 at 17:58 -0700, Aaron Brady wrote: > > I tried writing a small game on a pygame layer. The graphics are > > fine, and at the moment, it is not graphics intensive. It is multi- > > player, and for the communication, I am sending a pickle string across > > a LAN, once per frame. > > > I'm observing some latency. It seems that socket.recv isn't > > performing consistently. > > Not sure I understand the question, are you blocking for the data to > come down the network before rendering the next frame? > > For game programming I've always used select with non-blocking sockets > to receive data - and kept the transmissions to UDP to save time > (obviously you have to expect some data to be lost). Wire time is always > going to have too much latency for a message to be happily passed within > the time it takes to render a frame. > > For syncing time I use a really simple algorithm - both machines send > each other their local [game] time every few seconds, and if the > received time is ahead of the local time then the receiving machine > updates it's time to match - that way they are always out by at most the > shortest time it takes for a packet to travel from one to the other. > > Tim Wintle My game loop looks like this: poll events, get 1 at most send to server wait for server reply render entire frame Yes, I am blocking for the data to come down the network. Unfortunately, if I use any "prediction," I will have to go back and un-render the previous frame, then redraw with the new information. 40 transmissions per second in each way can't be too much to ask, it's just that they have to alternate, up one, down one. I don't understand your solution. I can't picture it for my favorite RTS game or the one I'm writing. Are you saying that the slower machine just jumps ahead, and its user just doesn't have the opportunity to make moves on the omitted frames? I am using TCP, socket.SOCK_STREAM. UDP is a potential solution, but it still doesn't fix my main loop. -- http://mail.python.org/mailman/listinfo/python-list
Re: pygame and socket.recv
On Wed, 2009-04-01 at 17:58 -0700, Aaron Brady wrote: > I tried writing a small game on a pygame layer. The graphics are > fine, and at the moment, it is not graphics intensive. It is multi- > player, and for the communication, I am sending a pickle string across > a LAN, once per frame. > > I'm observing some latency. It seems that socket.recv isn't > performing consistently. Not sure I understand the question, are you blocking for the data to come down the network before rendering the next frame? For game programming I've always used select with non-blocking sockets to receive data - and kept the transmissions to UDP to save time (obviously you have to expect some data to be lost). Wire time is always going to have too much latency for a message to be happily passed within the time it takes to render a frame. For syncing time I use a really simple algorithm - both machines send each other their local [game] time every few seconds, and if the received time is ahead of the local time then the receiving machine updates it's time to match - that way they are always out by at most the shortest time it takes for a packet to travel from one to the other. Tim Wintle -- http://mail.python.org/mailman/listinfo/python-list
pygame and socket.recv
Hi, I tried writing a small game on a pygame layer. The graphics are fine, and at the moment, it is not graphics intensive. It is multi- player, and for the communication, I am sending a pickle string across a LAN, once per frame. I'm observing some latency. It seems that socket.recv isn't performing consistently. The server is using time.clock and time.sleep to keep the frame rate at 40 frames per second. Latency occurred regardless of whether the connection was ethernet or wireless, although worse with wireless. Does anyone have any hints or suggestions? I am on Windows XP. -- http://mail.python.org/mailman/listinfo/python-list
Re: Thoughts on language-level configuration support?
> I just mean that there should be a > clear and easy way to do it, that it should be considered a basic > service, and that if the best way to satisfy all the goals is to > integrate it directly into the language, that shouldn't be shied away > from. Honestly, the programming language and the configuration languages should never, ever, ever be inseparable. I don't see a reason for it and I see some great reasons not to do it. > The example that I have on my blog post, I consider that 'syntax', > even though it's implemented as a function, mainly just because it > digs into the bytecode and modifies the normal way a function is > evaluated (the function's value is determined by where the output > would go). I don't particularly see why this is needed. To my mind the strongest argument you are making, by far, is the "discoverable" argument. If you were able to build a system which permitted other components to discover configuration options and give configurable levels of permanence and visibility to them, that would be great. If you were able to do it and make it easy for a programmer to interact with, you would most definitely have a module I would use. But I daresay you're going to have to build it (or at least mock it up) before you're going to get a lot of folks jumping on the bandwagon, and its a *long* slog before you hit the level of support and stability you're going to need to convince folks to trust their precious config files to it. -- http://mail.python.org/mailman/listinfo/python-list
Help for Toplevel
Hi Folks, I have a problem of handling Toplevel window. Basically, I wrote a listbox viewer with scrollbars, and saved in file listbo.py. Then in my main GUI window, with menu, I need to launch the listbox viewer, in a new window. Obviously, a Toplevel window is needed. But, I failed at passing parameters over to Toplevel window. Please take a look at my code: Listbox viewer: class ScrolledList(Frame): def __init__(self, options, parent=None): Frame.__init__(self, parent) self.pack(expand=YES, fill=BOTH) self.makeWidgets(options) In my main GUI: from XXX import ScrolledList class Foo: def __init__(self): def call_listbox(self, params): new = Toplevel() alist = ['foor','bar'] ScrolledList(new,alist) With the code above, the widgets did not show on the Toplevel window, and the data list ['foo','bar'] did not show up either. Can somebody help me on it? Thanks a lot! Muddy Coder -- http://mail.python.org/mailman/listinfo/python-list
Re: Matrix operations on character matrix element?
On 2009-04-01 19:12, Terry Reedy wrote: olusina eric wrote: I hope somebody will be able to help me here. I am trying to solve some physical problems that will require the generation of some function in terms of some parameters. These functions are derived from matrix operation on “characters”. Are there ways numpy/scipy perform matrix operations on characters? For example A = matrix([[a, b,c],[d,e,f],[1,2,3]]) B = matrix([[g,h,4],[I,j,5],[k,l,6]]) A to l are identifiers, not characters, and must be bound to objects for the above to make any sense. Did you mean 'a' to 'l'? Is it possible to perform operations like A*B or A+B And most especially: linalg.solve(A,eye(3,3)) If you mean, operate on symbols to do symbolic computation, the same way one might with paper and pencil, the simple answer is no. Numpy is not a computer algebra system. Computer algebra requires that one define classes such as Symbol, with all the usual arithmetic operations. I am not sure whether numpy algorithms can work on arrays of instances of user-defined classes such as this. They can't. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Demographic Information about Python
Betiana Krancenblum wrote: Hi, I'm looking for statistical information about where Python is beeing used as a programming language and where it is teached as a language for beginner programmers. Where do you think I can find that information? There is some info at python.org. Ask on the edu-sig list for more about educational usage. You might look at how information is gather for http://www.tiobe.com/content/paperinfo/tpci/index.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Beazley on Generators
On Thu, 02 Apr 2009 11:37:46 +1300, Lawrence D'Oliveiro wrote: > In message <13298fc5-5024-4343- > bf5a-7e271a08d...@o11g2000yql.googlegroups.com>, Michele Simionato > wrote: > >> However, there are situations when you need thousands of lightweight >> threads of execution ;;; > > The Linux kernel has been tested running hundreds of thousands of > threads. Did it pass or fail that test? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Matrix operations on character matrix element?
olusina eric wrote: I hope somebody will be able to help me here. I am trying to solve some physical problems that will require the generation of some function in terms of some parameters. These functions are derived from matrix operation on “characters”. Are there ways numpy/scipy perform matrix operations on characters? For example A = matrix([[a, b,c],[d,e,f],[1,2,3]]) B = matrix([[g,h,4],[I,j,5],[k,l,6]]) A to l are identifiers, not characters, and must be bound to objects for the above to make any sense. Did you mean 'a' to 'l'? Is it possible to perform operations like A*B or A+B And most especially: linalg.solve(A,eye(3,3)) If you mean, operate on symbols to do symbolic computation, the same way one might with paper and pencil, the simple answer is no. Numpy is not a computer algebra system. Computer algebra requires that one define classes such as Symbol, with all the usual arithmetic operations. I am not sure whether numpy algorithms can work on arrays of instances of user-defined classes such as this. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Thoughts on language-level configuration support?
On Wed, 01 Apr 2009 05:15:19 +0100, jfager wrote: On Mar 31, 10:44 pm, "Rhodri James" wrote: [...] What restrictions can be put on the value you get back? What can the help system say about this, or do we have to go back to doing all that by hand? Now translate all those questions into the very different environment of a config file. Repeat with a database, and all it's quirks. By the time your colossus has acquired enough parameters to at least hint at the desirable answers to these questions, you've effectively duplicated the interfaces to all of the config mechanisms you're trying to replace and you've still lost a whole heap of flexibility. Yes, you're right, the code that actually injects the configuration isn't trivial. I never intended to imply that it was. But it would probably only have to be written once (people would only write their own if they had a special need). The win is that the underlying code doesn't have to change just because the end-user configuration format did. On the contrary, because the configurable items can be introduced pretty much anywhere in module, class or function, the code that injects the configuration ends up having to be written over and over and over again. None of the questions I asked are rocket science, most of them apply to all configurables differently, and none of them can be interpolated from the name being assigned to the object produced by the config and the default. This is not going to be a win. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
On Wed, 01 Apr 2009 15:12:27 +0100, Lada Kugis wrote: On 01 Apr 2009 08:06:28 GMT, Steven D'Aprano wrote: There are advantages and disadvantages to both systems, but on balance, I think that zero-based is a better system for programming, and one-based for natural language. Nicely put. Yes, along with some of your other arguments, I think I can agree that this sums it up best. I'll just have to adapt myself to natural language thinking at one side, and programming thinking at the other. I always think it's sad that the concept of "zero" arrived too late to influence our fundamentally latinate language for ordinal numbers. (In other words, don't go thinking that there's anything logical about natural language :-) -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: how to handle/generate pcap file
On Wed, 01 Apr 2009 14:53:34 +0100, Evan wrote: Hello - I'm trying to decode the pcap file which is packet capture by tcpdump or wireshark. Is there a python module that I can use it for this problem? Can python-libpcap or pycap or dpkt do that? A quick browse of the pypcap website suggests that yes, it can. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
Lada Kugis wrote: > On 01 Apr 2009 01:26:41 GMT, Steven D'Aprano > wrote: > > >> Why Python (and other languages) count from zero instead of one, and >> why half-open intervals are better than closed intervals: >> >> http://www.johndcook.com/blog/2008/06/26/why-computer-scientists-count-from-zero/ >> http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html >> > > steven, thanks for answering, > > yes, i saw the second one a little time ago (someone else posted it as > well in really cute handwriting version :) and the first time just > now, but the examples which both of them give don't seem to me to be > that relevant, e.g. the pros don't overcome the cons. > > imho, although both sides (mathematical vs engineer) adress some > points, none of them give the final decisive argument. > i understand the math. point of view, but from the practical side it > is not good. it goes nicely into his tidy theory of everything, but > practical and intuitive it is not. as i said, being an engineer, i > tend towards the other side, so this is biased opinion (nobody can be > unbiased) but from a practical side it seems unpractical for > engineering problems (and to me, the purpose of computers is to help > humans to build a better world, not to prove theories - theories are > useless if they don't help us in reality. so we should try to adapt > computing to real world, not our world to computers). > Speaking about "reality", it would have saved a lot of time (but maybe not fun) to just do : >>> myRange = lambda x : range(1, x+1) >>> myRange(4) [1, 2, 3, 4] Put it in a file named "MyIntuition.py" in the python path, and then in your programs you can code : from MyIntuition import myRange -- http://mail.python.org/mailman/listinfo/python-list
Re: Beazley on Generators
In message <13298fc5-5024-4343- bf5a-7e271a08d...@o11g2000yql.googlegroups.com>, Michele Simionato wrote: > However, there are situations when you need thousands of lightweight > threads of execution ;;; The Linux kernel has been tested running hundreds of thousands of threads. -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
On Apr 1, 2:32 pm, Arnaud Delobelle wrote: > Lada Kugis writes: > > I'm coming from fortran and c background so I'm certainly biased by > > them. But if you could explain one thing to me: > > > in fortran for example: > > for i=1,n > > goes from 1,2,3,4,...,n > > > in python for example: > > for i in range(1,n) > > goes from 1,2,3,4,...,n-1 > > (that is, it goes from 1 up to, but not including n) > > > Why is that so ? What were the reasons for that "not including" part ? > > It troubles me greatly, and I cannot see it's advantages over the > > "standard" "up to and including" n. > > > Best regards > > Lada > > Luckily Python allows you to create your own indexing on lists: > > def dec(i): > if isinstance(i, slice): > return slice(dec(i.start), dec(i.stop), i.step) > elif i is None or i < 0: > return i > else: > return i - 1 > > defop = """ > def __%sitem__(s,i,*r): > val = list.__%sitem__(s,dec(i),*r) > if isinstance(i, slice): val = List1(val) > return val > def __%sslice__(s,i,j,*r): > return List1(list.__%sslice__(s,dec(i),dec(j),*r)) > """ > > class List1(list): > for op in 'del', 'get', 'set': > exec defop % (op, op, op, op) > def index(self, x): > return list.index(self, x) + 1 > def insert(self, i, x): > list.insert(self, dec(i), x) > def pop(self, i=None): > return list.pop() if i is None else list.pop(dec(i)) > for op in 'add', 'mul', 'radd', 'rmul': > exec "def __%s__(*r): return List1(list.__%s__(*r))" % (op, op) > > l1 = List1(range(10)) > l2 = List1("Python rules") > > I'll let you play with l1 and l2. If I were your boss and you ever pulled something like this, your ass would be so fired. This is unforgiveable, not only changing the indexing semantics of Python (because a user would have NO CLUE that something underlying has been changed, and thus it should never be done), but also for the needless abuse of exec. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: List of paths
Nico Grubert wrote: Dear Python developers... I have the following (sorted) list I want to remove all paths x from the list if there is a path y in the list which is part of x so y.startswith(x) is true. The list I want to have is: ['/notebook', '/desktop', '/server/hp/proliant'] Any idea how I can do this in Python? Thanks in advance Nico Here's a tricky case that doesn't show up in your example: In each case above, the directory names are distinct. how about: ['/desk', '/desk/ethanallen', '/desk/ikea', '/desktop', /desktop/pc', '/desktop/mac'] Should the answer be ['/desk'] or ['/desk', '/desktop'] ? --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Beazley on Generators
On Mar 31, 10:03 pm, Terry Reedy wrote: > At PyCon2008, David Beazley presented an excellent talk on generators. > Generator Tricks for Systems > Programmershttp://www.dabeaz.com/generators/index.html > > At PyCon2009, he followed up with another talk on more advanced > generator usage, which Guido commended on the python-ideas list: > A Curious Course on Coroutines and Concurrencyhttp://dabeaz.com/coroutines/ > > I have just started (this one will take more than one sitting ;-) but it > looks just as good. Yet another great thing about Python. The ability to run coroutines in Matlab would make my working life a lot easier right now. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Which is more Pythonic? (was: Detecting Binary content in files)
On Apr 2, 2:10 am, John Posner wrote: > Dennis Lee Bieber presented a code snippet with two consecutive statements > that made me think, "I'd code this differently". So just for fun ... is > Dennis's original statement or my "_alt" statement more idiomatically > Pythonic? Are there even more Pythonic alternative codings? > > mrkrs = [b for b in block > if b > 127 > or b in [ "\r", "\n", "\t" ] ] I'd worry about "correct" before "Pythonic" ... see my responses to Dennis in the original thread. > > mrkrs_alt1 = filter(lambda b: b > 127 or b in [ "\r", "\n", "\t" ], > block) > mrkrs_alt2 = filter(lambda b: b > 127 or b in list("\r\n\t"), block) Try this on and see if it fits: num_bin_chars = sum(b > "\x7f" or b < "\x20" and b not in "\r\n\t" for b in block) > (Note: Dennis's statement converts a string into a list; mine does not.) What is list("\r\n\t") doing, if it's not (needlessly) converting a string into a list? > --- > > binary = (float(len(mrkrs)) / len(block)) > 0.30 > > binary_alt = 1.0 * len(mrkrs) / len(block) > 0.30 > num_bin_chars > 0.30 * len(block) (no mucking about with float() or 1.0, and it doesn't blow up on a zero-length block) Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a PIL image object to a buffer
On 1 Apr, 21:43, Gary Herron wrote: > Simon Hibbs wrote: > > I'm trying to dump a snapshot of my application window to the > > clipboard. I can use ImageGrab in PIL to get the screen data into a > > PIL image object, which i have converted to a bitmap using ImageWin, > > but when I try to pass this to the clipboard using - > > > win32clipboard.SetClipboardData(win32clipboard.CF_BITMAP, img) > > > It fails, telling be that "The object must support the buffer > > interface". > > > How can I convert a PIL image into a buffer object? I can't find any > > clues. > > PIL images have a tostring method that returns a string containing all > the pixel data. Would that help you to either create the needed > buffer? Or perhaps you could by-pass the need for a buffer, and just > use the byte string. If I use tostring I get a string which I can put on the clipboard, but it isn't any kind of image. I can make a PIL image from the string but them I'm back to square one again. I suppse I could save the image object to a real file and then send that to the clipboard, but that seems wasteful and I'd have to worry about what to call it and where to put it. Much neater if I could just create it in memory somehow. Simon Hibbs -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting Binary content in files
On Apr 2, 8:39 am, John Machin wrote: > On Apr 1, 4:59 pm, Dennis Lee Bieber wrote: > > > > > On Tue, 31 Mar 2009 14:26:08 -0700 (PDT), ritu > > declaimed the following in > > gmane.comp.python.general: > > > > if ( ( -B $filename || > > > $filename =~ /\.pdf$/ ) && > > > -s $filename > 0 ) { > > > return(1); > > > } > > > According to my old copy of the Camel, -B only reads the "first > > block" of the file. If the block contains a , or if ~30% of the > > block contains bytes >127 or from some (undefined) set of control > > characters (that is, I expect it does not count , , , , > > , maybe some others)... So... > > Not sure whether this is meant to be rough pseudocode or an April 1 > "jeu d'esprit" or ... > > > > > def isbin(fid): > > fin = open(fid, "r") > > (1) mode = "rb" might be better > > > block = fin.read(1024) #what is the size of a "block" these days > > binary = "\0" in block > > if not binary: > > mrkrs = [b for b in block > > if b > 127 > > (2) [assuming Python 2.x] > b is a str object; change 127 to "\x3f" Gah ... it must be gamma rays from outer space! Trying again: change 127 to "\x7f" (and actually "\x7e" would be a better choice) > > > or b in [ "\r", "\n", "\t" > > ] ] #add needed > > (3) surely you mean "b not in" take 2: surely you mean ... or b < "\x20" and b not in "\r\n\t" and at that stage the idea of making a set of chars befor entering the loop has some attraction :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Beazley on Generators
this is great, thanks... we have used generators to create something akin to a cooperative tasking environment... not to implement multitasking, but to be able to control low level data processing scripts. These scripts, written as generators, yield control to a control loop which then can pause, resume, abort, or change the state of shared context objects which the script uses as it's input and output space. E.g. the control loop can see there is intermediate output which an operator (managing a data reduction pipeline) might want to see. I can see from the first few slide I need to understand this. It already seems clear that there are ways to improve our approach to what we have done, though the overall approach is solid and works well. anyway thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: A design problem I met again and again.
On Apr 1, 12:44 am, 一首诗 wrote: > I got the same problem when writing C#/C++ when I have to provide a > lot of method to my code's user. So I create a big class as the entry > point of my code. Although these big classes doesn't contains much > logic, they do grow bigger and bigger. This seems to be a classic result of "code-based organization", that is, you are organizing your code according to how your functions are used. That's appropriate sometimes. Procedural libraries are often organized by grouping functions according to use. The os module is a good example. However, it's usually much better to organize code according to what data it acts upon: "data-based organization". In other words, go though your big class and figure out what data belongs together conceptually, make a class for each conceptual set of data, then assign methods to classes based on what data the methods act upon. Consider the os module again. It's a big collection of functions, but there are a group of functions is os that all act on a particular piece of data, namely a file descriptor. This suggests tha all the functions that act upon file descriptors (os.open, os.close, os.seek, etc.) could instead be methods of a single class, with the file descriptor as a class member. (Note: the os library doesn't do that because functions like os.open are supposed to represent low-level operations corresponding to the underlying system calls, but never mind that. Ordinarily a bunch of functions operating on common data should be organized as a class.) Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
TIOBE programming language community index
The TIOBE programming community index has some interesting data this month. http://www.tiobe.com/content/paperinfo/tpci/index.html * The top three languages, C, C++ and Java between them have a combined rating approaching 50%; * Python has increased popularity over the last year, from position #7 to #6, with more than a 5% rating; * Ruby has remained steady at position 11 over the last year; * But Perl has dropped from #6 to #9; * Much to my happy surprise, Pascal and Delphi are both in the top twenty, at positions 16 and 10 respectively; * Despite the extremely high profile of Lisp and Scheme on discussion lists, it only manages to reach position 23 on the TIOBE index. This should put to rest the fears of certain people that Python is being abandoned in droves for Ruby. Now they can complain that we're not doing enough to overthrow the harsh tyranny of Java and C. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting Binary content in files
On Apr 1, 4:59 pm, Dennis Lee Bieber wrote: > On Tue, 31 Mar 2009 14:26:08 -0700 (PDT), ritu > declaimed the following in > gmane.comp.python.general: > > > > > if ( ( -B $filename || > > $filename =~ /\.pdf$/ ) && > > -s $filename > 0 ) { > > return(1); > > } > > According to my old copy of the Camel, -B only reads the "first > block" of the file. If the block contains a , or if ~30% of the > block contains bytes >127 or from some (undefined) set of control > characters (that is, I expect it does not count , , , , > , maybe some others)... So... Not sure whether this is meant to be rough pseudocode or an April 1 "jeu d'esprit" or ... > > def isbin(fid): > fin = open(fid, "r") (1) mode = "rb" might be better > block = fin.read(1024) #what is the size of a "block" these days > binary = "\0" in block > if not binary: > mrkrs = [b for b in block > if b > 127 (2) [assuming Python 2.x] b is a str object; change 127 to "\x3f" > or b in [ "\r", "\n", "\t" ] > ] #add needed (3) surely you mean "b not in" (4) possible improvements on ["\r", etc etc] : (4a) use tuple ("\r", etc etc) (4b) use string "\r\n\t" (you don't really want to build that list from scratch for each byte tested, do you?) > binary = (float(len(mrkrs)) / len(block)) > 0.30 > fin.close() > return binary Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: double/float precision question
On Wed, 01 Apr 2009 19:13:33 +0200, TP wrote: > Hi everybody, > > Try the following python statements: > "%.40f" % 0.222 > '0.098864108374982606619596' float( 0.222) > 0.1 Remove the leading quote from the first one, and you'll see that the two numbers look pretty similar: 0.098864108374982606619596 0.1 By the way, calling float(0....2) is redundant, because 0.222...2 is already a float. Calling float again just wastes CPU cycles, because the same object is returned again. >>> x = 0.22 >>> x is float(x) # check for object identity (same memory address) True We can see that floats have more precision than they display by default: >>> x 0.1 >>> x - 0. == 0 # Sixteen of digit 2 True >>> x - 0.222 # Fifteen of digit 2 2.2204460492503131e-16 Notice that doing this reveals more significant digits than were apparent from just printing x. > My problem is the following: > * the precision "40" (for example) is given by the user, not by the > programmer. > * I want to use the string conversion facility with specifier "e", that > yields number is scientific format; so I cannot apply float() on the > result of "%.40e" % 0.222, I would lost the > scientific format. No, this is confused. The float you create is the exact same object whether you use scientific format or not. >>> a = 0.0123 >>> b = 1.23e-2 >>> a == b True >>> a 0.0123 >>> b 0.0123 *All* floats contain mantissa and an exponent, but in binary, not decimal: >>> math.frexp(a) (0.78721, -6) >>> 0.78721 * 2**-6 0.0123 > Is there any means to obtain the full C double in Python Floats in Python *are* C doubles. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
Lada Kugis writes: > I'm coming from fortran and c background so I'm certainly biased by > them. But if you could explain one thing to me: > > in fortran for example: > for i=1,n > goes from 1,2,3,4,...,n > > in python for example: > for i in range(1,n) > goes from 1,2,3,4,...,n-1 > (that is, it goes from 1 up to, but not including n) > > Why is that so ? What were the reasons for that "not including" part ? > It troubles me greatly, and I cannot see it's advantages over the > "standard" "up to and including" n. > > Best regards > Lada Luckily Python allows you to create your own indexing on lists: def dec(i): if isinstance(i, slice): return slice(dec(i.start), dec(i.stop), i.step) elif i is None or i < 0: return i else: return i - 1 defop = """ def __%sitem__(s,i,*r): val = list.__%sitem__(s,dec(i),*r) if isinstance(i, slice): val = List1(val) return val def __%sslice__(s,i,j,*r): return List1(list.__%sslice__(s,dec(i),dec(j),*r)) """ class List1(list): for op in 'del', 'get', 'set': exec defop % (op, op, op, op) def index(self, x): return list.index(self, x) + 1 def insert(self, i, x): list.insert(self, dec(i), x) def pop(self, i=None): return list.pop() if i is None else list.pop(dec(i)) for op in 'add', 'mul', 'radd', 'rmul': exec "def __%s__(*r): return List1(list.__%s__(*r))" % (op, op) l1 = List1(range(10)) l2 = List1("Python rules") I'll let you play with l1 and l2. -- Arnaud PS. What day is it again? -- http://mail.python.org/mailman/listinfo/python-list
Re: Alpha/For Discussion: RPMs for around 3,000 PyPI packages.
Sean Reifschneider wrote: > At PyCon I got this idea in my head to try building packages for > everything > in the cheeseshop. I've had some success, getting over 3,000 packages > built on Fedora 10 (and fewer on CentOS 5 and fewer still on 4). This is > out of 6176 packages. neat idea. the info for each package includes information on which python versions it is compatible with. wouldn't it make sense to use that? might explain a lot of failures. andrew -- http://mail.python.org/mailman/listinfo/python-list
Alpha/For Discussion: RPMs for around 3,000 PyPI packages.
At PyCon I got this idea in my head to try building packages for everything in the cheeseshop. I've had some success, getting over 3,000 packages built on Fedora 10 (and fewer on CentOS 5 and fewer still on 4). This is out of 6176 packages. I've made these initial packages, which should be considered no better than *ALPHA* quality) available at: http://10tons.tummy.com/pypi/ If you are a package maintainer, or otherwise want to look at why a package failed to build, you can get the build output at: http://10tons.tummy.com/pypi-output/ At this point I'm looking for feedback on the packages as they are built, and looking to resolve issues found with these packages. The future will hopefully also include builds of Debian packages for at least Debian and Ubuntu, probably on stable and possibly on the latest release as well. USER NOTES == These packages are built simply by doing "python setup.py bdist_rpm". There are packages for both i386 and x86_64. Dependencies are likely incomplete if not incorrect, and we'll probably have to come up with a way of the package maintainers specifying the build and install dependencies. So at this point you will probably have to manually chase dependencies. Sorry about that. PACKAGE MAINTAINER NOTES If you maintain a package on the cheeseshop (http://pypi.python.org/pypi), there are a few things you should know about this repository: You can see the build output of all packages at: http://10tons.tummy.com/pypi-output/ Currently the builds are not automated. This is one of the first things I want to fix, but I will need to set up a secure way of rebuilding packages (so that one package can't compromise another, for example). The current packages were built with a 30 or 60 second time limit on the build. Some packages, if they looked like they were going well and just died, may have died because of the time limit. This time limit will probably be extended in the future. The packages are built basically just by doing "python setup.py bdist_rpm". There are some base set of packages installed on the system, but currently it doesn't do anything about installing dependencies that packages need which are not currently installed. We will probably need a way to specify this, on a per-distribution basis possibly, for both building and installing. I would like to have some community discussion on this. I rely on your source distribution being available either on the pypi.python.org machine (via the "python setup.py upload" command), or that the download link in PyPI point directly at a tar or zip file (.tar, .tar.gz, .tar.bz2, .tgz, .zip extensions). If your download link points at a generic download landing page, my programs can't find your code. I'm open to discussion on this, but in discussions I've had so far I've had no objections to the requirement that the source be on the pypi server. I'm hoping that package maintainers and I can work together to get maintainers the information they need to tweak their packages so that the build system can do the right thing without too many special cases on a package-by-package basis. I appreciate any review and thoughts you have. Feel free to either discuss it on the python mailing list or via e-mail to jafo-commun...@tummy.com Thanks, Sean -- "Never interrupt your enemy when he is making a mistake." -- Napoleon Bonaparte Sean Reifschneider, Member of Technical Staff tummy.com, ltd. - Linux Consulting since 1995: Ask me about High Availability -- http://mail.python.org/mailman/listinfo/python-list
Re: Demographic Information about Python
2009/4/1 Betiana Krancenblum : > Hi, > > I'm looking for statistical information about where Python is beeing used as > a programming language and where it is teached as a language for beginner > programmers. > Where do you think I can find that information? I don't think there are any statistics per se, but MIT tried (is trying?) Python for its CS intro course - http://www.amk.ca/diary/2006/11/mit_to_try_python_for_introduc.html Cheers, Chris -- I have a blog: http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
py2exe problem
Hey list, what kind of error do I have with getting this error at starting my app. Im am not using IdleConf.GetOption right now. Warning: configHandler.py - IdleConf.GetOption - problem retrieving configration option 'name' from section 'Keys'. returning default value: '' -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a PIL image object to a buffer
Simon Hibbs wrote: I'm trying to dump a snapshot of my application window to the clipboard. I can use ImageGrab in PIL to get the screen data into a PIL image object, which i have converted to a bitmap using ImageWin, but when I try to pass this to the clipboard using - win32clipboard.SetClipboardData(win32clipboard.CF_BITMAP, img) It fails, telling be that "The object must support the buffer interface". How can I convert a PIL image into a buffer object? I can't find any clues. PIL images have a tostring method that returns a string containing all the pixel data. Would that help you to either create the needed buffer? Or perhaps you could by-pass the need for a buffer, and just use the byte string. Gary Herron Help appreciated, Simon Hibbs -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Demographic Information about Python
Hi, I'm looking for statistical information about where Python is beeing used as a programming language and where it is teached as a language for beginner programmers. Where do you think I can find that information? Thanks, Betiana _ ¿Querés cuidarte y estar bien? Conocé MSN Salud y Bienestar http://salud.latam.msn.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: double/float precision question
TP wrote: > Hi everybody, > > Try the following python statements: > > >>> "%.40f" % 0.222 > '0.098864108374982606619596' > >>> float( 0.222) > 0.1 > > It seems the first result is the same than the following C program: > > #include > > int main(void) > { > double a = 0.222; > > printf( "%.40f\n", a ); > return 0; > } > # > > My problem is the following: > * the precision "40" (for example) is given by the user, not by the > programmer. > * I want to use the string conversion facility with specifier "e", that > yields number is scientific format; so I cannot apply float() on the result > of "%.40e" % 0.222, I would lost the scientific > format. > > Is there any means to obtain the full C double in Python, or should I limit > the precision given by the user (and used in "%.*e") to the one of a Python > float? Python floats are actually C doubles (as you proved yourself with your little test program). Eg >>> 1.+2.**-52 1.0002 >>> 1.+2.**-53 1.0 Indicating that python floats have about 52 bits of precision, so are definitely what C calls doubles. When you do >>> float( 0.222) 0.1 Python prints as many decimal places as are significant in the answer. This is covered in the FAQ http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate If you want more precision use the built in decimal module or the third party gmpy module. -- Nick Craig-Wood -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: imp.load_source() - explanation needed
On Wed, 2009-04-01 at 12:17 -0700, mynthon wrote: > Hi! > > I need help. I don't understand what doc says. > > I load module from path testmod/mytest.py using imp.load_source(). My > code is > > import imp > testmod = imp.load_source('koko', 'testmod/mytest.py) > print testmod > > but i don't understand whatt is first (name) argument for. Docs says > that "The name argument is used to create or access a module object." > But i still don't understand. I cant do this > > import imp > testmod = imp.load_source('koko', 'testmod/mytest.py) > print koko > I think that importing and loading are seperate steps. So either >>> koko = imp.load_source('koko', 'testmod/mytest.py') or >>> imp.load_source('koko', 'testmod/mytest.py') >>> import koko -- http://mail.python.org/mailman/listinfo/python-list
Re: Stripping non-numbers from a file parse without nested lists?
On Apr 1, 8:10 am, jay logan wrote: > On Apr 1, 11:05 am, jay logan wrote: > > > > > On Apr 1, 2:35 am, daku9...@gmail.com wrote: > > > > On Mar 31, 6:47 pm, "Rhodri James" > > > wrote: > > > > > What you're doing (pace error checking) seems fine for the data > > > > structures that you're using. I'm not entirely clear what your usage > > > > pattern for "dip" and "dir" is once you've got them, so I can't say > > > > whether there's a more appropriate shape for them. I am a bit curious > > > > though as to why a nested list is non-ideal? > > > > > ... > > > > if "/" in word and "dip" not in word: > > > > dip_n_dir.append(word.split("/", 1)) > > > > > is marginally shorter, and has the virtue of making it harder to use > > > > unrelated dip and dir values together. > > > > > -- > > > > Rhodri James *-* Wildebeeste Herder to the Masses > > > > Rhodri, > > > > Thanks. That works better than what I had before and I learned a new > > > method of parsing what I was looking for. > > > > Now I'm on to jumping a set number of lines from a given positive > > > search match: > > > > ...(lines of garbage)... > > > 5656 (or some other value I want, but don't explicitly know) > > > ...(18 lines of garbage)... > > > search object > > > ...(lines of garbage)... > > > > I've tried: > > > > def read_poles(filename): > > > index = 0 > > > fh = None > > > try: > > > fh = open(filename, "r") > > > lines=fh.readlines() > > > while True: > > > > if "search object" in lines[index] > > > poles = int(lines[index-18]) > > > print(poles) > > > > index +=1 > > > > except(IndexError): pass > > > > finally: > > > if fh is not None: # close file > > > fh.close() > > > > -- > > > > Which half works. If it's not found, IndexError is caught and passed > > > (avoids quitting on lines[index out of range]. The print(poles) > > > properly displays the value I am looking for (_always_ 18 lines before > > > the search object). > > > > However, since it is assigned using the index variable, the value of > > > poles doesn't keep (poles is always zero when referenced outside of > > > the read_poles function). I'm assuming because I'm pointing to a > > > certain position of an object and once index moves on, it no longer > > > points to anything valid. My python book suggested using > > > copy.deepcopy, but that didn't get around the fact I am calling it on > > > (index-18). > > > > Any experience jumping back (or forward) a set number of lines once a > > > search object is found? This is the only way I can think of doing it > > > and it clearly has some problems. > > > > Reading the file line by line using for line in blah works for finding > > > the search object, but I can't see a way of going back the 18 lines to > > > grabbing what I need. > > > > Thanks for the help! I'm slowly getting this mangled mess of a file > > > into something automated (hand investigating the several thousand > > > files I need to do would be unpleasant). > > > # You could try using a deque holding 18 lines and search using that > > deque > > # This is untested, but here's a try (>=Python 3.0) > > from collections import deque > > import itertools as it > > import sys > > > def read_poles(filename): > > with open(filename) as f: > > line_iter = iter(f) > > d = deque(it.islice(line_iter,17), maxlen=18) > > > for line in line_iter: > > d.append(line) > > > if 'search object' in line: > > poles = int(d[0]) > > print(poles) > > return poles > > else: > > print('No poles found in', filename, file=sys.err) > > Notice that I returned the "pole" from the function so you could catch > the return value as follows: > pole = read_poles(filename) > > if pole is None: > # no poles found > else: > print('Function returned this pole:', pole) > > If you need a list of poles, then return a list: > > def read_poles(filename): > all_poles = [] > with open(filename) as f: > line_iter = iter(f) > d = deque(it.islice(line_iter,17), maxlen=18) > > for line in line_iter: > d.append(line) > > if 'search object' in line: > all_poles.append(int(d[0])) > return all_poles > > ... > poles = read_poles(filename) > > if poles: > print('Here are the poles:\n', '\n'.join(map(str,poles))) > else: > print('There were no poles found in', filename) I think I found an easier (if possibly uglier way) of doing it: for filenames in files.split(): try: fh = open(filenames.replace("/","\\"),"r") lines=fh.readlines() except(IOError) as err: print(filename, err) finally: if fh is not None: fh.close() print(read_poles4(lines)) ... which opens my file (always < 10 megs
Converting a PIL image object to a buffer
I'm trying to dump a snapshot of my application window to the clipboard. I can use ImageGrab in PIL to get the screen data into a PIL image object, which i have converted to a bitmap using ImageWin, but when I try to pass this to the clipboard using - win32clipboard.SetClipboardData(win32clipboard.CF_BITMAP, img) It fails, telling be that "The object must support the buffer interface". How can I convert a PIL image into a buffer object? I can't find any clues. Help appreciated, Simon Hibbs -- http://mail.python.org/mailman/listinfo/python-list
imp.load_source() - explanation needed
Hi! I need help. I don't understand what doc says. I load module from path testmod/mytest.py using imp.load_source(). My code is import imp testmod = imp.load_source('koko', 'testmod/mytest.py) print testmod but i don't understand whatt is first (name) argument for. Docs says that "The name argument is used to create or access a module object." But i still don't understand. I cant do this import imp testmod = imp.load_source('koko', 'testmod/mytest.py) print koko How i can access module object using its name? Is " print sys.modules ['koko'] " only way or am i missing something? -- http://mail.python.org/mailman/listinfo/python-list
Re: A design problem I met again and again.
一首诗 wrote: But I think the first step to resolve a problem is to describe it. In that way, I might find the answer myself That is an excellent approach, knowing you have a problem and describing it is actually the hardest part of a design, the rest is more like a puzzle. What I guess so far is that you tried to (re)design your work by grouping on functionality and using classes for more clearer work. From what you wrote (that is if I understood you correctly), both of these approaches don't really seem to get 'there'. It might be worth to try another approach, instead of focussing on the characteristics of the functions and using them as a guideline for your design you could try this: Step 1: Write a Functional Design from a user perspective, restrain yourself from implying anything technical or choosing specific tools. Imagine yourself as an end-user and not as a developer. Pick a random person of the street that looks literate but is not working in IT (secretaries are usually great for this!), let them comment on your language and then quiz them about the content to see if they actually understood what you wrote. If commenting on language seems strange, in my experience if I can't properly describe what I want to say then there is a good chance that I haven't thought about it sufficiently or I was lazy in describing it. Step 2: Take this functional design and write a functional specification. This is much like the design but instead focusses on the business processes and interdependencies of these. Write out implied constraints and things you might think is obvious, although the specification are technical in nature you should still avoid naming specific tools unless it is to describe functionality, i.e. google like approach of indexing data. Use plain English (or whatever language you want to write it in) for this, don't use any diagrams, SQL table layouts, UML etc. Pick a random IT related colleague (network administrators are usually my preferred choice), let them read it and quiz them to make sure the specification are clear enough. Step 3: When you have your functional specification, write a technical design. Here you make a choice on the tools you are going to use based on evidence based research and describe the general outline of your solution. Pour your co-worker a nice cup of beverage of their choice and let them read it and of course quiz them. Step 4: Finally, use the technical design for writing a technical specification. Design you program using UML (or whatever thing that makes you look like you are developing without writing code). Specify deep, down to the name of all 'public' functions. Step 5: Let it rest for the weekend. Step 6: Reread your technical specification, if it still makes sense, continue. If it doesn't, go back to step 1 and repeat the process with the changes you made. Step 7: Do what you usually do (I write my unit-tests first and then solve them). Step 8: Compare the end product with your original functional design. If they do not align go back to Step 1. Some hints I found useful during step 4. I try to take in account that it is not me who is going to develop it but a team of reasonable qualified developers. Thus I split up the work in parts that can be simultaneously done by more then one person without them needing to know exactly what the other one is doing. If there is a need to know what the other developer is doing then the specification was not precise enough. If during the whole process something comes up that shows a better way, change your documentation accordingly. When all of this still results in an 'ugly' design, try letting more people read your documentation, if that doesn't help then one or more of the following may apply: - Despite of its ugliness it is the most elegant design possible. - You are working on something that is fundamentally broken. - You haven't met the person that can give you more insight. YMMV -- mph -- http://mail.python.org/mailman/listinfo/python-list
Re: New super python vm
On Apr 1, 1:55 pm, El Loco wrote: > Hi all, > > This is to announce that right after a few weeks after our first > coding sprint, > our project, "Unswallowed-snot", has already achieved substantial > results. > In our tests, runtime performance shows a 150x slowdown. > This is due mainly to our lead developer (myself) still not knowing > enough python, > but we expect the situation improves, or not, in the next couple of > months. > > Interested hackers, please drop me an email. > Thanks! > l&f Sounds good, but do you have binaries yet? because i can't compile from source distros. -- http://mail.python.org/mailman/listinfo/python-list
Re: league problem in python
On Apr 1, 12:35 pm, Ross wrote: [snip] > How should I go about starting this problem...I'm feel like this is a > really simple problem, but I'm having writer's/coder's block. Can you > guys help? Ross, I highly disagree with bear on this. What you have here is a 90 percent math problem and a 10 percent code problem. First get the numbers to add up correctly and then code that sucker up! -- http://mail.python.org/mailman/listinfo/python-list
[Ann] New super python vm
Hi all, This is to announce that right after a few weeks after our first coding sprint, our project, "Unswallowed-snot", has already achieved substantial results. In our tests, runtime performance shows a 150x slowdown. This is due mainly to our lead developer (myself) still not knowing enough python, but we expect the situation improves, or not, in the next couple of months. Interested hackers, please drop me an email. Thanks! l&f -- http://mail.python.org/mailman/listinfo/python-list
Re: double/float precision question
It's not at all clear what you really want. You say you want to "use" the %e format, but then imply you're then going to turn it back into a float. Since I don't know what the end goal is, I'll just comment generally. All Python floating point is equivalent to the 'double' type of the C implementation. That may vary by C compiler, or by processor, but what you see is typical of an 8 byte double type. I don't really remember my values, but it's around 16 digits of precision. Anything displayed beyond those digits is noise, and shouldn't be considered reproducible. In other words, those two results are the same, the rounding is just different. To put it simply, in Python, float() on a floating point number does not reduce the precision in the least. As for having the user specify the number of digits he/she wants, that just means you have to construct the format string in a variable. Something like: digits = 14 (this you'd have gotten from a user) format = "%." + str(digits) + "e" result = format % number #this does the formatting TP wrote: Hi everybody, Try the following python statements: "%.40f" % 0.222 '0.098864108374982606619596' float( 0.222) 0.1 It seems the first result is the same than the following C program: #include int main(void) { double a = 0.222; printf( "%.40f\n", a ); return 0; } # My problem is the following: * the precision "40" (for example) is given by the user, not by the programmer. * I want to use the string conversion facility with specifier "e", that yields number is scientific format; so I cannot apply float() on the result of "%.40e" % 0.222, I would lost the scientific format. Is there any means to obtain the full C double in Python, or should I limit the precision given by the user (and used in "%.*e") to the one of a Python float? Thanks in advance Julien -- http://mail.python.org/mailman/listinfo/python-list
Re: List of paths
On Apr 1, 3:57 am, Nico Grubert wrote: > Dear Python developers > > I have the following (sorted) list. > ['/notebook', > '/notebook/mac', > '/notebook/mac/macbook', > '/notebook/mac/macbookpro', > '/notebook/pc', > '/notebook/pc/lenovo', > '/notebook/pc/hp', > '/notebook/pc/sony', > '/desktop', > '/desktop/pc/dell', > '/desktop/mac/imac', > '/server/hp/proliant', > '/server/hp/proliant/385', > '/server/hp/proliant/585' > ] > > I want to remove all paths x from the list if there is a path y in the > list which is part of x so y.startswith(x) is true. > > The list I want to have is: > ['/notebook', '/desktop', '/server/hp/proliant'] > > Any idea how I can do this in Python? > > Thanks in advance > Nico paths = ['/notebook', '/notebook/mac', '/notebook/mac/macbook', '/notebook/mac/macbookpro', '/notebook/pc', '/notebook/pc/lenovo', '/notebook/pc/hp', '/notebook/pc/sony', '/desktop', '/desktop/pc/dell', '/desktop/mac/imac', '/server/hp/proliant', '/server/hp/proliant/385', '/server/hp/proliant/585' ] seen = set() basepaths = [ seen.add(s) or s for s in paths if not any(s.startswith(ss) for ss in seen) ] gives: ['/notebook', '/desktop', '/server/hp/proliant'] -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: A design problem I met again and again.
一首诗 wrote: > But I think the first step to resolve a problem is to describe it. In > that way, I might find the answer myself :-) That is a great saying! To answer your original question, split your code up into sections that can be tested independently. If you can test code in a isolated way then it belongs in a class / module of its own. If you have a class that is too big, then factor independent classes out of it until it is the right size. That is easier said than done and may require some creativity on your part. It will pay dividends though as the level of abstraction in your program will rise. I've noticed some programmers think in big classes and some think in small classes. Train yourself to do the other thing and your programming will improve greatly! -- Nick Craig-Wood -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a Python Module - Available Implementations
A python source file *is* a module. And you import it the same way you import any of the system modules. Just use the basename, without the .py extension. import mylib The only catch is where you locate this module. When you first write it, just put it in the same directory as your scripts, and it'll automatically be found. Then when you're using it from scripts that aren't all located in the same directory, move it to a place on the sys.path. Finally, when you have several related modules, you can make them into a package. A package is a directory located on the path, that contains afiloe wit the special name __init__.py There's some description needed for each of these steps, but just knowing what they are should be enough for now. Besides, the description varies by python version. The only needs to create a C-based module would be if 1) performance is an overriding consideration 2) or it's already written in C 3) or it needs access to some system facility that's not easily available directly from Python. Even then, you probably would write a bit of C "glue," and the rest in Python. ntwrkd wrote: I have been browsing through creating a Python module for common custom functions that I frequently use, but I am wondering, is this the best method, and is it necessary? Really all I need is to import functions from another plaintext Python source file, how might I do this? What would merit the need to create a C-based Python module? Thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
In article <91t6t4hfjicgvdrcgkhdjfro3ko3ktu...@4ax.com>, Lada Kugis wrote: > On Wed, 1 Apr 2009 00:40:17 -0700 (PDT), Carl Banks > wrote: > > > > >Lada, > > > >I am also an engineer, and I can tell your idea of intuitive is not > >universal, even among engineers. I certainly do not lean toward one- > >based indexing. > > > >From a programming standpoint--and remember Python is a programming > >language--zero-based indexing eliminates the need for a whole lot of > >extra +1s and -1s when indexing, slicing, and iterating, a lot more > >than it causes, and that is worth the "cost". This might not be > >apparent to you if you never tried seriously taking advantage of > >indexing from zero, or if your programming experience is very narrow. > >These both seem to be true for you, so you'll just have to take my > >word for it. > > > You have repeated several cs based points already stated. But apart > from a programming standpoint - could you give a few examples, where > "on paper" (as to avoid stepping into "programmer's territory") zero > indexing could be more intuitive ? This has become a moving target. I thought your original complaint was about Python (the programming language) vs. Fortran (the programming language) and C (the programming language used in an odd way). -- -- Lou Pecora -- http://mail.python.org/mailman/listinfo/python-list
Re: league problem in python
Ross: > How should I go about starting this problem...I'm feel like this is a > really simple problem, but I'm having writer's/coder's block. Can you > guys help? There are refined ways to design a program, but this sounds like a simple and small one, so you probably don't need much formal things to solve it. So start writing down: 1) A precise description of what results you want 2) A precise description of what data you have to find those answers 2b) You may want to think about what kind of user interface to give to your program, but being this program very small and being you not much experienced yet, you may think about this later too (see point 9). Then: 3) Invent the simplest way to feed that data to the program, for example reading a TXT file. 4) Create artificially some toy data files, very short, and able to reveal several of the corner cases of your problem. Then start programming in a test-driven way. Write a tiny program that just reads and decodes the input data of one of your inputs and shows them. 5) Once that is done, you may write some outputs, that is the result of each of those little inputs. 6) Try to slowly grow the code to go toward the solutions you look for. 7) If the algorithm and processing required to find the solutions isn't simple, then you may want to step away from the computer, take a graphite pencil, eraser and paper and invent how to solve the problem generally. 7b) sometimes you may also need to invent how to represent data and solutions (and even intermediate stages) into your small program. 8) Keep creating more complex test cases and look if their solution is correct. If it's wrong then debug your program. Soon your purpose will be to invent stranger and stranger corner cases able to break your program (that make your program give a wrong answer). 9) Eventually you will have to think to improve the user interface. In bigger programs this has to be done after point (2), but for your small program you may do it now too. This programming strategy is not good enough if you are writing big programs or very difficult ones, but for small easy programs it's more than enough. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: double/float precision question
On Apr 1, 12:13 pm, TP wrote: > Hi everybody, > > Try the following python statements: > > >>> "%.40f" % 0.222 > > '0.098864108374982606619596'>>> float( > 0.222) > > 0.1 > > It seems the first result is the same than the following C program: > > #include > > int main(void) > { > double a = 0.222; > > printf( "%.40f\n", a ); > return 0;} > > # > > My problem is the following: > * the precision "40" (for example) is given by the user, not by the > programmer. > * I want to use the string conversion facility with specifier "e", that > yields number is scientific format; so I cannot apply float() on the result > of "%.40e" % 0.222, I would lost the scientific > format. > > Is there any means to obtain the full C double in Python, or should I limit > the precision given by the user (and used in "%.*e") to the one of a Python > float? You can get arbitrary precision floats from the gmpy module. > > Thanks in advance > > Julien > > -- > python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\ > 9&1+,\'Z4(55l4('])" > > "When a distinguished but elderly scientist states that something is > possible, he is almost certainly right. When he states that something is > impossible, he is very probably wrong." (first law of AC Clarke) -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
On Apr 1, 9:08 am, Lada Kugis wrote: > On Wed, 1 Apr 2009 00:40:17 -0700 (PDT), Carl Banks > > > > > > wrote: > > >Lada, > > >I am also an engineer, and I can tell your idea of intuitive is not > >universal, even among engineers. I certainly do not lean toward one- > >based indexing. > > >From a programming standpoint--and remember Python is a programming > >language--zero-based indexing eliminates the need for a whole lot of > >extra +1s and -1s when indexing, slicing, and iterating, a lot more > >than it causes, and that is worth the "cost". This might not be > >apparent to you if you never tried seriously taking advantage of > >indexing from zero, or if your programming experience is very narrow. > >These both seem to be true for you, so you'll just have to take my > >word for it. > > You have repeated several cs based points already stated. But apart > from a programming standpoint - could you give a few examples, where > "on paper" (as to avoid stepping into "programmer's territory") zero > indexing could be more intuitive ? Here's an easy example: Standard Positional Number Systems. 765 in octal is 7 * 8**2 + 6 * 8**1 + 5 * 8**0 123 in decimal is 1 * 10**2 + 2 * 10**1 + 3 * 10**0 666 in hexadecimal is 6 * 16**2 + 6 * 16**1 + 6 * 16**0 0-based indexing is kinda important. > (of course, taking into account your previous based calculations, > which are based on 1 indexing - I imagine you still use matrices with > a11 as a first element) > > Lada- Hide quoted text - > > - Show quoted text - -- http://mail.python.org/mailman/listinfo/python-list
Re: Thoughts on language-level configuration support?
On Apr 1, 6:29 am, jfager wrote: > On Apr 1, 3:29 am, Kay Schluehr wrote: > > > > "Discoverable", as in built-in tools that let you have the following > > > conversation: "Program, tell me all the things I can configure about > > > you" - "Okay, here they all are". No digging through the source > > > required. > > > But this doesn't have any particular meaning. If I run a dir(obj) > > command all attributes of obj will be returned and I can be sure these > > are all. In C# I can reflect on attributes of an assembly which is a > > well defined entity. "Program" is not an entity. It's kind of a user > > interface name in StarTreck ( which prefers "computer" for this > > purpose though ). This way we cannot design systems. > > "Module and transitive graph of other modules (constructed through > 'import' statements), tell me all the things I can configure about > you". Is that a little clearer? Using shelve, which I suggested earlier, you have to rely on modules to choose the options they want to make available. You could require them to store configs. on a per-module basis in separate files, or require them to use separate namespaces in the shelf. It could also be possible to interface with the target process's garbage collector, but you're limited to objects you can identify in the list of tracked objects, and only the ones that are mutable at that. -- http://mail.python.org/mailman/listinfo/python-list
RE: Which is more Pythonic? (was: Detecting Binary content in files)
>> > mrkrs_alt2 = filter(lambda b: b > 127 or b in list("\r\n\t"), block) >> > >> >> Never tested my 'pythonicity', but I would do: >> >> def test(b) : b > 127 or b in r"\r\n\t" Oops! Clearly, b in "\r\n\t" is preferable to ... b in list("\r\n\t") You do *not* want to use a raw string here: >>> len ("\n\r\t") 3 >>> len (r"\n\r\t") 6 E-mail message checked by Spyware Doctor (6.0.0.386) Database version: 5.12090 http://www.pctools.com/en/spyware-doctor-antivirus/ -- http://mail.python.org/mailman/listinfo/python-list
league problem in python
I'm new to programming and have chosen Python as my first language. I've gone through Allen Downey's Think Python book and I think I'm ready to dive into a project. The first problem I've chosen to tackle is a problem I have seen at my tennis club. Each spring/fall, the pro puts out a sheet of paper for people to sign up for tennis leagues. Depending on how many people sign up for a league, he'll assign a certain number of courts each week to that league. After this, he makes up a schedule of who plays who on each week and who has a bye. Unfortunately, he does this by hand and a lot of times, some people will play certain people more than once and certain other people never. Other problems that arise: some people have more bye weeks than others, some people have all their bye weeks clumped together so that they don't play for weeks on end. I would like to create a simple program where the pro could enter in how many people were in the league, the number of courts available, and the number of weeks the schedule would run and then generate a schedule where everybody played everybody else once and got the same number of bye weeks, preferably spaced out evenly. How should I go about starting this problem...I'm feel like this is a really simple problem, but I'm having writer's/coder's block. Can you guys help? -- http://mail.python.org/mailman/listinfo/python-list
Re: The spam to content ratio of this group
On Apr 1, 9:57 am, Grant Edwards wrote: > On 2009-04-01, Eric wrote: > 3) Simply ignoring all posts made from Google Groups works > quite well. Yea, there's no spam in Usenet land APRIL FOOLS -- http://mail.python.org/mailman/listinfo/python-list
double/float precision question
Hi everybody, Try the following python statements: >>> "%.40f" % 0.222 '0.098864108374982606619596' >>> float( 0.222) 0.1 It seems the first result is the same than the following C program: #include int main(void) { double a = 0.222; printf( "%.40f\n", a ); return 0; } # My problem is the following: * the precision "40" (for example) is given by the user, not by the programmer. * I want to use the string conversion facility with specifier "e", that yields number is scientific format; so I cannot apply float() on the result of "%.40e" % 0.222, I would lost the scientific format. Is there any means to obtain the full C double in Python, or should I limit the precision given by the user (and used in "%.*e") to the one of a Python float? Thanks in advance Julien -- python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\ 9&1+,\'Z4(55l4('])" "When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong." (first law of AC Clarke) -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
andrew cooke wrote: MRAB wrote: Steven D'Aprano wrote: On Wed, 01 Apr 2009 04:58:48 +0200, Lada Kugis wrote: Why do we try to create languages that are intuitive to humans, then ? Because of the foolish hope that sufficiently easy syntax will make excellent programmers out of average people. Programming is not intuitive to humans. *Counting* isn't intuitive to humans -- children need to learn how to count. [snip] Research suggests that your wrong. For example, even baby chicks can count: http://news.bbc.co.uk/1/hi/sci/tech/7975260.stm i saw that earlier today. it's really pushing the definition of "count", at least as described there. there have been similar experiments where they address whether the animal is actually looking at "how big" the total "pile" is rather than counting (do they know the difference between two small things and one big thing, for example). that experiment doesn't seem to address this. Just occurred to me. Chicks and eggs, on 1 April, with Easter approaching. Hmm... -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
On Apr 1, 7:08 am, Lada Kugis wrote: > On Wed, 1 Apr 2009 00:40:17 -0700 (PDT), Carl Banks > > > > > > wrote: > > >Lada, > > >I am also an engineer, and I can tell your idea of intuitive is not > >universal, even among engineers. I certainly do not lean toward one- > >based indexing. > > >From a programming standpoint--and remember Python is a programming > >language--zero-based indexing eliminates the need for a whole lot of > >extra +1s and -1s when indexing, slicing, and iterating, a lot more > >than it causes, and that is worth the "cost". This might not be > >apparent to you if you never tried seriously taking advantage of > >indexing from zero, or if your programming experience is very narrow. > >These both seem to be true for you, so you'll just have to take my > >word for it. > > You have repeated several cs based points already stated. But apart > from a programming standpoint - could you give a few examples, where > "on paper" (as to avoid stepping into "programmer's territory") zero > indexing could be more intuitive ? That's beside the point. Python's job is to be usable as a programming language. It made a decision to use zero-based indexing so as to simplify programming usage. Therefore, that's what you have to use for matrix indices, whether it is intuitive for you or not. I have no real opinion whether zero- or one-based indexing works best on paper for engineering calculations, except that it's a trivial consideration. > (of course, taking into account your previous based calculations, > which are based on 1 indexing - I imagine you still use matrices with > a11 as a first element) I don't know what you're referring to by my previous based calculations, and the sentences doesn't make sense, so I can't answer this. FTR: I use zero-based matrix indices when I'm using a language with zero-based indexing, and one-based indices when using a language with one-based indexing. Simple as that. You should do the same. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Creating a Python Module - Available Implementations
I have been browsing through creating a Python module for common custom functions that I frequently use, but I am wondering, is this the best method, and is it necessary? Really all I need is to import functions from another plaintext Python source file, how might I do this? What would merit the need to create a C-based Python module? Thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: Beazley on Generators
On Wed, 01 Apr 2009 01:03:50 -0400, Terry Reedy wrote: > At PyCon2008, David Beazley presented an excellent talk on generators. > Generator Tricks for Systems Programmers > http://www.dabeaz.com/generators/index.html > > At PyCon2009, he followed up with another talk on more advanced > generator usage, which Guido commended on the python-ideas list: > A Curious Course on Coroutines and Concurrency > http://dabeaz.com/coroutines/ Great presentations. Thanks. -- To email me, substitute nowhere->spamcop, invalid->net. -- http://mail.python.org/mailman/listinfo/python-list
Re: Which is more Pythonic? (was: Detecting Binary content in files)
On Apr 1, 5:10 pm, John Posner wrote: > Dennis Lee Bieber presented a code snippet with two consecutive statements > that made me think, "I'd code this differently". So just for fun ... is > Dennis's original statement or my "_alt" statement more idiomatically > Pythonic? Are there even more Pythonic alternative codings? > > mrkrs = [b for b in block > if b > 127 > or b in [ "\r", "\n", "\t" ] ] > > mrkrs_alt1 = filter(lambda b: b > 127 or b in [ "\r", "\n", "\t" ], > block) > mrkrs_alt2 = filter(lambda b: b > 127 or b in list("\r\n\t"), block) > Never tested my 'pythonicity', but I would do: def test(b) : b > 127 or b in r"\r\n\t" mrkrs = filter( test, block ) Note: before starting to study haskell, I would probably have used the list comprehension. Still can't stand anonimous functions though. > (Note: Dennis's statement converts a string into a list; mine does not.) > > --- > > binary = (float(len(mrkrs)) / len(block)) > 0.30 > > binary_alt = 1.0 * len(mrkrs) / len(block) > 0.30 > I believe now one should do (at least on new code): from __future__ import division # not needed for python 3.0 binary = ( len( mrks) / len (blocks) ) > 3.0 In the past, I often used the * 1.0 trick, but nevertheless believe that it is better using explicit cast. > -John > Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list
Matrix operations on character matrix element?
I hope somebody will be able to help me here. I am trying to solve some physical problems that will require the generation of some function in terms of some parameters. These functions are derived from matrix operation on “characters”. Are there ways numpy/scipy perform matrix operations on characters? For example A = matrix([[a, b,c],[d,e,f],[1,2,3]]) B = matrix([[g,h,4],[I,j,5],[k,l,6]]) Is it possible to perform operations like A*B or A+B And most especially: linalg.solve(A,eye(3,3)) Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: A design problem I met again and again.
On Wed, Apr 1, 2009 at 3:40 PM, 一首诗 wrote: > What are the average size of source files in your project? If it's > far lower than 15,000, don't feel it's a little unbalance? > -- > http://mail.python.org/mailman/listinfo/python-list > While I think 15,000 is, in the vast majority of cases, quite high, what we're talking about here isn't about LOC, it's about whether or not things are separated cleanly. I'm sure that sometimes that means a 15,000 line file (although I can't think of a relevant example off the top of my head). Whether or not the other files are a lot smaller doesn't matter. "Correctly" organizing a project is more about separation of responsibility than line-count. -- http://mail.python.org/mailman/listinfo/python-list
Re: List of paths
Sure, generators rock! :-) 2009/4/1 andrew cooke : > Nico Grubert wrote: >>> May be not so much pythonic, but works >>> >>> for i in range(len(q)): >>> for x in q[i:]: >>> if x.startswith(q[i]) and x!=q[i]: >>> q.remove(x) >> >> ...but works fine. Thanks, Eugene. >> Also thanks to Andrew. Your example works fine, too. Thanks to remind me >> of the 'yield' statement! ;-) > > in case it's not clear, the method above is O(n^2) while mine was O(n). > that will not matter for small lists, but for long ones mine will be much > faster. > > andrew > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Sincerely yours, Eugene Perederey > -- Sincerely yours, Eugene Perederey -- http://mail.python.org/mailman/listinfo/python-list
Re: The spam to content ratio of this group
s...@pobox.com wrote: Eric> is getting very high. Why aren't captcha's used to prevent all of Eric> this noise? Steven> /me opens mouth to make sarcastic comment Steven> /me shuts mouth again Steven> That's like saying "There's a lot of oil slicks washing up onto Steven> the beach. Why don't we put more trashcans by the road to the Steven> beach?" What good do you think captchas will do on a newsgroup? Come on over the python-l...@python.org. The water's fine! I was going to say much the same, coupled with a vote of thanks to the people (person?) who's done all the work to keep the spam at bay. (part-pun partly intended) TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: The spam to content ratio of this group
Eric> is getting very high. Why aren't captcha's used to prevent all of Eric> this noise? Steven> /me opens mouth to make sarcastic comment Steven> /me shuts mouth again Steven> That's like saying "There's a lot of oil slicks washing up onto Steven> the beach. Why don't we put more trashcans by the road to the Steven> beach?" What good do you think captchas will do on a newsgroup? Come on over the python-l...@python.org. The water's fine! -- Skip Montanaro - s...@pobox.com - http://www.smontanaro.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: xml to xhtml
On Wed, Apr 1, 2009 at 10:43 AM, wrote: > If anyone can give me some guidance what should be the best way to > generate html/xhtml page using python would be great. I am open to > other options like xsl or anything else that can make things simple. Since you're open to other options, I would take a look at XSLT. http://www.w3schools.com/xsl/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Beazley on Generators
Kay Schluehr wrote: > There is just one thing I find disappointing. Since the talk is almost > a compendium of advanced uses of generators I'm missing a reference to > Peter Thatchers implementation of monads: > > http://www.valuedlessons.com/2008/01/monads-in-python-with-nice-syntax.html > > Peters implementation can be simplified but it already contains all > relevant ideas. oh that's neat. thanks for that. andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: Stripping non-numbers from a file parse without nested lists?
On Apr 1, 11:05 am, jay logan wrote: > On Apr 1, 2:35 am, daku9...@gmail.com wrote: > > > > > On Mar 31, 6:47 pm, "Rhodri James" > > wrote: > > > > What you're doing (pace error checking) seems fine for the data > > > structures that you're using. I'm not entirely clear what your usage > > > pattern for "dip" and "dir" is once you've got them, so I can't say > > > whether there's a more appropriate shape for them. I am a bit curious > > > though as to why a nested list is non-ideal? > > > > ... > > > if "/" in word and "dip" not in word: > > > dip_n_dir.append(word.split("/", 1)) > > > > is marginally shorter, and has the virtue of making it harder to use > > > unrelated dip and dir values together. > > > > -- > > > Rhodri James *-* Wildebeeste Herder to the Masses > > > Rhodri, > > > Thanks. That works better than what I had before and I learned a new > > method of parsing what I was looking for. > > > Now I'm on to jumping a set number of lines from a given positive > > search match: > > > ...(lines of garbage)... > > 5656 (or some other value I want, but don't explicitly know) > > ...(18 lines of garbage)... > > search object > > ...(lines of garbage)... > > > I've tried: > > > def read_poles(filename): > > index = 0 > > fh = None > > try: > > fh = open(filename, "r") > > lines=fh.readlines() > > while True: > > > if "search object" in lines[index] > > poles = int(lines[index-18]) > > print(poles) > > > index +=1 > > > except(IndexError): pass > > > finally: > > if fh is not None: # close file > > fh.close() > > > -- > > > Which half works. If it's not found, IndexError is caught and passed > > (avoids quitting on lines[index out of range]. The print(poles) > > properly displays the value I am looking for (_always_ 18 lines before > > the search object). > > > However, since it is assigned using the index variable, the value of > > poles doesn't keep (poles is always zero when referenced outside of > > the read_poles function). I'm assuming because I'm pointing to a > > certain position of an object and once index moves on, it no longer > > points to anything valid. My python book suggested using > > copy.deepcopy, but that didn't get around the fact I am calling it on > > (index-18). > > > Any experience jumping back (or forward) a set number of lines once a > > search object is found? This is the only way I can think of doing it > > and it clearly has some problems. > > > Reading the file line by line using for line in blah works for finding > > the search object, but I can't see a way of going back the 18 lines to > > grabbing what I need. > > > Thanks for the help! I'm slowly getting this mangled mess of a file > > into something automated (hand investigating the several thousand > > files I need to do would be unpleasant). > > # You could try using a deque holding 18 lines and search using that > deque > # This is untested, but here's a try (>=Python 3.0) > from collections import deque > import itertools as it > import sys > > def read_poles(filename): > with open(filename) as f: > line_iter = iter(f) > d = deque(it.islice(line_iter,17), maxlen=18) > > for line in line_iter: > d.append(line) > > if 'search object' in line: > poles = int(d[0]) > print(poles) > return poles > else: > print('No poles found in', filename, file=sys.err) Notice that I returned the "pole" from the function so you could catch the return value as follows: pole = read_poles(filename) if pole is None: # no poles found else: print('Function returned this pole:', pole) If you need a list of poles, then return a list: def read_poles(filename): all_poles = [] with open(filename) as f: line_iter = iter(f) d = deque(it.islice(line_iter,17), maxlen=18) for line in line_iter: d.append(line) if 'search object' in line: all_poles.append(int(d[0])) return all_poles ... poles = read_poles(filename) if poles: print('Here are the poles:\n', '\n'.join(map(str,poles))) else: print('There were no poles found in', filename) -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
MRAB wrote: > Steven D'Aprano wrote: >> On Wed, 01 Apr 2009 04:58:48 +0200, Lada Kugis wrote: >> >>> Why do we try to create languages that are intuitive to humans, then ? >> >> Because of the foolish hope that sufficiently easy syntax will make >> excellent programmers out of average people. >> >> Programming is not intuitive to humans. *Counting* isn't intuitive to >> humans -- children need to learn how to count. >> > [snip] > Research suggests that your wrong. For example, even baby chicks can > count: > > http://news.bbc.co.uk/1/hi/sci/tech/7975260.stm i saw that earlier today. it's really pushing the definition of "count", at least as described there. there have been similar experiments where they address whether the animal is actually looking at "how big" the total "pile" is rather than counting (do they know the difference between two small things and one big thing, for example). that experiment doesn't seem to address this. andrew -- http://mail.python.org/mailman/listinfo/python-list
Which is more Pythonic? (was: Detecting Binary content in files)
Dennis Lee Bieber presented a code snippet with two consecutive statements that made me think, "I'd code this differently". So just for fun ... is Dennis's original statement or my "_alt" statement more idiomatically Pythonic? Are there even more Pythonic alternative codings? mrkrs = [b for b in block if b > 127 or b in [ "\r", "\n", "\t" ] ] mrkrs_alt1 = filter(lambda b: b > 127 or b in [ "\r", "\n", "\t" ], block) mrkrs_alt2 = filter(lambda b: b > 127 or b in list("\r\n\t"), block) (Note: Dennis's statement converts a string into a list; mine does not.) --- binary = (float(len(mrkrs)) / len(block)) > 0.30 binary_alt = 1.0 * len(mrkrs) / len(block) > 0.30 -John E-mail message checked by Spyware Doctor (6.0.0.386) Database version: 5.12090 http://www.pctools.com/en/spyware-doctor-antivirus/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Stripping non-numbers from a file parse without nested lists?
On Apr 1, 2:35 am, daku9...@gmail.com wrote: > On Mar 31, 6:47 pm, "Rhodri James" > wrote: > > > What you're doing (pace error checking) seems fine for the data > > structures that you're using. I'm not entirely clear what your usage > > pattern for "dip" and "dir" is once you've got them, so I can't say > > whether there's a more appropriate shape for them. I am a bit curious > > though as to why a nested list is non-ideal? > > > ... > > if "/" in word and "dip" not in word: > > dip_n_dir.append(word.split("/", 1)) > > > is marginally shorter, and has the virtue of making it harder to use > > unrelated dip and dir values together. > > > -- > > Rhodri James *-* Wildebeeste Herder to the Masses > > Rhodri, > > Thanks. That works better than what I had before and I learned a new > method of parsing what I was looking for. > > Now I'm on to jumping a set number of lines from a given positive > search match: > > ...(lines of garbage)... > 5656 (or some other value I want, but don't explicitly know) > ...(18 lines of garbage)... > search object > ...(lines of garbage)... > > I've tried: > > def read_poles(filename): > index = 0 > fh = None > try: > fh = open(filename, "r") > lines=fh.readlines() > while True: > > if "search object" in lines[index] > poles = int(lines[index-18]) > print(poles) > > index +=1 > > except(IndexError): pass > > finally: > if fh is not None: # close file > fh.close() > > -- > > Which half works. If it's not found, IndexError is caught and passed > (avoids quitting on lines[index out of range]. The print(poles) > properly displays the value I am looking for (_always_ 18 lines before > the search object). > > However, since it is assigned using the index variable, the value of > poles doesn't keep (poles is always zero when referenced outside of > the read_poles function). I'm assuming because I'm pointing to a > certain position of an object and once index moves on, it no longer > points to anything valid. My python book suggested using > copy.deepcopy, but that didn't get around the fact I am calling it on > (index-18). > > Any experience jumping back (or forward) a set number of lines once a > search object is found? This is the only way I can think of doing it > and it clearly has some problems. > > Reading the file line by line using for line in blah works for finding > the search object, but I can't see a way of going back the 18 lines to > grabbing what I need. > > Thanks for the help! I'm slowly getting this mangled mess of a file > into something automated (hand investigating the several thousand > files I need to do would be unpleasant). # You could try using a deque holding 18 lines and search using that deque # This is untested, but here's a try (>=Python 3.0) from collections import deque import itertools as it import sys def read_poles(filename): with open(filename) as f: line_iter = iter(f) d = deque(it.islice(line_iter,17), maxlen=18) for line in line_iter: d.append(line) if 'search object' in line: poles = int(d[0]) print(poles) return poles else: print('No poles found in', filename, file=sys.err) -- http://mail.python.org/mailman/listinfo/python-list
Re: List of paths
Nico Grubert wrote: >> May be not so much pythonic, but works >> >> for i in range(len(q)): >> for x in q[i:]: >>if x.startswith(q[i]) and x!=q[i]: >>q.remove(x) > > ...but works fine. Thanks, Eugene. > Also thanks to Andrew. Your example works fine, too. Thanks to remind me > of the 'yield' statement! ;-) in case it's not clear, the method above is O(n^2) while mine was O(n). that will not matter for small lists, but for long ones mine will be much faster. andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: Regex trouble
more exactly, my guess is perl has a special case for this that avoids doing a search over all possible matchers via the pushdown stack. andrew cooke wrote: > > ".*?" is a "not greedy" match, which is significantly more difficult to > handle than a normal ".*". so the performance will depend on quite > complex details of how the regular expression engine is implemented. it > wouldn't surprise me if perl was better here, because it comes from a > background with a much stronger emphasis on regular expressions. > > i know that not an exact answer, but unless you find the author of the re > library i am not sure you will get a much better explanation. it comes > down to whether the regular expression can be implemented using a > deterministic finite automaton (rather than an indeterministic one). if > you look at the table at the bottom of > http://en.wikipedia.org/wiki/Finite_state_machine then i believe (i am not > 100% sure) that the ".*?" match requires at least a pushdown automota, > while ".*" can be handled with a simple finite automaton. > > disclaimer: this is all fairly new to me as i just recently implemented a > regular expression matcher myself, and i may be wrong on some of the > details. > > andrew > > > akshat agarwal wrote: >> Hi, >> >> I am trying to use the following snippet of code to print a regex match. >> >> s = '01234567890123456789x012' >> >> pat = r'(.*?x|[^a]+)*y' >> >> mo = re.search(pat, s) >> if mo is not None: >> print mo.group(0) >> >> By adding one character before the 'x' in the input string, the time >> taken >> to print the match doubles. This behaviour is not observed in perl. I am >> curious to know about the difference the in regex implementations of >> perl >> and python which causes this. >> >> Thanks >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Regex trouble
".*?" is a "not greedy" match, which is significantly more difficult to handle than a normal ".*". so the performance will depend on quite complex details of how the regular expression engine is implemented. it wouldn't surprise me if perl was better here, because it comes from a background with a much stronger emphasis on regular expressions. i know that not an exact answer, but unless you find the author of the re library i am not sure you will get a much better explanation. it comes down to whether the regular expression can be implemented using a deterministic finite automaton (rather than an indeterministic one). if you look at the table at the bottom of http://en.wikipedia.org/wiki/Finite_state_machine then i believe (i am not 100% sure) that the ".*?" match requires at least a pushdown automota, while ".*" can be handled with a simple finite automaton. disclaimer: this is all fairly new to me as i just recently implemented a regular expression matcher myself, and i may be wrong on some of the details. andrew akshat agarwal wrote: > Hi, > > I am trying to use the following snippet of code to print a regex match. > > s = '01234567890123456789x012' > > pat = r'(.*?x|[^a]+)*y' > > mo = re.search(pat, s) > if mo is not None: > print mo.group(0) > > By adding one character before the 'x' in the input string, the time taken > to print the match doubles. This behaviour is not observed in perl. I am > curious to know about the difference the in regex implementations of perl > and python which causes this. > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: The spam to content ratio of this group
On 2009-04-01, Eric wrote: > is getting very high. Why aren't captcha's used to prevent all of this > noise? 1) Captcha's don't work. 2) The NNTP protocol doesn't support Captcha's 3) Simply ignoring all posts made from Google Groups works quite well. -- Grant Edwards grante Yow! Did YOU find a at DIGITAL WATCH in YOUR box visi.comof VELVEETA? -- http://mail.python.org/mailman/listinfo/python-list
The spam to content ratio of this group
is getting very high. Why aren't captcha's used to prevent all of this noise? -- http://mail.python.org/mailman/listinfo/python-list