Re: StopIteration in the if clause of a generator expression

2005-04-04 Thread Raymond Hettinger
> > Use a genexp when you need a generator > > and use a listcomp when you need a list. [Steven Bethard] > So do I read this right in preferring > [ for in ] > over > list( for in ) Yes! Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: sparse sets of integers?

2005-04-04 Thread Raymond Hettinger
n.activestate.com/ASPN/Cookbook/Python/Recipe/230113 Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: StopIteration in the if clause of a generator expression

2005-04-05 Thread Raymond Hettinger
> > [Steven Bethard] > > > So do I read this right in preferring > > > [ for in ] > > > over > > > list( for in ) [Raymond Hettinger] > > Yes! [Simon Brunning] > Why? (Serious question. I'm sure that you have a good reason -

Re: Propagating poorly chosen idioms

2005-04-05 Thread Raymond Hettinger
. I hope they don't lose it as the package evolves to include doctests and such. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: sorting a list and counting interchanges

2005-04-06 Thread Raymond Hettinger
ution anyway: >>> phase = 1 >>> def mycmp(x, y): global phase phase = -phase return cmp(x, y) >>> sorted('abracadabra', cmp=mycmp) ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r'] >>> phase -1 Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: sorting a list and counting interchanges

2005-04-06 Thread Raymond Hettinger
est: a[i], a[lowest] = a[lowest], a[i] parity = -parity print 'swapping %d with %d. parity is %d' % (i, lowest, parity) print parity, a Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: sorting a list and counting interchanges

2005-04-06 Thread Raymond Hettinger
if c > 0: # i.e. a swap will be performed in the sort >phase = -phase >return c You're right. An important test was omitted. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: sorting a list and counting interchanges

2005-04-06 Thread Raymond Hettinger
...). For some problems, that is a useful invariant. For instance, iirc, the parity determines whether a given 15 puzzle arrangement is solvable. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Why does StringIO discard its initial value?

2005-04-10 Thread Raymond Hettinger
> Is this the > expected behavior Yes. > , and why it isn't mentioned in the docs if so? Per your request, the docs have been updated. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

RE: [Python-Dev] args attribute of Exception objects

2005-04-12 Thread Raymond Hettinger
bjects: >>> class Boom(Exception): pass >>> x = 10 >>> if x != 5: raise Boom("Value must be a five", x) Traceback (most recent call last): File "", line 2, in -toplevel- raise Boom("Value must be a five", x) Boom: ('Value must be a five', 10) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Why does StringIO discard its initial value?

2005-04-12 Thread Raymond Hettinger
ther than letting it be a guide to good code. If there were something wrong with the API, Guido would have long since fired up the time machine and changed the timeline so that all would be as right as rain ;-) Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Python 2.4 killing commercial Windows Python development ?

2005-04-12 Thread Raymond Hettinger
[Robin Becker] > People have mentioned the older v6 build scripts/tools still work. Last time I > tried they seemed a bit out of date. I routinely use the current CVS to build Py2.4 and Py2.5 with MSC6. It is effortless and I've had no problems. Raymond Hettinger -- http://mail

Re: New-style classes, iter and PySequence_Check

2005-04-14 Thread Raymond Hettinger
rforms an __iter__ lookup, fill the slot with something that does that lookup. Raymond Hettinger E = mc**2 # Einstein E = IR # Ohm's law therefore IR = mc**2 # Raymond's grand unified theory -- http://mail.python.org/mailman/listinfo/python-list

Re: New-style classes, iter and PySequence_Check

2005-04-14 Thread Raymond Hettinger
n't walked the relevant iter() code. > That would be too easy ;-) The actual code for Object/abstract.c's PyObject_GetIter() is somewhat more straight-forward and less mysterious than those experiments suggest. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Behaviour of str.split

2005-04-18 Thread Raymond Hettinger
a person's intuition seems to lead them to guess that the behavior will be different than it actually is. Unfortunately, one person's intuition is often at odds with another's. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Removing dictionary-keys not in a set?

