Re: pure python code to do modular-arithmetic unit conversions?

2005-01-21 Thread Michael Spencer
Dan Stromberg wrote: Is there already a pure python module that can do modular-arithmetic unit conversions, like converting a huge number of seconds into months, weeks... or a bandwidth measure into megabits/s or gigabits/s or megabytes/s or gigabytes/s, whatever's the most useful (ala df -h)?

Re: Reload Tricks

2005-01-21 Thread Michael Spencer
Kamilche wrote: I want my program to be able to reload its code dynamically. I have a large hierarchy of objects in memory. The inheritance hierarchy of these objects are scattered over several files. I find that after reloading the appropriate files, and overwriting the __class__ of object

Re: Reload Tricks

2005-01-22 Thread Michael Spencer
Kamilche wrote: I want my program to be able to reload its code dynamically. I have a large hierarchy of objects in memory. The inheritance hierarchy of these objects are scattered over several files. Michael Spencer wrote: An alternative approach (with some pros and cons) is to modify the class

Re: default value in a list

2005-01-22 Thread Michael Spencer
Alex Martelli wrote: [explanation and the following code:] a, b, c = it.islice( ... it.chain( ... line.split(':'), ... it.repeat(some_default), ... ), ... 3) ... ... def pad_with_default(N, iterable,

Re: What YAML engine do you use?

2005-01-22 Thread Michael Spencer
Paul Rubin wrote: YAML looks to me to be completely insane, even compared to Python lists. I think it would be great if the Python library exposed an interface for parsing constant list and dict expressions, e.g.: [1, 2, 'Joe Smith', 8237972883334L, # comment {'Favorite fruits':

Re: Classical FP problem in python : Hamming problem

2005-01-25 Thread Michael Spencer
Francis Girard wrote: The following implementation is even more speaking as it makes self-evident and almost mechanical how to translate algorithms that run after their tail from recursion to tee usage : Thanks, Francis and Jeff for raising a fascinating topic. I've enjoyed trying to get my

Re: Classical FP problem in python : Hamming problem

2005-01-25 Thread Michael Spencer
Nick Craig-Wood wrote: Steven Bethard [EMAIL PROTECTED] wrote: Nick Craig-Wood wrote: Thinking about this some more leads me to believe a general purpose imerge taking any number of arguments will look neater, eg def imerge(*generators): values = [ g.next() for g in generators ] while True:

Re: limited python virtual machine (WAS: Another scripting language implemented into Python itself?)

2005-01-25 Thread Michael Spencer
Steven Bethard wrote: I wish there was a way to, say, exec something with no builtins and with import disabled, so you would have to specify all the available bindings, e.g.: exec user_code in dict(ClassA=ClassA, ClassB=ClassB) but I suspect that even this wouldn't really solve

Re: limited python virtual machine (WAS: Another scripting language implemented into Python itself?)

2005-01-25 Thread Michael Spencer
Steven Bethard wrote: I wish there was a way to, say, exec something with no builtins and with import disabled, so you would have to specify all the available bindings, e.g.: exec user_code in dict(ClassA=ClassA, ClassB=ClassB) but I suspect that even this wouldn't really solve the

Re: limited python virtual machine (WAS: Another scripting language implemented into Python itself?)

2005-01-25 Thread Michael Spencer
Steven Bethard wrote: Michael Spencer wrote: Safe eval recipe posted to cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 This recipe only evaluates constant expressions: Description: Evaluate constant expressions, including list, dict and tuple using the abstract syntax

Re: limited python virtual machine (WAS: Another scripting language implemented into Python itself?)

2005-01-25 Thread Michael Spencer
Cameron Laird wrote: In article [EMAIL PROTECTED], Michael Spencer [EMAIL PROTECTED] wrote: . . . Right - the crux of the problem is how to identify dangerous objects. My point is that if such as test is possible, then safe

Re: python without OO

2005-01-25 Thread Michael Spencer
Davor wrote: Thanks, I do not hate OO - I just do not need it for the project size I'm dealing with - and the project will eventually become open-source and have additional developers - so I would prefer that we all stick to simple procedural stuff rather than having to deal with a developer that

Re: Classical FP problem in python : Hamming problem

2005-01-27 Thread Michael Spencer
Paul Rubin wrote: Francis Girard [EMAIL PROTECTED] writes: Thank you Nick and Steven for the idea of a more generic imerge. If you want to get fancy, the merge should use a priority queue (like in the heapsort algorithm) instead of a linear scan through the incoming iters, to find the next item

Re: remove duplicates from list *preserving order*

2005-02-03 Thread Michael Spencer
Steven Bethard wrote: I'm sorry, I assume this has been discussed somewhere already, but I found only a few hits in Google Groups... If you know where there's a good summary, please feel free to direct me there. I have a list[1] of objects from which I need to remove duplicates. I have to

Re: returning True, False or None

2005-02-04 Thread Michael Spencer
Steven Bethard wrote: I have lists containing values that are all either True, False or None, e.g.: [True, None, None, False] [None, False, False, None ] [False, True, True, True ] etc. For a given list: * If all values are None, the function should return None. * If at

Re: changing local namespace of a function

2005-02-04 Thread Michael Spencer
Bo Peng wrote: Dear list, I have many dictionaries with the same set of keys and I would like to write a function to calculate something based on these values. For example, I have a = {'x':1, 'y':2} b = {'x':3, 'y':3} def fun(dict): dict['z'] = dict['x'] + dict['y'] fun(a) and fun(b) will set

Re: changing local namespace of a function

2005-02-04 Thread Michael Spencer
Bo Peng wrote: Michael Spencer wrote: There are hundreds of items in the dictionary (that will be needed in the calculation) so passing the whole dictionary is a lot better than passing individual items. ... def fun(d): exec 'z = x + y' in globals(), d seems to be more readable than def fun

Re: returning True, False or None

2005-02-04 Thread Michael Spencer
Fahri Basegmez wrote: reduce(lambda x, y: x or y, lst) works but when I tried import operator reduce(operator.or_, lst) this did not work. It pukes Traceback (most recent call last): File interactive input, line 1, in ? TypeError: unsupported operand type(s) for |: 'NoneType' and 'bool' Any

Re: changing local namespace of a function

2005-02-04 Thread Michael Spencer
Nick Coghlan wrote: Michael Spencer wrote: def fun(dict): # set dict as local namespace # locals() = dict? z = x + y As you no doubt have discovered from the docs and this group, that isn't doable with CPython. Not entirely impossible: Py def f(d): ... exec locals().update(d

Re: returning True, False or None

2005-02-04 Thread Michael Spencer
Fahri Basegmez wrote: Michael Spencer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Fahri Basegmez wrote: reduce(lambda x, y: x or y, lst) works but when I tried import operator reduce(operator.or_, lst) this did not work. It pukes Traceback (most recent call last): File

Re: changing local namespace of a function

2005-02-05 Thread Michael Spencer
Alex Martelli wrote: Hmmm, you do realize that wrapdict uses a lot of indirection while my equivalent approach, just posted, is very direct, right? To reiterate the latter, and dress it up nicely too, it's class wrapwell(object): def __init__(self, somedict): self.__dict__ = somedict

Re: empty classes as c structs?

2005-02-05 Thread Michael Spencer
Alex Martelli wrote: Nick Coghlan [EMAIL PROTECTED] wrote: ... Michael Spencer also posted ... Wasted indirection, IMHO. A better implementation: class attr_view(object): def __init__(self, data): self.__dict__ = data Alex Indeed! A complete brain-blip Michael -- http

Re: empty classes as c structs?

2005-02-05 Thread Michael Spencer
Steven Bethard wrote: Nick Coghlan wrote: class attr_view(object): def __init__(self, data): self.__dict__ = data I think the idea definitely deserves mention as a possible implementation strategy in the generic objects PEP, with the data argument made optional: That's basically

Re: empty classes as c structs?

2005-02-06 Thread Michael Spencer
Alex Martelli wrote: Steven Bethard [EMAIL PROTECTED] wrote: Hmm... interesting. This isn't the main intended use of Bunch/Struct/whatever, but it does seem like a useful thing to have... I wonder if it would be worth having, say, a staticmethod of Bunch that produced such a view, e.g.: class

Re: empty classes as c structs?

2005-02-07 Thread Michael Spencer
Steven Bethard wrote: Do you mean there should be a separate Namespace and Bunch class? Or do you mean that an implementation with only a single method is less useful? The former. If the former, then you either have to repeat the methods __repr__, __eq__ and update for both Namespace and Bunch,

Re: turing machine in an LC

2005-02-08 Thread Michael Spencer
Jeremy Bowers wrote: That's not a generator expression, that's a generator function. Nobody contests they can reference earlier states, that's most of their point :-) Are you sure? I just wrote my examples in functions to label them Here's your example with this method: import itertools as it

Re: turing machine in an LC

2005-02-08 Thread Michael Spencer
Jeremy Bowers wrote: OK then, I still don't quite see how you can build a Turing Machine in one LC, but an LC and one preceding list assignment should be possible, although the resulting list from the LC is garbage; Not necessarily garbage - could be anything, say a copy of the results: results

A ListComp that maintains its own state (Was: Re: turing machine in an LC)

2005-02-08 Thread Michael Spencer
Jeremy Bowers [EMAIL PROTECTED] writes: On Tue, 08 Feb 2005 17:36:19 +0100, Bernhard Herzog wrote: Nick Vargish [EMAIL PROTECTED] writes: Xah Lee [EMAIL PROTECTED] writes: is it possible to write python code without any indentation? Not if Turing-completeness is something you desire. Bernhard

Re: A ListComp that maintains its own state (Was: Re: turing machine in an LC)

2005-02-08 Thread Michael Spencer
Carl Banks wrote: Pay attention, chief. I suggested this days ago to remove duplicates from a list. from itertools import * [ x for (x,s) in izip(iterable,repeat(set())) if (x not in s,s.add(x))[0] ] ;) Sorry, I gave up on that thread after the first 10 Million* posts. Who knows what other

Re: A ListComp that maintains its own state

2005-02-09 Thread Michael Spencer
Bernhard Herzog wrote: Michael Spencer [EMAIL PROTECTED] writes: So, here's factorial in one line: # state refers to list of state history - it is initialized to [1] # on any iteration, the previous state is in state[-1] # the expression also uses the trick of list.append() = None # to both

Re: Hack with os.walk()

2005-02-12 Thread Michael Spencer
Frans Englich wrote: Hello, Have a look at this recursive function: def walkDirectory( directory, element ): element = element.newChild( None, directory, None ) # automatically appends to parent element.setProp( name, os.path.basename(directory)) for root, dirs, files in os.walk(

Re: check if object is number

2005-02-12 Thread Michael Spencer
Steven Bethard wrote: Peter Hansen wrote: Of course, most of the other definitions of is a number that have been posted may likewise fail (defined as not doing what the OP would have wanted, in this case) with a numarray arange. Or maybe not. (Pretty much all of them will call an arange a

Re: check if object is number

2005-02-12 Thread Michael Spencer
Steven Bethard wrote: Michael Spencer wrote: Steven Bethard wrote: Peter Hansen wrote: Of course, most of the other definitions of is a number that have been posted may likewise fail (defined as not doing what the OP would have wanted, in this case) with a numarray arange. How about explicitly

Re: Hack with os.walk()

2005-02-12 Thread Michael Spencer
Tim Peters wrote: [Frans Englich] ... [snip] class HasPath: def __init__(self, path): self.path = path def __lt__(self, other): return self.path other.path class Directory(HasPath): def __init__(self, path): HasPath.__init__(self, path) self.files = []

Re: Iterator / Iteratable confusion

2005-02-13 Thread Michael Spencer
Francis Girard wrote: Example 8 Running after your tail with itertools.tee The beauty of it is that recursive running after their tail

Re: builtin functions for and and or?

2005-02-13 Thread Michael Spencer
Roose wrote: Yeah, as we can see there are a million ways to do it. But none of them are as desirable as just having a library function to do the same thing. I'd argue that since there are so many different ways, we should just collapse them into one: any() and all(). That is more in keeping

Re: Iterator / Iteratable confusion

2005-02-13 Thread Michael Spencer
Francis Girard [EMAIL PROTECTED] wrote in message an iterator doesn't have to support the __iter__ method Terry Reedy wrote: Yes it does. iter(iterator) is iterator is part of the iterater protocol for the very reason you noticed... But, notwithstanding the docs, it is not essential that

Re: builtin functions for and and or?

2005-02-13 Thread Michael Spencer
Roose wrote: Previous discussion on this topic: http://groups-beta.google.com/group/comp.lang.python/msg/a76b4c2caf6c435c Michael OK, well then. That's really the exact same thing, down to the names of the functions. So what ever happened to that? I don't recall: probably

Re: nested lists as arrays

2005-02-14 Thread Michael Spencer
naturalborncyborg wrote: Hi, I'm using nested lists as arrays and having some problems with that approach. In my puzzle class there is a swapelement method which doesn't work out. What doesn't work out? On casual inspection that method seems to work: p = Puzzle(2) p.elements[0][0] = 1

Re: nested lists as arrays

2005-02-14 Thread Michael Spencer
Terry Reedy wrote: [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] def setRandomState(self): # container for the elements to pick from container = [1,2,3,4,5,6,7,8,-1] # create elements of puzzle randomly i = 0 j = 0 while i = self.dim-1: while

Re: Iterator / Iteratable confusion

2005-02-15 Thread Michael Spencer
Michael Spencer wrote: But, notwithstanding the docs, it is not essential that iter(iterator) is iterator Terry Reedy wrote: iter(iterator) is iterator is part of the iterater protocol [...]I interpret [your post] as saying three things: 1. There is more than one possible definition of 'iterator

Re: Can __new__ prevent __init__ from being called?

2005-02-15 Thread Michael Spencer
Peter Hansen wrote: Felix Wiemann wrote: Sometimes (but not always) the __new__ method of one of my classes returns an *existing* instance of the class. However, when it does that, the __init__ method of the existing instance is called nonetheless, so that the instance is initialized a second

Re: renaming 'references' to functions can give recursive problems

2005-02-16 Thread Michael Spencer
peter wrote: Hello, nice solution: but it puzzles me :) can anyone tell me why ---correct solution def fA(input): return input def newFA(input, f= fA): return f(input) fA = newFA is correct and: -infinite loop- def fA(input): return input

Re: sampling items from a nested list

2005-02-16 Thread Michael Spencer
Steven Bethard wrote: So, I have a list of lists, where the items in each sublist are of basically the same form. It looks something like: ... Can anyone see a simpler way of doing this? Steve You just make these up to keep us amused, don't you? ;-) If you don't need to preserve the ordering,

Re: Iterator / Iteratable confusion

2005-02-16 Thread Michael Spencer
Terry Reedy wrote: Michael Spencer [EMAIL PROTECTED] wrote in message We are both interested in the murky edges at and beyond conventional usage. ... I am quite aware that multiple iterators for the same iterable (actual or conceptual) can be useful (cross products, for example). But I am

Re: Iterator / Iteratable confusion

2005-02-16 Thread Michael Spencer
Adam DePrince wrote: How is a spencerator [an iterator that doesn't return itself unmodified on iter] different than itertools.tee? Taking your question literally, it changes the behavior of an itertools.tee object 'tee', so that iter(tee) returns tee.__copy__(), rather than tee itself. It

Re: sampling items from a nested list

2005-02-16 Thread Michael Spencer
Michael Spencer wrote: def resample2(data): ... bag = {} ... random.shuffle(data) ... return [[(item, label) ... for item, label in group ... if bag.setdefault(label,[]).append(item) ... or len(bag[label]) 3

Re: check if object is number

2005-02-17 Thread Michael Spencer
Christos TZOTZIOY Georgiou wrote: On Sat, 12 Feb 2005 16:01:26 -0800, rumours say that Michael Spencer [EMAIL PROTECTED] might have written: Yup, that's basically what I'm doing right now. The question was really how to define that adapter function. =) Steve OK - then my entry

Re: Need advice on subclassing code

2005-11-15 Thread Michael Spencer
Kent Johnson wrote: Rusty Shackleford wrote: ... C_1_1 and C_1_2 share a common C ancestor, and in practice may be identical, but theoretically, could have the same function name with two different implementations underneath. ... How are you instantiating the correct class? You should be

Re: best cumulative sum

2005-11-22 Thread Michael Spencer
David Isaac wrote: for a solution when these are available. Something like: def cumreduce(func, seq, init = None): Return list of cumulative reductions. This can be written more concisely as a generator: import operator def ireduce(func, iterable, init): ... for i in

Re: Securing a future for anonymous functions in Python

2004-12-30 Thread Michael Spencer
topic /Idle speculation Michael Spencer -- http://mail.python.org/mailman/listinfo/python-list

args (was Re: Lambda as declarative idiom (was RE: what is lambda used for in real code?))

2005-01-04 Thread Michael Spencer
Roman Suzi wrote: Maybe this is too outlandish, but I see lambdas as a quote mechanism, which presents a possibility to postpone (precisely control, delegate) evaluation. That is, an ovehead for lambda must be much lower but at the same time visible to the programmer: d = a + (lambda x, y: x+

Re: aligning a set of word substrings to sentence

2005-12-01 Thread Michael Spencer
Steven Bethard wrote: I've got a list of word substrings (the tokens) which I need to align to a string of text (the sentence). The sentence is basically the concatenation of the token list, with spaces sometimes inserted beetween tokens. I need to determine the start and end offsets of

Re: Checking length of each argument - seems like I'm fighting Python

2005-12-03 Thread Michael Spencer
Brendan wrote: ... class Things(Object): def __init__(self, x, y, z): #assert that x, y, and z have the same length But I can't figure out a _simple_ way to check the arguments have the same length, since len(scalar) throws an exception. The only ways around this I've found

Re: Documentation suggestions

2005-12-06 Thread Michael Spencer
A.M. Kuchling wrote: Here are some thoughts on reorganizing Python's documentation, with one big suggestion. Thanks for raising this topic, and for your on-going efforts in this field. I use the compiled html help file provided by PythonWin, which includes all the core documentation. I

Re: i=2; lst=[i**=2 while i1000]

2005-12-06 Thread Michael Spencer
Daniel Schüle wrote: Hello NG, I am wondering if there were proposals or previous disscussions in this NG considering using 'while' in comprehension lists # pseudo code i=2 lst=[i**=2 while i1000] You are actually describing two features that list comps don't natively support -

Re: Documentation suggestions

2005-12-07 Thread Michael Spencer
A.M. Kuchling wrote: On Tue, 06 Dec 2005 10:29:33 -0800, Michael Spencer [EMAIL PROTECTED] wrote: not that helpful. Miscellaneous Services, in particular, gives no clue to treasures it contains. I would prefer, for example, to see the data structure modules: collections, heapq

Re: Bitching about the documentation...

2005-12-07 Thread Michael Spencer
Fredrik Lundh wrote: Rocco Moretti wrote: Insert punctuation capitalization to make the following a correct and coherent (if not a little tourtured). fred where guido had had had had had had had had had had had a better effect on the reader punctuation, including quote marks, I

Re: newby question: Splitting a string - separator

2005-12-08 Thread Michael Spencer
Thomas Liesner wrote: Hi all, i am having a textfile which contains a single string with names. I want to split this string into its records an put them into a list. In normal cases i would do something like: #!/usr/bin/python inp = open(file) data = inp.read() names = data.split()

Re: Dynamically add Class to Modules

2005-12-08 Thread Michael Spencer
[EMAIL PROTECTED] wrote: I'm trying to add a class to a module at runtime. I've seen examples of adding a method to a class, but I haven't been able to suit it to my needs. As part of a testsuite, I have a main process X that searches recursively for python test files. Those files

Re: Dynamically add Class to Modules

2005-12-08 Thread Michael Spencer
[EMAIL PROTECTED] wrote: ... exec testModule.TheTestCode %(testModule.TheTestName, testModule.TheTestName ) ... Try changing that to exec ~ in testModule.__dict__ otherwise, your class statement gets executed in the current scope Michael --

Re: getting host and path from url

2005-12-09 Thread Michael Spencer
Steve Young wrote: Hi, this is probably an easy question but is there a way to get the host and path seperatly out of an url? Example: url = http://news.yahoo.com/fc/world/iraq and i want some way of getting: host = http://news.yahoo.com and path =

Re: newby question: Splitting a string - separator

2005-12-09 Thread Michael Spencer
[EMAIL PROTECTED] wrote: Thomas Liesner wrote: Hi all, i am having a textfile which contains a single string with names. I want to split this string into its records an put them into a list. In normal cases i would do something like: #!/usr/bin/python inp = open(file) data = inp.read()

Re: Pattern matching with string and list

2005-12-12 Thread Michael Spencer
[EMAIL PROTECTED] wrote: Hi, I'd need to perform simple pattern matching within a string using a list of possible patterns. For example, I want to know if the substring starting at position n matches any of the string I have a list, as below: sentence = the color is $red patterns =

Re: newbie: generate a function based on an expression

2005-12-12 Thread Michael Spencer
Jacob Rael wrote: Hello, I would like write a function that I can pass an expression and a dictionary with values. The function would return a function that evaluates the expression on an input. For example: fun = genFun(A*x+off, {'A': 3.0, 'off': -0.5, 'Max': 2.0, 'Min': -2.0} )

Re: newbie: generate a function based on an expression

2005-12-13 Thread Michael Spencer
Bengt Richter wrote: On 12 Dec 2005 21:38:23 -0800, Jacob Rael [EMAIL PROTECTED] wrote: Hello, I would like write a function that I can pass an expression and a dictionary with values. The function would return a function that evaluates the expression on an input. For example: fun =

Re: Newbie needs help with regex strings

2005-12-14 Thread Michael Spencer
Dennis Benzinger wrote: Christopher Subich schrieb: Paul McGuire wrote: [...] For the example listed, pyparsing is even overkill; the OP should probably use the csv module. But the OP wants to parse lines with key=value pairs, not simply lines with comma separated values. Using the csv

Re: Newbie needs help with regex strings

2005-12-14 Thread Michael Spencer
Catalina Scott A Contr AFCA/EVEO wrote: I have a file with lines in the following format. pie=apple,quantity=1,cooked=yes,ingredients='sugar and cinnamon' Pie=peach,quantity=2,ingredients='peaches,powdered sugar' Pie=cherry,quantity=3,cooked=no,price=5,ingredients='cherries and sugar' I

Re: Parser or regex ?

2005-12-16 Thread Michael Spencer
Fuzzyman wrote: Hello all, I'm writing a module that takes user input as strings and (effectively) translates them to function calls with arguments and keyword arguments.to pass a list I use a sort of 'list constructor' - so the syntax looks a bit like : checkname(arg1, arg 2, 'arg

Re: Problem with exec

2005-12-16 Thread Michael Spencer
Peter Otten wrote: If you could provide a function with a different namespace when it's called, e. g f() in namespace would look up its globals in namespace, that might be an interesting concept but it's not how Python works. Peter It does seem like an interesting concept, so I

Re: object oriented programming question

2005-12-17 Thread Michael Spencer
Daniel Nogradi wrote: I have class 'x' with member 'content' and another member 'a' which is an instance of class '_a'. The class '_a' is callable and has a method 'func' which I would like to use to modify 'content' but I don't know how to address 'content' from the class '_a'. Is it

effbot ExeMaker: custom icon?

2005-12-17 Thread Michael Spencer
What is the recommended way to change the icon of the exe ExeMaker* produces? (I tried replacing the exemaker.ico file, and indeed removing it; but that had no effect.) Thanks Michael *http://effbot.org/zone/exemaker.htm -- http://mail.python.org/mailman/listinfo/python-list

Re: python coding contest

2005-12-30 Thread Michael Spencer
Tim Hochberg wrote: Shane Hathaway wrote: Andrew Durdin wrote: On 12/28/05, Shane Hathaway [EMAIL PROTECTED] wrote: I just found a 125 character solution. It's actually faster and more readable than the 133 character solution (though it's still obscure.) Having spent a good deal of time

Re: python coding contest

2006-01-01 Thread Michael Spencer
Claudio Grondi wrote: ...I analysed the outcome of it and have come to the conclusion, that there were two major factors which contributed to squeezing of code: (1). usage of available variants for coding of the same thing (2). sqeezing the size of used numeric and string literals

Re: inline function call

2006-01-05 Thread Michael Spencer
Bengt Richter wrote: ... This could be achieved by a custom import function that would capture the AST and e.g. recognize a declaration like __inline__ = foo, bar followed by defs of foo and bar, and extracting that from the AST and modifying the rest of the AST wherever foo and bar calls

Re: itertools.izip brokeness

2006-01-05 Thread Michael Spencer
Bengt Richter wrote: ... from itertools import repeat, chain, izip it = iter(lambda z=izip(chain([3,5,8],repeat(Bye)), chain([11,22],repeat(Bye))):z.next(), (Bye,Bye)) for t in it: print t ... (3, 11) (5, 22) (8, 'Bye') (Feel free to generalize ;-) [EMAIL PROTECTED]

Re: itertools.izip brokeness

2006-01-05 Thread Michael Spencer
Paul Rubin wrote: Michael Spencer [EMAIL PROTECTED] writes: for i in range(10): result = [] ... Do you mean while True: ...? oops, yes! so, this should have been: from itertools import repeat def izip2(*iterables, **kw): kw:fill. An element that will pad

Re: Regex help needed

2006-01-10 Thread Michael Spencer
rh0dium wrote: Hi all, I am using python to drive another tool using pexpect. The values which I get back I would like to automatically put into a list if there is more than one return value. They provide me a way to see that the data is in set by parenthesising it. ... CAN SOMEONE

Re: Regex help needed

2006-01-10 Thread Michael Spencer
rh0dium wrote: Michael Spencer wrote: def parse(source): ... source = source.splitlines() ... original, rest = source[0], \n.join(source[1:]) ... return original, rest_eval(get_tokens(rest)) This is a very clean and elegant way to separate them - Very nice!! I like

Re: How can I test if an argument is a sequence or a scalar?

2006-01-10 Thread Michael Spencer
Jean-Paul Calderone wrote: On 10 Jan 2006 15:18:22 -0800, [EMAIL PROTECTED] wrote: I want to be able to pass a sequence (tuple, or list) of objects to a function, or only one. ... but in case you're curious, the easiest way to tell an iterable from a non-iterable is by trying to iterate

Re: flatten a level one list

2006-01-11 Thread Michael Spencer
Robin Becker schrieb: Is there some smart/fast way to flatten a level one list using the latest iterator/generator idioms. ... David Murmann wrote: Some functions and timings ... Here are some more timings of David's functions, and a couple of additional contenders that time faster on

Re: flatten a level one list

2006-01-11 Thread Michael Spencer
Tim Hochberg wrote: Michael Spencer wrote: Robin Becker schrieb: Is there some smart/fast way to flatten a level one list using the latest iterator/generator idioms. ... David Murmann wrote: Some functions and timings ... Here's one more that's quite fast using Psyco, but only

Re: flatten a level one list

2006-01-12 Thread Michael Spencer
by Michael Spencer) Interleave any number of sequences, padding shorter sequences if kw pad is supplied dopad = pad in kw pad = dopad and kw[pad] count = len(args) lengths = map(len, args) maxlen = max(lengths) result = maxlen*count*[None] for ix, input

Re: How can I make a dictionary that marks itself when it's modified?

2006-01-12 Thread Michael Spencer
[EMAIL PROTECTED] wrote: It's important that I can read the contents of the dict without flagging it as modified, but I want it to set the flag the moment I add a new element or alter an existing one (the values in the dict are mutable), this is what makes it difficult. Because the values are

Re: flatten a level one list

2006-01-13 Thread Michael Spencer
Michael Spencer wrote: result[ix::count] = input + [pad]*(maxlen-lengths[ix]) Peter Otten rewrote: result[ix:len(input)*count:count] = input Quite so. What was I thinking? Michael -- http://mail.python.org/mailman/listinfo/python-list

Re: unusual exponential formatting puzzle

2005-09-21 Thread Michael Spencer
Neal Becker wrote: Like a puzzle? I need to interface python output to some strange old program. It wants to see numbers formatted as: e.g.: 0.23456789E01 That is, the leading digit is always 0, instead of the first significant digit. It is fixed width. I can almost get it with '%

Re: unusual exponential formatting puzzle

2005-09-21 Thread Michael Spencer
Michael Spencer wrote: Neal Becker wrote: Like a puzzle? I need to interface python output to some strange old program. It wants to see numbers formatted as: e.g.: 0.23456789E01 That is, the leading digit is always 0, instead of the first significant digit. It is fixed width. I can almost

Re: What is self?

2005-09-23 Thread Michael Spencer
Ron Adam wrote: Erik Max Francis wrote: Ron Adam wrote: When you call a method of an instance, Python translates it to... leader.set_name(leader, John) It actually translates it to Person.set_name(leader, John) I thought that I might have missed something there. Is there

Re: Wrapping classes

2005-09-23 Thread Michael Spencer
Jeremy Sanders wrote: Colin J. Williams wrote: Could you not have functions a and b each of which returns a NumArray instance? Your expression would then be something like a(..)+2*b(..). The user enters the expression (yes - I'm aware of the possible security issues), as it is a

Re: What is self?

2005-09-27 Thread Michael Spencer
Ron Adam wrote: What I've noticed is you can block the visibility of a class attribute, which include methods, by inserting an object in the instance with the same name. [snip example of this behavior] Yes, that's true for non-data descriptors (see last two bullets below) Raymond

Re: Silly function call lookup stuff?

2005-09-27 Thread Michael Spencer
Lucas Lemmens wrote: Dear pythonians, I've been reading/thinking about the famous function call speedup trick where you use a function in the local context to represent a remoter function to speed up the 'function lookup'. This is especially usefull in a loop where you call the function

Re: grouping array

2005-09-29 Thread Michael Spencer
[EMAIL PROTECTED] wrote: hi if I have an array say x = [[2,2,0,0,1,1], [1,1,0,0,1,1], [1,1,0,0,1,1]] I basically want to group regions that are non zero like I want to get the coordinates of non zero regions..as (x1,y1,x2,y2) [(0,0,2,1),(0,4,2,5)] which show the top

Re: grouping array

2005-09-30 Thread Michael Spencer
[EMAIL PROTECTED] wrote: fredrick's solutions seems to be more closer to what I was looking for.But I am still not sure if that could be done without the use of Image module. What do you mean by closer to what I was looking for? For the single test case you provided: say x =

Re: metaclass that inherits a class of that metaclass?

2005-06-01 Thread Michael Spencer
ironfroggy wrote: Hoping this isn't seeming too confusing, but I need to create a metaclass and a class using that metaclass, such that one of the bases of the metaclass is the class created with that metaclass. I can't figure out a way to do this, even after trying to add the class as a base

Re: Performance Issues please help

2005-06-02 Thread Michael Spencer
PyPK wrote: Yep that improved the speed by about 50% now it takes about 10 secs instead of 24 seconds..Thanks much. I guess that is the best we could do right.It would be really helpful if I could get it less than 5 seconds. Any suggestions on that?? Things to try: * in-lining the min and

Re: Performance Issues please help

2005-06-02 Thread Michael Spencer
Michael Spencer wrote: def search1(m): box = {} for r,row in enumerate(m): for c,e in enumerate(row): try: minc, minr, maxc, maxr = box[e] box[e] = ( c minc and c or minc, r minr and r or minr

Re: Read-only class properties

2005-07-10 Thread Michael Spencer
Bengt Richter wrote: ... class Foo(object): class __metaclass__(type): def __setattr__(cls, name, value): if type(cls.__dict__.get(name)).__name__ == 'Descriptor': raise AttributeError, 'setting Foo.%s to %r is not allowed' %(name, value)

Re: Match First Sequence in Regular Expression?

2006-01-26 Thread Michael Spencer
Roger L. Cauvin wrote: Fredrik Lundh [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Roger L. Cauvin wrote: $ python test.py gotexpected --- accept accept reject reject accept accept reject reject accept accept Thanks, but the second test case I listed

Re: generating method names 'dynamically'

2006-01-26 Thread Michael Spencer
Daniel Nogradi wrote: ... - database content --- Alice 25 Bob 24 - program1.py - class klass: ... inst = klass() - program2.py --- import program1 # The code in klass above should be such that the following # line should

Re: Using bytecode, not code objects

2006-01-29 Thread Michael Spencer
Fredrik Lundh wrote: Fabiano Sidler wrote: I'm looking for a way to compile python source to bytecode instead of code-objects. Is there a possibility to do that? The reason is: I want to store pure bytecode with no additional data. use marshal. The second question is, therefore: How

  1   2   3   4   >