Re: list comprehension question

2009-04-30 Thread Michael Spencer
Ross wrote: If I have a list of tuples a = [(1,2), (3,4), (5,6)], and I want to return a new list of each individual element in these tuples, I can do it with a nested for loop but when I try to do it using the list comprehension b = [j for j in i for i in a], my output is b = [5,5,5,6,6,6] inste

Re: efficiently checking for string.maketrans conflicts?

2009-04-22 Thread Michael Spencer
Saketh wrote: Thank you, Peter and Michael, for your solutions! I think that Michael's is what I was edging towards, but Peter's has demonstrated to me how efficient Python's set functions are. I have a lot more to learn about optimizing algorithms in Python... :) -- http://mail.python.org/mail

Re: generating random tuples in python

2009-04-22 Thread Michael Spencer
Robert Kern wrote: On 2009-04-20 23:04, per wrote: to be more formal by very different, i would be happy if they were maximally distant in ordinary euclidean space... so if you just plot the 3-tuples on x, y, z i want them to all be very different from each other. i realize this is obviously b

Re: efficiently checking for string.maketrans conflicts?

2009-04-20 Thread Michael Spencer
Saketh wrote: Hi everyone: I'm using "translation" in the sense of string.maketrans here. I am trying to efficiently compare if two string translations "conflict" -- that is, either they differently translate the same letter, or they translate two different letters to the same one. ... Anoth

Re: get rid of duplicate elements in list without set

2009-03-20 Thread Michael Spencer
Alexzive wrote: Hello there, I'd like to get the same result of set() but getting an indexable object. How to get this in an efficient way? Example using set A = [1, 2, 2 ,2 , 3 ,4] B= set(A) B = ([1, 2, 3, 4]) B[2] TypeError: unindexable object Many thanks, alex -- http://mail.python.org/m

Re: having a function called after the constructor/__init__ is done

2009-03-16 Thread Michael Spencer
thomas.han...@gmail.com wrote: ... So any ideas on how to get a function called on an object just after __init__ is done executing? -- http://mail.python.org/mailman/listinfo/python-list Yes, you *can* use metaclasses - you need to override the type.__call__ method, which is what normally ca

Re: sort functions in python

2008-02-08 Thread Michael Spencer
t3chn0n3rd wrote: > Do you think it is relatively easy to write sort algorithms such as > the common Bubble sort in Python as compared to other high level > programming langauges yes -- http://mail.python.org/mailman/listinfo/python-list

Re: which one is more efficient

2008-02-08 Thread Michael Spencer
ki lo wrote: > I have type variable which may have been set to 'D' or 'E' > > Now, which one of following statements are more efficient > > if type =='D' or type == 'E': > > or > > if re.search("D|E", type): > > Please let me know because the function is going to called 10s of > millions of t

Re: Why does list have no 'get' method?

2008-02-07 Thread Michael Spencer
Wildemar Wildenburger wrote: > Arnaud Delobelle wrote: >> Personally, between >> >> * foo if foo else bar >> * foo or bar >> >> I prefer the second. Maybe it could be spelt >> >> * foo else bar ? >> > How about > > val = foo rather than bar > > If that is not clear and obvios, I don't know what i

Re: 5 queens

2007-12-22 Thread Michael Spencer
cf29 wrote: > Greetings, > > I designed in JavaScript a small program on my website called 5 > queens. .. Has anyone tried to do a such script? If anyone is > interested to help I can show what I've done so far. Tim Peters has a solution to 8 queens in test_generators in the standard library

Re: Problem with generator expression and class definition

2007-12-07 Thread Michael Spencer
Terry Reedy wrote: > "Maric Michaud" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > |I faced a strange behavior with generator expression, which seems like a > bug, for both > | python 2.4 and 2.5 : > > Including the latest release (2.5.2)? > > | >>> class A : > | ... a = 1

Re: How does python build its AST