2005-04-18 Thread Raymond Hettinger
> >>> for k in s1-s2: > ... del d1[k] > ... FWIW, if s2 is not already a set object, it need not be transformed before using it. Instead, write: for k in set(d1).difference([1,3,5]): del d1[k] If you prefer to work with dictionaries instead of sets, then adapt the existing code for symmetric_difference_update() in sets.py. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Why Python does *SLICING* the way it does??

2005-04-19 Thread Raymond Hettinger
<[EMAIL PROTECTED]> > Many people I know ask why Python does slicing the way it does. Half open intervals are just one way of doing things. Each approach has its own merits and issues. Python's way has some useful properties: * s == s[:i] + s[i:] * len(s[i:j]) == j-i # if s is long eno

Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Raymond Hettinger
ething with lst[i] After going to all that trouble, you might as well also get the value at that position: for i, x in enumerate(lst): do something with lst[i] also known as x Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Raymond Hettinger
st[i] also known as x > > No you wouldn't, enumerate always starts with 0. You don't get it. Your proposed list-like class indicates its start index. enumerate() can be made to detect that start value so that the above code always works for both 0-based and 1-based arrays. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: time.strftime in 2.4.1 claims data out of range when not

2005-04-22 Thread Raymond Hettinger
0, 0, 6, 135, -1) >>> strftime("%Y-%m-%d", _) '2005-05-15' This somewhat circular technique sticks with the documented API but allows you to access all of the time module's options (like accessing the locale's names for days of the week and months of the year). Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Micro-PEP: str.translate(None) to mean identity translation

2005-04-30 Thread Raymond Hettinger
me. I'll put this in for you. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Fix for no module named _sysconfigdata while compiling

2015-02-26 Thread Raymond Cote
Thought I might help someone else address a problem I ran into this afternoon. While compiling Python 2.7.9 on CentOS 6, I received the error: no module named _sysconfigdata Googling found a number of other people having this problem — but the other issues were all after the Python was installed

Re: Windows service in production?

2015-03-20 Thread Raymond Cote
Years and years ago we found a module called ntsvc which allows us to run as a Service on Windows. We’ve been using it since well before 2011 to build 32-bit services on Windows with py2exe. If you contact me directly, I’ll dig it out of our source tree and post it on a shared location. Alterna

Python education survey

2011-12-19 Thread Raymond Hettinger
at as well; and IDLE sometimes just freezes for no reason. It also doesn't have an easy way to specify the startup directory. If your goal is to quickly get new users up and running in Python, what IDE or editor do you recommend? Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Python education survey

2011-12-22 Thread Raymond Hettinger
ll the other respondents for your thoughtful answers. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Differences creating tuples and collections.namedtuples

2013-02-18 Thread raymond . hettinger
'Guido') or Person(**d). The repr for the namedtuple would lose its eval(repr(t)) roundtrip property. If your starting point is an existing iterable such as s=['Guido', 'BDFL', 1], you have a couple of choices: p=Person(*s) or p=Person._make(s). The latter form was put it to help avoid unpacking and repacking the arguments. Raymond -- http://mail.python.org/mailman/listinfo/python-list

How to get urllib2 HTTPConnection object, use httplib methods?

2013-04-21 Thread Brian Raymond
I have a httplib based application and in an effort to find a quick way to start leveraging urllib2, including NTLM authentication (via python-ntlm) I am hoping there is a way to utilize an HTTPConnection object opened by urllib2. The goal is to change the initial opener to use urllib2, after t

Re: Memoization and encapsulation

2005-12-30 Thread Raymond Hettinger
cache[x] result = x + 1 # or a time consuming function return result * If cache hits are the norm, then a try/except version would be a bit faster. * In your original code, the global declaration wasn't needed because the assigment to _cache wasn't changed, rather its contents w

Re: Memoization and encapsulation

2005-12-30 Thread Raymond Hettinger
_cache[x] result = x + 1 # or a time consuming function _cache[x] = result return result * If cache hits are the norm, then a try/except version would be a bit faster. * In your original code, the global declaration wasn't needed because the assigment to _cache wasn&#x

Re: itertools.izip brokeness