2007-12-07 Thread Michael Spencer
MonkeeSage wrote: > A quick question about how python parses a file into compiled > bytecode. Does it parse the whole file into AST first and then compile > the AST, or does it build and compile the AST on the fly as it reads > expressions? (If the former case, why can't functions be called before

Re: Why Python 3?

2007-12-05 Thread Michael Spencer
Kay Schluehr wrote: > > This unexpected attack in his rear frightened him so much, that he > leaped forward with all his might: the horse's carcase dropped on the > ground, but in his place the wolf was in the harness, and I on my part > whipping him continually: we both arrived in full career saf

Re: converting to and from octal escaped UTF--8

2007-12-02 Thread Michael Spencer
Michael Goerz wrote: > Hi, > > I am writing unicode stings into a special text file that requires to > have non-ascii characters as as octal-escaped UTF-8 codes. > > For example, the letter "Í" (latin capital I with acute, code point 205) > would come out as "\303\215". > > I will also have to r

Re: Interfaces to high-volume discussion forums

2007-12-01 Thread Michael Spencer
Dennis Lee Bieber wrote: > On Fri, 30 Nov 2007 11:36:44 -0800, Michael Spencer >> >> Can anyone recommend a solution that also synchronizes post read status? If >> Google Reader or something like it handled NNTP, I imagine I'd use it to >> achieve >>

Re: Interfaces to high-volume discussion forums

2007-11-30 Thread Michael Spencer
Ben Finney wrote: > > I'm not interested in learning some centralised web-application > interface, and far prefer the discussion forum to be available by a > standard *protocol*, that I can use my choice of *local client* > application with. > I agree: I use Thunderbird, and it works well. But

Re: Convert obejct string repr to actual object

2007-10-08 Thread Michael Spencer
Tor Erik Sønvisen wrote: > Hi, > > I've tried locating some code that can recreate an object from it's > string representation... > The object in question is really a dictionary containing other > dictionaries, lists, unicode strings, floats, ints, None, and > booleans. > > I don't want to use ev

Re: Dynamically creating class properties

2007-10-04 Thread Michael Spencer
Karlo Lozovina wrote: > > Any idea how to do that with metaclasses and arbitrary long list of > attributes? I just started working with them, and it's driving me nuts :). > > Thanks for the help, > best regards. > Try implementing a property factory function before worrying about the metaclas

Re: module confusion

2007-10-03 Thread Michael Spencer
+1 Subject line of the week (SLOTW) rjcarr wrote: > So my question is ... why are they [os.path and logging.handlers] different? [A] wrote: > Because you misspelled it. First, do a dir() on logging: [B] wrote: > No, he didn't... OP: logging is a package and logging.handlers is one module > in t

Re: I could use some help making this Python code run faster using only Python code.

2007-09-20 Thread Michael Spencer
Python Maniac wrote: > I am new to Python however I would like some feedback from those who > know more about Python than I do at this time. > > def scrambleLine(line): > s = '' > for c in line: > s += chr(ord(c) | 0x80) > return s > > def descrambleLine(line): > s = '' >

Re: subclass of integers

2007-09-14 Thread Michael Spencer
Mark Morss wrote: > I would like to construct a class that includes both the integers and > None. I desire that if x and y are elements of this class, and both > are integers, then arithmetic operations between them, such as x+y, > return the same result as integer addition. However if either x o

Re: Problem with filter()

2007-04-03 Thread Michael Spencer
Boudreau, Emile wrote: > Hey all, > So I'm trying to filter a list with the built-in function > filter(). My list looks something like this: > ['logs', 'rqp-8.2.104.0.dep', 'rqp-8.2.93.0.dep', > 'rqp-win32-app-8.2.96.0-inst.tar.gz', 'rqp-win32-app-8.2.96.0-inst.tar.gz'] > > Calling filte

Re: manually implementing staticmethod()?

2007-03-28 Thread Michael Spencer
"7stud" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hi, > > Can someone show me how to manually implement staticmethod()? Here is > my latest attempt: > Raymond Hettinger can: http://users.rcn.com/python/download/Descriptor.htm#static-methods-and-class-methods

Re: challenge ?

2007-03-22 Thread Michael Spencer
alain wrote: > I have a problem I wonder if it has been solved before. > I have a dictionnary and I want the values in the dictionnary to be > annotated with the rank that would be obtained by sorting the values > > def annotate_with_rank(my_dict): > > return my_annotated_dict >

Re: To count number of quadruplets with sum = 0

2007-03-15 Thread Michael Spencer
n00m wrote: > http://www.spoj.pl/problems/SUMFOUR/ > > 3 > 0 0 0 0 > 0 0 0 0 > -1 -1 1 1 > Answer for this input data is 33. > > My solution for the problem is > == > > import time > t = time.clock() > > q,w,e,r,sch,h = [],[],[

Re: Signed zeros: is this a bug?

2007-03-11 Thread Michael Spencer
Gabriel Genellina wrote: > > (I cannot find peephole.c on the source distribution for Python 2.5, but > you menctioned it on a previous message, and the comment above refers to > the peephole optimizer... where is it?) > The peephole optimizer is in compile.c - the entry point is optimize_c

Re: Flatten a two-level list --> one liner?

2007-03-07 Thread Michael Spencer
Sergio Correia wrote: > spam = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] > > Into something like > eggs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] > > There are *no* special cases (no empty sub-lists). eggs = [i for j in spam for i in j] Michael -- http://mail.python.org/mailman/listinfo/

Re: Python Source Code Beautifier

2007-02-27 Thread Michael Spencer
Franz Steinhaeusler wrote: > Use Spaces, size: 4 > detect mixed line ending > detect tabs mixed with space > trim trailing whitespaces. look at: tools/scripts/reindent.py > convert structs like: if (a > b): to if a > b: > fill in spaces, but not in functions between operators: > > a+=1 =>

Re: Overloading assignment operator

2007-01-29 Thread Michael Spencer
J. Clifford Dyer wrote: > I think that's the first time I've actually seen someone use a Monty > Python theme for a python example, and I must say, I like it. However, > "We are all out of Wensleydale." > > Cheers, > Cliff Oh, then you clearly don't waste nearly enough time on this newsgroup ;

Re: python poetry?

2006-12-19 Thread Michael Spencer
BartlebyScrivener wrote: > Python pseudo code limericks anywhere? I wrote the following in response to Steve Holden's limerick challenge a couple of years ago: # run me or voice the alphanumeric tokens from itertools import repeat for feet in [3,3,2,2,3]: print " ".join("DA-DA-DUM"

Re: Iterating over several lists at once

2006-12-13 Thread Michael Spencer
John Henry wrote: > Carl Banks wrote: > >> The function can be extended to allow arbitrary arguments. Here's a >> non-minmal recursive version. >> >> def cartesian_product(*args): >> if len(args) > 1: >> for item in args[0]: >> for rest in cartesian_product(*args[1:]): >>

Re: Defining classes

2006-12-13 Thread Michael Spencer
Nick Maclaren wrote: > > Well, I am already doing that, and regretting the fact that Python > doesn't seem to allow a class instantiation to return a new class :-) > >>> class Fake(object): ... def __new__(cls): ... return 42 ... >>> Fake() 42 >>> "instantiation" (i.e.

Re: Slicing / subsetting list in arbitrary fashion

2006-11-17 Thread Michael Spencer
Gregg Lind wrote: > I wish something like this was part of the standard python installation, > and didn't require one to use Numpy or Numarray. This sort of list > subsetting is useful in many, many contexts. > Many of numpy's multi-dimensional slicing and indexing operations are implemented

Re: How to identify generator/iterator objects?

2006-10-25 Thread Michael Spencer
Kenneth McDonald wrote: > I'm trying to write a 'flatten' generator which, when give a > generator/iterator that can yield iterators, generators, and other data > types, will 'flatten' everything so that it in turns yields stuff by > simply yielding the instances of other types, and recursively

Re: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees

2006-10-24 Thread Michael Spencer
Martin v. Löwis wrote: > Georg Brandl schrieb: >> Perhaps you can bring up a discussion on python-dev about your improvements >> and how they could be integrated into the standard library... > > Let me second this. The compiler package is largely unmaintained and > was known to be broken (and perh

Re: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees

2006-10-24 Thread Michael Spencer
Paul Boddie wrote: > Martin v. Löwis wrote: ...The compiler package is largely unmaintained and >> was known to be broken (and perhaps still is). > > I don't agree entirely with the "broken" assessment. Although I'm not > chasing the latest language constructs, the AST construction part of > the p

Re: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees

2006-10-23 Thread Michael Spencer
Georg Brandl wrote: > Michael Spencer wrote: >> Announcing: compiler2 >> - >> >> For all you bytecode enthusiasts: 'compiler2' is an alternative to the >> standard >> library 'compiler' package, with several adva

ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees

2006-10-19 Thread Michael Spencer
Announcing: compiler2 - For all you bytecode enthusiasts: 'compiler2' is an alternative to the standard library 'compiler' package, with several advantages. Improved pure-python compiler - Produces identical bytecode* to the built-in compile function for all /Lib and L

Re: Refactor a buffered class...

2006-09-07 Thread Michael Spencer
George Sakkis wrote: > Michael Spencer wrote: >> George Sakkis wrote: >>> Michael Spencer wrote: >>> >>>> def chunker(s, chunk_size=3, sentry=".", keep_first = False, keep_last = >>>> False): >>>> buffer=[] >

Re: Refactor a buffered class...

2006-09-06 Thread Michael Spencer
George Sakkis wrote: > Michael Spencer wrote: > >> Here's a small update to the generator that allows optional handling of the >> head >> and the tail: >> >> def chunker(s, chunk_size=3, sentry=".", keep_first = False, keep_last = >>

Re: Refactor a buffered class...

2006-09-06 Thread Michael Spencer
[EMAIL PROTECTED] wrote: > actually for the example i have used only one sentry condition by they > are more numerous and complex, also i need to work on a huge amount on > data (each word are a line with many features readed from a file) An open (text) file is a line-based iterator that can be fed

Re: Refactor a buffered class...

2006-09-06 Thread Michael Spencer
[EMAIL PROTECTED] wrote: > Hello, > > i'm looking for this behaviour and i write a piece of code which works, > but it looks odd to me. can someone help me to refactor it ? > > i would like to walk across a list of items by series of N (N=3 below) > of these. i had explicit mark of end of a seque

Re: replace deepest level of nested list

2006-09-05 Thread Michael Spencer
David Isaac wrote: > Thanks to both Roberto and George. > I had considered the recursive solution > but was worried about its efficiency. > I had not seen how to implement the numpy > solution, which looks pretty nice. > > Thanks! > Alan > > You could also use pyarray, which mimics numpy's index

Re: Optimizing Inner Loop Copy

2006-08-17 Thread Michael Spencer
Mark E. Fenner wrote: > Michael Spencer wrote: > >> Mark E. Fenner wrote: >> >>> and the copy is taking the majority (42%) of my execution time. >>> So, I'd like to speed up my copy. I had an explicit copy method that did >>> what was needed a

Re: Optimizing Inner Loop Copy

2006-08-17 Thread Michael Spencer
Mark E. Fenner wrote: > > and the copy is taking the majority (42%) of my execution time. > So, I'd like to speed up my copy. I had an explicit copy method that did > what was needed and returned a new object, but this was quite a bit slower > than using the standard lib copy.copy(). > How are

Re: Dispatch with multiple inheritance

2006-07-19 Thread Michael Spencer
Michael J. Fromberger wrote: ... > > Of course, I could just bypass super, and explicitly invoke them as: > > C.__init__(self, ...) > D.__init__(self, ...) > > ... but that seems to me to defeat the purpose of having super in the > first place. As others have pointed out, super, is designe

Re: Determining if an object is a class?

2006-07-13 Thread Michael Spencer
Michele Simionato wrote: > [EMAIL PROTECTED] wrote: >> I need to find out if an object is a class. >> Which is quite simply awful...does anyone know of a better way to do >> this? > > inspect.isclass > > M.S. > ...which made me wonder what this canonical test is. The answer: def isclass(o

Re: Getting external name of passed variable

2006-06-20 Thread Michael Spencer
David Hirschfield wrote: > I'm not sure this is possible, but it sure would help me if I could do it. > > Can a function learn the name of the variable that the caller used to > pass it a value? For example: > > def test(x): > print x > > val = 100 > test(val) > > Is it possible for function

Re: Running code on assignment/binding

2006-06-20 Thread Michael Spencer
David Hirschfield wrote: > Another deep python question...is it possible to have code run whenever > a particular object is assigned to a variable (bound to a variable)? > > So, for example, I want the string "assignment made" to print out > whenever my class "Test" is assigned to a variable: >

Re: Creating instances of untrusted new-style classes

2006-05-25 Thread Michael Spencer
Devan L wrote: > Is there any safe way to create an instance of an untrusted class > without consulting the class in any way? With old-style classes, I can > recreate an instance from another one without worrying about malicious > code (ignoring, for now, malicious code involving attribute access)

Re: How to add columns to python arrays

2006-05-17 Thread Michael Spencer
Terry Reedy wrote: > "Michael Spencer" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] >> If you're just looking for a multi-dimensional array type, and don't need >> maximum speed or the vast range of array-processing that numpy offers,

Re: How to add columns to python arrays

2006-05-17 Thread Michael Spencer
Terry Reedy wrote: > "CC" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] >> I wanna compile a 6000x1000 array with python. The array starts from >> 'empty', each time I get a 6000 length list, I wanna add it to the >> exist array as a column vector. Is there any function to do so? >