2006-01-04 Thread Raymond Hettinger
as not been previously reported, nor have there any related feature requests, nor was the use case contemplated in the PEP discussions: http://www.python.org/peps/pep-0201 ). Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: itertools.izip brokeness

2006-01-04 Thread Raymond Hettinger
-clauses in a for-loop. OTOH, this approach is at odds with the notion of side-effect free functional programming and the purported benefits of that programming style. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Real-world use cases for map's None fill-in feature?

2006-01-08 Thread Raymond Hettinger
Does an outer-join have anything to do with lock-step iteration? Is this a fundamental looping construct or just a theoretical wish-list item? Does Python need itertools.izip_longest() or would it just become a distracting piece of cruft? Raymond Hettinger FWIW, the OP's use cas

Do you have real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
undamental looping construct or just a theoretical wish-list item? IOW, does Python really need itertools.izip_longest() or would that just become a distracting piece of cruft? Raymond Hettinger P.S. FWIW, the OP's use case involved printing files in multiple columns: for f, g in itertools.izip

Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
and, as I mentioned, even here the reliance was rather > doubtful. OTOH, if I had easily been able to specify a different > filler, I _would_ have been able to use it a couple of times. Did you run across any cookbook code that would have been improved by the proposed itertools.zip_longest() function? Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
the resulting strings according to their index? What does the code look like that accesses newAttrVal and how does it know the significance of various positions in the list? This is important because it could shed some light on how an app finds itself looping over two lists which share a common

Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
nations. It more easily explained than the versions with zip tricks. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
nction was specifically designed for tacking one or more elements onto the end of another iterable. It is ideal for appending sentinels. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Real-world use cases for map's None fill-in feature?

2006-01-09 Thread Raymond Hettinger
> Alternately, the need can be met with existing tools by pre-padding the > iterator with enough extra values to fill any holes: > > it = chain(iterable, repeat('', group_size-1)) > result = izip_longest(*[it]*group_size) Typo: That should be izip() instead of izip_longest() -- http://m

Re: Do you have real-world use cases for map's None fill-in feature?

2006-01-10 Thread Raymond Hettinger
code in which case it is probably better to explicitly manage individual iterators within a while loop. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Do you have real-world use cases for map's None fill-in feature?

2006-01-10 Thread Raymond Hettinger
[Raymond Hettinger] > > I am evaluating a request for an alternate version of itertools.izip() > > that has a None fill-in feature like the built-in map function: > > > > >>> map(None, 'abc', '12345') # demonstrate map's None fill-in

Re: Real-world use cases for map's None fill-in feature?

2006-01-10 Thread Raymond Hettinger
[Raymond] > > Both approaches require a certain measure of inventiveness, rely on > > advanced tricks, and forgo readability to gain the raw speed and > > conciseness afforded by a clever use of itertools. They are also a > > challenge to review, test, modify, read, or ex

Re: Do you have real-world use cases for map's None fill-in feature?

2006-01-10 Thread Raymond Hettinger
[Raymond] > >ISTM, these cures are worse than the disease ;-) [Bengt] > Are you reacting to my turgidly rambling post, or to > > >>> from ut.izip2 import izip2 as izip > >>> it = izip('abc','12','ABCD') > >>> for

Re: Augmented generators?

2006-01-10 Thread Raymond Hettinger
s with classlike attribute reads and writes. It shouldn't be hard to adapt the technique for attaching methods. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Bug in struct.pack?

2006-01-11 Thread Raymond Hettinger
ve alignment come into play. Specify a standard alignment to avoid padding. >>> pack("BI", 0, 1) '\x00\x00\x00\x00\x01\x00\x00\x00' >>> pack("=BI", 0, 1) '\x00\x01\x00\x00\x00' All is explained in the docs: http://docs.python.org/lib/module-struct.html Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Real-world use cases for map's None fill-in feature?

2006-01-12 Thread Raymond Hettinger
izip_longest() would end-up as unutilized cruft and add dead-weight to the language. The jury is still out but it doesn't look promising. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Real-world use cases for map's None fill-in feature?

2006-01-12 Thread Raymond Hettinger
[EMAIL PROTECTED] > > > How well correlated in the use of map()-with-fill with the > > > (need for) the use of zip/izip-with-fill? [raymond] > > Close to 100%. A non-iterator version of izip_longest() is exactly > > equivalent to map(None, it1, it2, ...). [EMAIL P

Re: flatten a level one list

2006-01-12 Thread Raymond Hettinger
;, 'x3', 'y3'] FWIW, if you're into working out puzzles, there's no end of interesting iterator algebra tricks. Here are a few identities for your entertainment: # Given s (any sequence) and n (a non-negative integer): assert zip(*izip(*tee(s,n))) == [tuple(s)]*n assert list(chain(*tee(s,n))) == list(s)*n assert map(itemgetter(0),groupby(sorted(s))) == sorted(set(s)) Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: How to remove subset from a file efficiently?

2006-01-12 Thread Raymond Hettinger
20.dat'): if num not in barred: print num, Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Freezing

2006-01-12 Thread Raymond Hettinger
non-PythonWay is to have state flag indicating frozenness and have that flag disable mutating methods while enabling a __hash__ method. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Real-world use cases for map's None fill-in feature?

2006-01-12 Thread Raymond Hettinger
ts. The existence of the latter is good news for the proposal. Its absence would be a contra-indication. If you get a chance, please look at those few multi-input cases. Thanks, Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: How to remove subset from a file efficiently?

2006-01-12 Thread Raymond Hettinger
inates duplicates (possibly a bad thing), and loses the original input ordering (probably a bad thing). To jam the action into a couple lines, try this: b = set(file('CBR319.dat')) file('PSP-CBR.dat','w').writelines(itertools.ifilterfalse(b.__contains__,file('PSP320.dat'))) Raymond -- 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 Raymond Hettinger
[EMAIL PROTECTED] > 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 > mu

Re: Real-world use cases for map's None fill-in feature?

2006-01-12 Thread Raymond Hettinger
[Paul Rubin] > ISTR there's also a plan to eliminate map in Python 3.0 in favor of > list comprehensions. That would get rid of the possibility of using > map(None...) instead of izip_longest. This needs to be thought through. Not to fear. If map() eventually loses its built-in status, it will

Re: How to remove subset from a file efficiently?

2006-01-14 Thread Raymond Hettinger
> > b = set(file('/home/sajid/python/wip/stc/2/CBR333')) > > > > file('PSP-CBR.dat,ray','w').writelines(itertools.ifilterfalse(b.__contains__,file('/home/sajid/python/wip/stc/2/PSP333'))) > > > > -- > > $ time ./cleanup_ray.py > > > > real0m5.451s > > user0m4.496

Re: proposal: another file iterator

2006-01-15 Thread Raymond Hettinger
#x27;ve seen it expressed using other tools: for c in iter(partial(somefile.read, blocksize), ''): . . . Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Decimal ROUND_HALF_EVEN Default

2006-01-16 Thread Raymond Hettinger
ro), or ROUND_UP (away from zero). > I usually do: Y = int(X + 0.5) scaled to proper # of decimal places. > Which type of rounding is this? If either. The interpreter shows that ties are rounded down towards zero: >>> [int(x + 0.5) for x in range(-5, 6)] [-4, -3, -2, -1, 0, 0, 1,

Re: random shuffles

2006-07-21 Thread Raymond Hettinger
s yes. But I don't feel quite > confortable > with the intuition... can anyone think of a more solid argumentation ? Try this: x.sort(key=lambda x: random.random()) Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Jumping over in the class hierarchy

2006-08-01 Thread Raymond Hettinger
g(self): C.__bases__[0].__bases__[0].f(self) # go up two levels >>> c = C() >>> c.f() 3 >>> c.g() 1 Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: enumerate improvement proposal

2006-10-31 Thread Raymond Hettinger
te(2, 'abcdef') --> (2, 'a'), (3, 'b') ... FWIW, it is not hard to roll-your-own with something like: for pagenum, page in izip(count(1), book): ... The izip/count combination runs at C speed, matches enumerate() in its efficiency, and is arguably clearer in expressing its intended behavior. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: multi split function taking delimiter list