Re: Editing a function in-memory and in-place

2006-04-27 Thread Michael Spencer
Ian Bicking wrote: > I got a puzzler for y'all. I want to allow the editing of functions > in-place. I won't go into the reason (it's for HTConsole -- > http://blog.ianbicking.org/introducing-htconsole.html), except that I > really want to edit it all in-process and in-memory. So I want the > id

Re: Classic class conversion

2006-04-24 Thread Michael Spencer
Kay Schluehr wrote: > Just reasoning about conversion of classic to new style classes ( > keeping deprecation of ClCl in Py3K in mind ) I wonder if there is a > metaclass that can be used to express the semantics of ClCl in terms of > new style classes? Intuitively I would expect that there is quit

Re: Generate a sequence of random numbers that sum up to 1?

2006-04-21 Thread Michael Spencer
Anthony Liu wrote: > I am at my wit's end. > > I want to generate a certain number of random numbers. > This is easy, I can repeatedly do uniform(0, 1) for > example. > > But, I want the random numbers just generated sum up > to 1 . > > I am not sure how to do this. Any idea? Thanks. > > __

Re: String To Dict Problem

2006-04-21 Thread Michael Spencer
Clodoaldo Pinto wrote: > Michael Spencer wrote: > >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 > > Very nice work. It will be very useful. Thanks. > > Only a small problem when I try to evaluate this: > > safe_eval('True') > >

Re: How to create a dictionary from a string?

2006-04-21 Thread Michael Spencer
Clodoaldo Pinto wrote: > Is there a simple way to build a dictionary from a string without using > eval()? > s = '{"a":1}' d = eval(s) d > {'a': 1} > > Regards, Clodoaldo Pinto > Here is a discussion about one way to do it: http://tinyurl.com/o8mmm HTH Michael -- http://mail.p

Re: temporary scope change

2006-04-18 Thread Michael Spencer
Edward Elliott wrote: ... > > for x in list1: > i += 1 > # for y in list2: > print x * i > > and have the print line execute as part of the for x block. In other > words, I want the block with print to be in the scope of the for x loop. > But instead it raises a SyntaxError bec

Re: updated pre-PEP: The create statement

2006-04-10 Thread Michael Spencer
Steven Bethard wrote: > Azolex wrote: >> Steven Bethard wrote: >>> and named, nested hierarchies like XML documents could be created >>> like:: >>> >>> create ETobject html: >>> "This statement would generate an ElementTree object" >>> >>> create ETobject head: >>> "

Re: how to make a generator use the last yielded value when it regains control

2006-04-08 Thread Michael Spencer
John Salerno wrote: > Michael Spencer wrote: > >> itertools.groupby makes this very straightforward: > > I was considering this function, but then it seemed like it was only > used for determing consecutive numbers like 1, 2, 3 -- not consecutive > equivalent numbers l

Re: how to make a generator use the last yielded value when it regains control

2006-04-08 Thread Michael Spencer
John Salerno wrote: > Ben Cartwright wrote: > >> Definitely go for (1). The Morris sequence is a great candidate to >> implement as a generator. As a generator, it will be more flexible and >> efficient than (2). > > Actually I was just thinking about this and it seems like, at least for > my

Re: How to determine if a line of python code is a continuation of the line above it

2006-04-08 Thread Michael Spencer
Sandra-24 wrote: > No it's not an academic excercise, but your right, the situation is > more complex than I originally thought. I've got a minor bug in my > template code, but it'd cause more trouble to fix than to leave in for > the moment. > > Thanks for your input! > -Sandra > Take a look at

Re: Merging Objects

2006-04-03 Thread Michael Spencer
Cloudthunder wrote: > Sorry, I don't understand, how does this solve my problem? > __getattr__ and __setattr__ allow you to set up dynamic delegation e.g., class Foo(object): def __init__(self, **kw): self.__dict__.update(kw) def methFoo(self, x): return "Foo.methFoo(%

Re: wildcard exclusion in cartesian products

2006-03-26 Thread Michael Spencer
[EMAIL PROTECTED] wrote: > The python code below is adapted from a Haskell program written by > Tomasz > Wielonka on the comp.lang.functional group. It's more verbose than his > since I wanted to make sure I got it right. > > http://groups.google.com/group/comp.lang.functional/browse_frm/thread...

Re: String To Dict Problem

2006-03-26 Thread Michael Spencer
Kamilche wrote: > Thanks! It's interesting, and nearly what I want, but not quite there. > > When I run my sample code through it, I get a syntax error because it's > not a valid expression. If I were to put a 'dict(' in front and a ')' > at the end, THEN it nearly works - but it gives me an > 'Un

Re: String To Dict Problem

2006-03-26 Thread Michael Spencer
Kamilche wrote: > Hi everyone. I'm trying to convert a string that looks like this: > > gid = 'FPS', type = 'Label', pos = [0, 20], text = 'FPS', text2 = 'more > text without quotes', fmtline = "@VALUE @SIGNAL", signals = [('FPS', > None), ('FPS2', 'something')] > > to a dict that looks like this

Re: Help: Creating condensed expressions

2006-03-24 Thread Michael Spencer
[EMAIL PROTECTED] wrote: > Nevermind, I didn't understand the problem/question... Sorry. > > Bye, > bearophile > Really? Your solution looks fine to me. In any case, here's an alternative approach to the (based on the same understanding of the problem as bearophile's, but with the additional

Re: overlapping sets

2006-03-24 Thread Michael Spencer
kpp9c wrote: > I have a question... and ... whew ... i am gonna be honest, i haven't > the slightest clue how to even start ... i am not sure if i used up all > my good will here or can take a mulligan.. i love to try to at least > post some lame broken code of my own at first... but like i said, n

Re: Per instance descriptors ?

2006-03-22 Thread Michael Spencer
Bruno Desthuilliers wrote: > Michael Spencer a écrit : >> I may be missing the subtlety of what you're up to, but why is >> overriding __getattribute__ more desirable than simply defining the >> descriptor in a subclass? > > The code snippet I gave as an exa

Re: Wrap a dictionary in a class?

2006-03-22 Thread Michael Spencer
Joseph Turian wrote: > In another thread, it was recommended that I wrap a dictionary in a > class. > How do I do so? > >Joseph > > that thread: > http://groups.google.com/group/comp.lang.python/browse_frm/thread/9a0fbdca450469a1/b18455aa8dbceb8a?q=turian&rnum=1#b18455aa8dbceb8a > Perhaps li

Re: Per instance descriptors ?

2006-03-22 Thread Michael Spencer
bruno at modulix wrote: > Ziga Seilnacht wrote: >> bruno at modulix wrote: >> >>> Hi >>> >>> I'm currently playing with some (possibly weird...) code, and I'd have a >>> use for per-instance descriptors, ie (dummy code): >> >> >> >>> Now the question: is there any obvious (or non-obvious) drawback

Re: String comparison question

2006-03-20 Thread Michael Spencer
Fredrik Lundh wrote: > " hello world ".split() > ['hello', 'world'] a.split() == b.split() is a convenient test, provided you want to normalize whitespace rather than ignore it. I took the OP's requirements to mean that 'A B' == 'AB', but this is just a guess. Michael -- http://mail.

Re: user-supplied locals dict for function execution?

2006-03-20 Thread Michael Spencer
Lonnie Princehouse wrote: >> What's your use case exactly ? > > I'm trying to use a function to implicitly update a dictionary. The > whole point is to avoid the normal dictionary semantics, so kw['x'] = 5 > unfortunately won't do. > > I think bytecode hacks may be the way to go > I once messed

Re: String comparison question

2006-03-19 Thread Michael Spencer
Alex Martelli wrote: > Michael Spencer <[EMAIL PROTECTED]> wrote: >> >> Here, str.translate deletes the characters in its optional second argument. >> Note that this does not work with unicode strings. > > With unicode, you could do something strictly equ

Re: String comparison question

2006-03-19 Thread Michael Spencer
Olivier Langlois wrote: > Hi Michael! > > Your suggestion is fantastic and is doing exactly what I was looking > for! Thank you very much. > There is something that I'm wondering though. Why is the solution you > proposed wouldn't work with Unicode strings? > Simply, that str.translate with two a

Re: Is there such an idiom?

2006-03-19 Thread Michael Spencer
Per wrote: > Thanks Ron, > surely set is the simplest way to understand the question, to see > whether there is a non-empty intersection. But I did the following > thing in a silly way, still not sure whether it is going to be linear > time. > def foo(): > l = [...] > s = [...] > dic =

Re: String comparison question

2006-03-19 Thread Michael Spencer
Olivier Langlois wrote: > I would like to make a string comparison that would return true without > regards of the number of spaces and new lines chars between the words > > like 'A B\nC' = 'A\nBC' > import string NULL = string.maketrans("","") WHITE = string.whitespace def compare(a,b)

Re: Large algorithm issue -- 5x5 grid, need to fit 5 queens plus some squares

2006-03-16 Thread Michael Spencer
Fredrik Lundh wrote: > [EMAIL PROTECTED] wrote: > >> The problem I'm trying to solve is. >> There is a 5x5 grid. >> You need to fit 5 queens on the board such that when placed there are >> three spots left that are not threatened by the queen. > > when you're done with your homework (?), you can

Re: Newbie Class/Counter question

2006-03-14 Thread Michael Spencer
ProvoWallis wrote: > > My document looks like this > > A. Title Text > 1. Title Text > 1. Title Text > 1. Title Text > B. Title Text > 1. Title Text > 1. Title Text > > but I want to change the numbering of the second level to sequential > numbers like 1, 2, 3, etc. so my output would look like

Re: Printable string for 'self'

2006-03-14 Thread Michael Spencer
Don Taylor wrote: > Is there a way to discover the original string form of the instance that > is represented by self in a method? > > For example, if I have: > > fred = C() > fred.meth(27) > > then I would like meth to be able to print something like: > > about to call meth(

Re: Dictionary project

2006-03-11 Thread Michael Spencer
> [EMAIL PROTECTED] wrote: ... >> I'm working on a project for school (it's not homework; just for fun). >> For it, I need to make a list of words, starting with 1 character in length, >> up to 15 or so. >> It would look like: >> >> A B C d E F G ... Z Aa Ab Ac Ad Ae Aaa Aab Aac ... >> If there is

Re: Dictionary project

2006-03-11 Thread Michael Spencer
[EMAIL PROTECTED] wrote: > Hi All, > First, I hope this post isn't against list rules; if so, I'll take note in > the future. > > I'm working on a project for school (it's not homework; just for fun). > For it, I need to make a list of words, starting with 1 character in length, > up to 15 or so.

Re: Best way to have a for-loop index?

2006-03-09 Thread Michael Spencer
[EMAIL PROTECTED] wrote: > I write a lot of code that looks like this: > > for myElement, elementIndex in zip( elementList, > range(len(elementList))): > print "myElement ", myElement, " at index: ",elementIndex > > > My question is, is there a better, cleaner, or easier way to get at the >

Re: reshape an array?

2006-03-08 Thread Michael Spencer
KraftDiner wrote: > I have a 2D array. Say it is 10x10 and I want a 1D Array of 100 > elements... > What is the syntax? > > oneD = reshape(twoD, (100,1)) > or > oneD = reshape(twoD, (1,100)) > > One I guess is the transpose of the other but both seem to be > arrays of arrays... > > help?! > Us

Re: reshape a list?

2006-03-06 Thread Michael Spencer
Robert Kern wrote: > KraftDiner wrote: >> I have a list that starts out as a two dimensional list >> I convert it to a 1D list by: >> >> b = sum(a, []) >> >> any idea how I can take be and convert it back to a 2D list? > > Alternatively, you could use real multidimensional arrays instead of fakin

Re: Separating elements from a list according to preceding element

2006-03-05 Thread Michael Spencer
Rob Cowie wrote: > I'm having a bit of trouble with this so any help would be gratefully > recieved... > > After splitting up a url I have a string of the form > 'tag1+tag2+tag3-tag4', or '-tag1-tag2' etc. The first tag will only be > preceeded by an operator if it is a '-', if it is preceded by n

Re: two generators working in tandem

2006-02-11 Thread Michael Spencer
john peter wrote: > I'd like to write two generators: one is a min to max sequence number > generator that > rolls over to min again once the max is reached. the other is a generator > that cycles > through N (say, 12) labels. currently, i'm using these generators in nested > loops like >

Re: random playing soundfiles according to rating.

2006-02-08 Thread Michael Spencer
[EMAIL PROTECTED] wrote: ... > > But i am stuck on how to do a random chooser that works according to my > idea of choosing according to rating system. It seems to me to be a bit > different that just choosing a weighted choice like so: > ... > > And i am not sure i want to have to go through w

Re: Pulling all n-sized combinations from a list

2006-02-08 Thread Michael Spencer
Swroteb wrote: > Paul Rubin wrote: >> I think the natural approach is to make a generator that yields a >> 5-tuple for each combination, and then have your application iterate >> over that generator. Here's my version: >> >> def comb(x,n): >> """Generate combinations of n items from li

Re: A __getattr__ for class methods?

2006-02-08 Thread Michael Spencer
Dylan Moreland wrote: > I'm trying to implement a bunch of class methods in an ORM object in > order to provide functionality similar to Rails' ActiveRecord. This > means that if I have an SQL table mapped to the class "Person" with > columns name, city, and email, I can have class methods such as:

Re: Global variables, Classes, inheritance

2006-02-03 Thread Michael Spencer
DaveM wrote: > Although I've programmed for fun - on and off - since the mid 70's, I'm > definitely an OO (and specifically Python) beginner. > > My first question is about global variables. Are they, as I'm starting to > suspect, a sin against God or just best avoided? Having got my current > ap

Re: Having Trouble with Scoping Rules

2006-01-30 Thread Michael Spencer
Charles Krug wrote: > List: > ... > # expensive Object Module > > _expensiveObject = None > def ExpensiveObject(): > > if not(_expensiveObject): > _expensiveObject = "A VERY Expensive object" > > return _expensiveObject > ... > I obviously missed some part of the scoping rules.

Re: Print dict in sorted order

2006-01-29 Thread Michael Spencer
Raymond Hettinger wrote: >> from itertools import count, izip >> >> def dict2str(d, preferred_order = ['gid', 'type', 'parent', 'name']): >> last = len(preferred_order) >> rank = dict(izip(preferred_order, count())) >> pairs = d.items() >> pairs.sort(key=lambda (k,v): rank.get(k, (l

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, there

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

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: 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 a

Re: flatten a level one list

2006-01-12 Thread Michael Spencer
uences and un-equal lengths, with only modest loss of speed: def interleave(*args, **kw): """Peter Otten flatten7 (generalized by Michael Spencer) Interleave any number of sequences, padding shorter sequences if kw pad is supplied""" dopad = "pa

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

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

  1   2   3   4   >