2006-11-14 Thread Raymond Hettinger
values, one approach is to replace each of the possible splitters with a single splitter: def multi_split(s, splitters): first = splitters[0] for splitter in splitters: s = s.replace(splitter, first) return s.split(first) print multi_split( 'a:=b+c' , [':=','+'] ) Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: itertools.count() as built-in

2006-05-29 Thread Raymond Hettinger
, copy.copy, and many others would also be candidates. > It's a wonderful little function and I find myself > importing it in every module I write. I'm glad you find it so useful. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: split a line, respecting double quotes

2006-07-10 Thread Raymond Hettinger
f a stupid solution. IMO, this solution is on the right track. FWIW, the StringIO wrapper is unnecessary. Any iterable will do: reader(['a b c "d e"'], delimiter=' ') Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: "filtered view" upon lists?

2006-09-12 Thread Raymond Hettinger
unction=None): self._actual_list = actual_list self._filter_function = filter_function ### Example calls a = range(10) b = ListView(a, lambda x: x%2==0) print list(b), len(b), b[2], b[:3] a[:] = range(10,20) print list(b), len(b), b[2], b[:3] Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Inconsistency in dictionary behaviour: dict(dict) not calling __setitem__

2006-12-12 Thread Raymond Hettinger
elf, k,v) > self[k].visit_register_map(self) > > > However, when constructing dictionary with dictionary in constructor > like d = RegisterMap({'k':'v'}), __setitem__ is not called, Try subclassing from UserDict.DictMixin. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: How to subclass sets.Set() to change intersection() behavior?

2006-12-12 Thread Raymond Hettinger
little): return False return True p = mySet('abc') q = mySet('def') r = mySet('cde') print p.isDisjoint(q) print r.isDisjoint(q) Hope something like this works for you. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: trees

2006-12-18 Thread Raymond Hettinger
ttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/201423 Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Sorting on multiple values, some ascending, some descending

2007-01-03 Thread Raymond Hettinger
e, r.height))# sorts descending age and ascending height Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Efficient Find and Replace

2006-01-27 Thread Raymond Hettinger
L): L[i] = Mget(v, v) Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Efficient Find and Replace

2006-01-28 Thread Raymond Hettinger
Fredrik Lundh] > but that's 2-3 times slower than the OP's corrected code for his use > case, so I'm not sure it qualifies as more "efficient"... The alternate wasn't presented for efficiency. Its virtue is that with no additional effort, it generalizes to

Re: Using bytecode, not code objects

2006-01-28 Thread Raymond Hettinger
life unnecessarily hard, you can hack the compiler module just upstream from the creation of the code object -- alter the newCodeObject() method in pyassem.py. It's a pointless exercise, but maybe you'll have fun doing it or perhaps learn not to avoid obvious, direct solutions to the problem

Re: newbie: working iwth list of tuples

2006-01-28 Thread Raymond Hettinger
ds, operation): def z(record): newfield = operation(*[record[f] for f in inputfields]) return record + (newfield,) return z z = pfunc((1, 3), operator.add) # parameters specified by the user at runtime result = map(z, database) Parameterized filter, extract, and reduce functions can be handled in a like manner. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: newbie: working iwth list of tuples

2006-01-29 Thread Raymond Hettinger
[Raymond Hettinger] > Parameterized filter, extract, and reduce functions can be handled in a > like manner. Just for grins, here is a more worked-out example: def pfunc(inputfields, operation): "Parameterized computation of a new field" # For example, append a field th

Re: Decoupling the version of the file from the name of the module.

2006-01-29 Thread Raymond Hettinger
dule) Of course, the right answer is to do what everyone else does. Use a version control system instead of multiple files. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: newbie: working iwth list of tuples

2006-01-29 Thread Raymond Hettinger
[Raymond Hettinger] > > Parameterized filter, extract, and reduce functions can be handled in a > > like manner. > > Just for grins, here is a more worked-out example: See the ASPN Cookbook recipe for a version with doctests and a couple bug-fixes: http://aspn.activestate

Re: Print dict in sorted order

2006-01-29 Thread Raymond Hettinger
parent', 'name']): last = len(preferred_order) rank = dict(izip(preferred_order, count())) pairs = d.items() pairs.sort(key=lambda (k,v): rank.get(k, (last, k, v))) return '{%s}' % repr(pairs)[1:-1] d = dict(gid=10, type=20, parent=30, name=40, other=50

Re: Print dict in sorted order

2006-01-29 Thread Raymond Hettinger
> 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, (last, k, v))) > return '{%s}'

Re: StringIO proposal: add __iadd__

2006-01-29 Thread Raymond Hettinger
e everything that is filelike to have += as a synonym for write()? In for a penny; in for a pound. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: finding the intersection of a list of Sets

2006-01-31 Thread Raymond Hettinger
[Peter Otten] > >>> sets = map(set, "abc bcd cde".split()) > >>> reduce(set.intersection, sets) > set(['c']) Very nice. Here's a refinement: >>> sets.sort(key=len) >>> reduce(set.intersection, sets[1:], sets[0]) set(['c']) -- http://mail.python.org/mailman/listinfo/python-list

Re: determinant

2006-01-31 Thread Raymond Hettinger
[Tuvas] > I am trying to find a nice function that quickly determines the > determanant in python. Anyone have any recommendations? I've heard > about numpy, but I can't get it to work (It doesn't seem to like the > import Matrix statement...). Thanks! http://aspn.activestate.com/ASPN/Cookbook/Pyt

Re: StringIO proposal: add __iadd__

2006-01-31 Thread Raymond Hettinger
[Raymond Hettinger] > > The StringIO API needs to closely mirror the file object API. > > Do you want to change everything that is filelike to have += > > as a synonym for write()? [Paul Rubin] > Why would they need that? Polymorphism > StringIO objects have getvalue

Re: finding the intersection of a list of Sets

2006-01-31 Thread Raymond Hettinger
That should have been: >>> sets.sort(key=len) >>> reduce(set.intersection, sets) The only refinement was the pre-sort based on set length. -- http://mail.python.org/mailman/listinfo/python-list

Re: Calling a string as a function.

2006-02-02 Thread Raymond Hettinger
[EMAIL PROTECTED] wrote: > I'm completely new to python, so sorry for my ignorence. > How does one go about converting a string, for instants one received through > tcp, into something that can be called as a function? > I'm trying to have what the user sends to the computer through the network, >

Re: Reverse of map()?

2006-02-05 Thread Raymond Hettinger
ions with identical args and > kwds, since it's a rare need. Also, it is almost certain that the function calls and their execution will dominate his runtime. Even if the fantasied rmap() function existed, it would be unlikely to help. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Using bytecode, not code objects

2006-02-06 Thread Raymond Hettinger
Fabiano Sidler wrote: > 2006/1/29, Fabiano Sidler <[EMAIL PROTECTED]>: > > 28 Jan 2006 22:02:45 -0800, Raymond Hettinger <[EMAIL PROTECTED]>: > > > But if you want to make your life unnecessarily hard, you can hack the > > > compiler module just upstre

Re: datetime object from string

2006-02-06 Thread Raymond Hettinger
time_tuple = time.strptime(s, "%d/%m/%Y %H:%M:%S") >>> datetime.datetime(*time_tuple[:6]) datetime.datetime(2005, 1, 20, 15, 10, 1) http://docs.python.org/lib/datetime-datetime.html http://docs.python.org/lib/module-time.html Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: * 'struct-like' list *

2006-02-06 Thread Raymond Hettinger
+)\s+ Birthday:\s+(\d+)\s+ SocialSecurity:\s+(\d+) ''' print re.findall(pattern, inputData) Other respondants have suggested the third-party PyParsing module which provides a powerful general-purpose toolset for text parsing; however, it is always worth mastering Python basic

Re: Question about idioms for clearing a list

2006-02-07 Thread Raymond Hettinger
re was a pithy Tim Peters quotation to the effect that he was unpersuaded by language proposals predicated on some hypothetical average programmer not being smart enough to understand something that the rest of us find to be basic. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list

Re: Question about idioms for clearing a list

2006-02-07 Thread Raymond Hettinger
rent code. For instance, given a large list, you can typically update or replace individual elements faster than you can build-up a new list: L = [0] * 1000 # starting list for i in xrange(len(L)): L[i] += 1 beats: L = [0] * 1000 # starting list L = [L[i]+1 for i in x

Re: Question about idioms for clearing a list

2006-02-07 Thread Raymond Hettinger
ent of language or doc issues). If I never learn the del-statement, should I be surprised that I stuggle with how to express deletion? Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Question about idioms for clearing a list

2006-02-07 Thread Raymond Hettinger
[Ed Singleton] > Is it obvious to a newbie what the difference between mappings and > "not-mappings", and is it obvious exactly what is and isn't a mapping? FWIW, there is a glossary in the tutorial: http://docs.python.org/tut/node18.html -- http://mail.python.org/mailman/listinfo/python-lis

Re: Question about idioms for clearing a list

2006-02-10 Thread Raymond Hettinger
ogic or a print-statement. Guido, would of course recommend using a plain def-statement: L = list() def L_clearer(L=L): del L[:] for listbunch in buncher(src, '', L, L.append, L_clearer): print listbunch While I question why in-place updating was need

Re: Question about idioms for clearing a list

2006-02-10 Thread Raymond Hettinger
ceit, sentinel, constructor): for k, g in groupby(sourceit, lambda x: x != sentinel): if k: yield constructor(g) for setbunch in buncher(src, '', set): print setbunch * The improved version has no need for list.clear(). End of story. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: ordered sets operations on lists..

2006-02-10 Thread Raymond Hettinger
[Amit Khemka] > > Hello, Is there a *direct* way of doing set operations on lists which > > preserve the order of the input lists ? > > For Ex. l1 = [1, 5, 3, 2, 4, 7] > > l2 = [3, 5, 10] > > > > and (l1 intersect l2) returns [5, 3] (and (l2 intersect l1) [bonono] > what d

Re: itertools examples

2006-02-11 Thread Raymond Hettinger
t algebra; hence, it is appropriate that it be included in itertool examples. If your taste says otherwise, that's okay. Program however you want. If reading the examples helped you understand the toolset, then the docs accomplished their goal. Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Unexpected behaviour of getattr(obj, __dict__)

2006-02-14 Thread Raymond Hettinger
>>> getattr(Parrot, '__dict__') # creates a dictionary wrapper IOW, attribute lookup can do more than just return the result of a straight-lookup. The underlying mechanism is a deep and interesting subject. If you want to know more, try this link: http://users.rcn.com/python/download/Descriptor.htm Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Soduku

2006-02-15 Thread Raymond Hettinger
lgorithms. FWIW, my version is listed on ASPN: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473893 Raymond -- http://mail.python.org/mailman/listinfo/python-list

Re: Does python have an internal list/dictionary of functions?

2006-02-17 Thread Raymond Hettinger
[Carl J. Van Arsdall] > basically we have: > > >>>def functA(): > ... pass > > >>> functA > > > And what I'd like to do is: > > >>>__internalFuncDict__['functA'] > globals()['functA'] -- http://mail.python.org/mailman/listinfo/python-list

Re: Add a month

2006-02-17 Thread Raymond Hettinger
ut timedelta doesn't have a 'months' setting. Am I missing some easy > method or do I have to code a work around myself?? You need to code you own version. It was not included with datetime.timedelta() because the definition is ambiguous (i.e. what date is one month after Jan

Re: getting the line just before or after a pattern searched

2006-02-17 Thread Raymond Hettinger
and below ( or more than 1 line above/below) the pattern > 12345678 and save to variables? thanks You could use the re module to search everything at once: >>> import re >>> print re.findall('\n([^\n]*)\n12345678\n([^\n]*)', open('input.dat').read()) [('

Re: Multiplication optimization

2006-02-18 Thread Raymond Hettinger
ization efforts on making choosing the best data structures and hoisting constants out of loops. Raymond -- http://mail.python.org/mailman/listinfo/python-list

<    1   2   3   4   5   6   7   8   9   >