Re: how to make ["a","b",["c","d"],"e"] into ['a', 'b', 'c', 'd', 'e'] ?

2014-04-10 Thread Boris Borcic

Boris Borcic wrote:

Rustom Mody wrote:

def fl1(l): return [y for x in l for y in x]



# recursive flatten

def fr(l):

...   if not isinstance(l,list): return [l]
...   return fl1([fr(x) for x in l])


For a short non-recursive procedure - not a function, modifies L in-place but 
none of its sublists.

 >>> def flatten(L) :
for k,_ in enumerate(L) :
while isinstance(L[k],list) :
L[k:k+1]=L[k]

flattens L to any depth, eg

 >>> L=[1,[2,[3,4]],5,6,[[7],8]]
 >>> flatten(L)
 >>> L
[1, 2, 3, 4, 5, 6, 7, 8]


Mh, this will fail though if the last item (of the last item (of the...)) is an empty list, eg L=[[]]. If you 
want to cover this case you can wrap the inside of the proc with a try except IndexError: pass, in which case 
you can also simplify the enumerate(L) to an indefinite counter. Or insert a dummy value before starting and 
pop it off at the end.




---
Ce courrier électronique ne contient aucun virus ou logiciel malveillant parce 
que la protection avast! Antivirus est active.
http://www.avast.com


--
https://mail.python.org/mailman/listinfo/python-list


Re: how to make ["a","b",["c","d"],"e"] into ['a', 'b', 'c', 'd', 'e'] ?

2014-04-10 Thread Boris Borcic

Rustom Mody wrote:

def fl1(l): return [y for x in l for y in x]



# recursive flatten

def fr(l):

...   if not isinstance(l,list): return [l]
...   return fl1([fr(x) for x in l])


For a short non-recursive procedure - not a function, modifies L in-place but 
none of its sublists.

>>> def flatten(L) :
for k,_ in enumerate(L) :
while isinstance(L[k],list) :
L[k:k+1]=L[k]

flattens L to any depth, eg

>>> L=[1,[2,[3,4]],5,6,[[7],8]]
>>> flatten(L)
>>> L
[1, 2, 3, 4, 5, 6, 7, 8]


---
Ce courrier électronique ne contient aucun virus ou logiciel malveillant parce 
que la protection avast! Antivirus est active.
http://www.avast.com


--
https://mail.python.org/mailman/listinfo/python-list


Re: A and B but not C in list

2011-01-24 Thread Boris Borcic

Terry Reedy wrote:


The straightforward code

if a in L and b in L and c not in L and d not in L

scans the list 4 times.


of course for a single scan one can setify the list and write

S=set(L)
if a in S and b in S and c not in S and d not in S

or even, I guess, something like

{a,b} <= S and not S & {c,d}

also, I suppose that in some settings a,b,c,d could be made to belong to a class 
that has defined eg


__nonzero__ = __bool__ = S.__contains__

so that the if statement would become

if a and b and not c and not d

btw, did anybody ask the OP which if any of A,B,C,D otoh and L otoh would vary 
fastest ?


Whatever, BB


--
http://mail.python.org/mailman/listinfo/python-list


Re: How convert list to nested dictionary?

2010-11-05 Thread Boris Borcic

Arnaud Delobelle wrote:

macm  writes:


Hi Folks

How convert list to nested dictionary?


l

['k1', 'k2', 'k3', 'k4', 'k5']

result

{'k1': {'k2': {'k3': {'k4': {'k5': {}}

Regards

macm


reduce(lambda x,y: {y:x}, reversed(l), {})



d={}
while L : d={L.pop():d}


--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Macros's Not the Power in OOo they should be ?

2010-09-23 Thread Boris Borcic

Lawrence D'Oliveiro wrote:

flebber wrote:


Has anyone had much success with python macro's. Or developing powerful
macro's in an language?


I did an application for my own use recently, involving automatically
generating invoices in editable OOWriter format from my billing database. I
gave up on all the PyUNO stuff, and used ODFPY instead—so much easier to
generate ODF directly, without having to go through OpenOffice code.

And OpenOffice has been able to open the results for final tweaking just
fine.


A nice package to manipulate Ooo text documents with python is the pod module of 
the appy framework. It uses the same approach with a twist.



--
http://mail.python.org/mailman/listinfo/python-list


Re: List of lists surprising behaviour

2010-06-17 Thread Boris Borcic

candide wrote:


So what is the right way to initialize to 0 a 2D array ? Is that way
correct :


 >>> t=[[0 for _ in range(2)] for _ in range(3)]


That's overkill :) You can skip the inner loop by using a list display, eg

t=[[0,0] for _ in range(3)]



It seems there is no more trouble now :

 >>> t
[[0, 0], [0, 0], [0, 0]]
 >>> t[0][0]=1
 >>> t
[[1, 0], [0, 0], [0, 0]]
 >>>

Correct ?



--
http://mail.python.org/mailman/listinfo/python-list


Re: pythonize this!

2010-06-16 Thread Boris Borcic

Ignacio Mondino wrote:

On Tue, Jun 15, 2010 at 8:49 AM, superpollo  wrote:

goal (from e.c.m.): evaluate
1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three
consecutive + must be followed by two - (^ meaning ** in this context)

my solution:


s = 0
for i in range(1, 2011):

... s += i**2
... if not (i+1)%5:
... s -= 2*i**2
... if not i%5:
... s -= 2*i**2
...

print s

536926141




bye


I think This one is pretty, clean, using the standard library.
pretty pythonic.

def sign_and_sqr(n):
""" return a numbers square a change the sign accordingly
 if n % 5 == 0 or (n + 1) % 5 == 0:


imho this fails DRY too much to be wholly pythonic,
write rather

  if n%5 in (0,4) :


 return  (n ** 2) * -1
 else:
 return n ** 2

result = sum([sign_and_sqr(x) for x in range(0,2011)])
print result

ok, the function has two exits, but im lazy at the moment :)





--
http://mail.python.org/mailman/listinfo/python-list


Re: An iteration idiom (Was: Re: [Guppy-pe-list] loading files containing multiple dumps)

2009-09-02 Thread Boris Borcic

Sverker Nilsson wrote:

Sverker Nilsson wrote:

It reads one Stat object at a time and wants to report something
when there is no more to be read from the file. 

Hmm, am I right in thinking the above can more nicely be written as:

 >>> from guppy import hpy
 >>> h = hpy()
 >>> f = open(r'your.hpy')
 >>> sets = []
 >>> for s in iter(h.load(f)): sets.append(s)
...


The above iterates over one Stat object returned by h.load(f). I assume
you want to iterate over all the objects loaded.


I dont know guppy,
but if h.load(f) raises StopIteration upon eof, as seems implied by your 
proposal, then something like the following would work.


sets.extend(h.load(f) for _ in xrange(1e9))

--
http://mail.python.org/mailman/listinfo/python-list


Re: Making the case for repeat

2009-06-12 Thread Boris Borcic

Raymond Hettinger wrote:

There is a natural inclination to do the opposite.  We factor code
to eliminate redundancy, but that is not always a good idea with
an API.  The goal for code factoring is to minimize redundancy.
The goal for API design is having simple parts that are easily
learned and can be readily combined (i.e. the notion of an
iterator algebra).


This reminds me of an early programming experience that left me with a 
fascination. At a time where code had to fit in a couple dozens kilobytes, I 
once had to make significant room in what was already very tight and terse code. 
Code factoring *did* provide the room in the end, but the fascinating part came 
before.


There was strictly no redundancy apparent at first, and finding a usable one 
involved contemplating code execution paths for hours until some degree of 
similarity was apparent between two code path families. And then, the 
fascinating part, was to progressively mutate both *away* from minimality of 
code, in order to enhance the similarity until it could be factored out.


I was impressed; in various ways. First; that the effort could be characterized 
quite mechanically and in a sense stupidly as finding a shortest equivalent 
program, while the subjective feeling was that the task exerted perceptive 
intelligence to the utmost. Second; by the notion that a global constraint of 
code minimization could map more locally to a constraint that drew code to 
expand. Third; that the process resulted in bottom-up construction of what's 
usually constructed top-down, mimicking the willful design of the latter case, 
eg. an API extension, as we might call it nowadays.


Cheers, BB
--
"hope achieves the square root of the impossible"


--
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehension question

2009-05-06 Thread Boris Borcic

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] instead of the correct b = [1,2,3,4,5,6]. What am I
doing wrong?
--
http://mail.python.org/mailman/listinfo/python-list



just fyi, in python 2.6

list(itertools.chain.from_iterable(a))

would do it

in python 2.5

list(itertools.chain(*a))

would do it too, but I wouldn't try it with arbitrarily long a





--
http://mail.python.org/mailman/listinfo/python-list


Re: Python to Perl transalators

2009-03-18 Thread Boris Borcic

Armin wrote:



Why on earth would you want to? That'd be like translating Shakespeare
into a bad rap song!



lol, actually I would prefer a rap song over Shakespeare, so your analogy 
doesn't work there ;)


Why, some people do prefer Perl over Python, so what's wrong with the analogy ?

--
http://mail.python.org/mailman/listinfo/python-list


Re: Ban Xah Lee

2009-03-08 Thread Boris Borcic

seconded.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Themed TK (tk Tile) at last?!

2009-03-08 Thread Boris Borcic

Python Nutter wrote:

Looks like we finally get tkinter GUI based programs according to
Issue# 2983 in Python 3.1a so our programs don't look like something
out of early 1980's


Please don't confuse History gratuitously. Make that mid 90's.

Cheers, BB

--
http://mail.python.org/mailman/listinfo/python-list


Re: Delete all items in the list

2009-02-26 Thread Boris Borcic

Chris Rebert wrote:

On Thu, Feb 26, 2009 at 3:05 AM, Clarendon  wrote:

...

L=['a', 'b', 'c', 'a']

I want to delete all 'a's from the list.
But if L.remove('a') only deletes the first 'a'.

How do you delete all 'a's?


There are several ways. I'd go with a list comprehension:


and for a couple other ways

while 'a' in L : L.remove('a')

L = filter('a'.__ne__,L)

--
http://mail.python.org/mailman/listinfo/python-list


Re: lazy evaluation is sometimes too lazy... help please.

2009-01-16 Thread Boris Borcic

   itlist[i] = (x+(i*10) for i,s in (i,count()) for x in s)


oops, that would be

 itlist[i] = (x+(i*10) for i,s in [(i,count())] for x in s)

or equivalent, kind of ugly anyway.

--
http://mail.python.org/mailman/listinfo/python-list


Re: lazy evaluation is sometimes too lazy... help please.

2009-01-16 Thread Boris Borcic

The minimal correction, I guess, is to write

   itlist[i] = (x+(i*10) for i in [i] for x in count())

instead of

   itlist[i] = (x+(i*10) for x in count())

although

   itlist[i] = (x+(i*10) for i,s in (i,count()) for x in s)

will better mimic generalizations in the sense that the "minimal correction" 
delays the evaluation of count(), which doesn't matter in the case of count(), 
but might make a difference if you replace it with some other expression.


The point is that the first iterator-producing expression in a generator 
expression - eg the  in ( for vars in ...) - is evaluated immediately 
in the surrounding context, in contrast to the rest of the genexp.


Cheers, BB

Ken Pu wrote:

Hi,  below is the code I thought should create two generates, it[0] =
0,1,2,3,4,5, and it[1] = 0,10,20,30,..., but they turn out to be the
same!!!

from itertools import *
itlist = [0,0]
for i in range(2):
  itlist[i] = (x+(i*10) for x in count())

print "what's in the bags:"
print list(islice(itlist[0], 5))
print list(islice(itlist[1], 5))

The output is:
[10, 11, 12, 13, 14]
[10, 11, 12, 13, 14]

I see what Python is doing -- lazy evaluation doesn't evaluate
(x+(i*10) for x in count()) until the end.  But is this the right
behaviour?  How can I get the output I want:
[0, 1, 2, 3, 4]
[10, 11, 12, 13, 14]

Thanks.

Ken
--
http://mail.python.org/mailman/listinfo/python-list



--
http://mail.python.org/mailman/listinfo/python-list


Re: More elegant way to try running a function X times?

2008-11-20 Thread Boris Borcic

Tim Chase wrote:

success = None
for i in range(5):
#Try to fetch public IP
success = CheckIP()
if success:
break
if not success:
print "Exiting."
sys.exit()

Though a bit of an abuse, you can use

  if not any(CheckIP() for _ in range(5)):
print "Exiting"
sys.exit()


I don't see why you speak of abuse, bit of abuse would be, say if you 
replaced range(5) by '12345' to win a char; but otoh I think you 
misspelled any() for all().


The OP's code break'ed (broke?) upon the first success, rather than 
checking all of them.  Thus, it would be any() rather than all().  Using 
all() would require 5 successful calls to CheckIP(), rather than 
one-out-of-five successful calls.


Right. So it could also be written " if all(not CheckIP()... ". Perhaps more 
closely re-telling the OP's ?




As for abuse, the "for _ in iterable" always feels a little hokey to 
me.  It works, but feels warty.


I guess this means you did not learn Prolog before Python ?

Cheers, BB

--
http://mail.python.org/mailman/listinfo/python-list


Re: More elegant way to try running a function X times?

2008-11-20 Thread Boris Borcic

Tim Chase wrote:


success = None
for i in range(5):
#Try to fetch public IP
success = CheckIP()
if success:
break
if not success:
print "Exiting."
sys.exit()


Though a bit of an abuse, you can use

  if not any(CheckIP() for _ in range(5)):
print "Exiting"
sys.exit()


I don't see why you speak of abuse, bit of abuse would be, say if you replaced 
range(5) by '12345' to win a char; but otoh I think you misspelled any() for all().


Cheers BB

--
http://mail.python.org/mailman/listinfo/python-list


Re: Function to Add List Elements?

2008-10-23 Thread Boris Borcic

Chris Rebert wrote:

On Wed, Oct 22, 2008 at 12:59 PM, Henry Chang <[EMAIL PROTECTED]> wrote:

This seems like a simple problem, but I can't find a simple solution.

Suppose I have two lists of integers.

List A = [A1, A2, A3]
List B = [B1, B2, B3]

I just simply want a new list, such as:

List C = [C1, C2, C3]

where:

C1 = A1 + B1
C2 = A2 + B2
C3 = A3 + B3

Is there a simple function to do this?


A one-liner in fact:

summed = [sum(pair) for pair in zip(listA, listB)]


or a two-liner :

from operator import add
summed = map(add,listA,listB)

or a hybrid :

summed = map(sum,zip(listA,listB))

Cheers, BB

--
http://mail.python.org/mailman/listinfo/python-list


Re: Append a new value to dict

2008-10-16 Thread Boris Borcic

Kirk Strauser wrote:

While we're on
the subject, use keyword arguments to dict like:

foo.update(dict(quux='blah', baz='bearophile', jdd='dict'))

was *much* slower, at 11.8s.


Presumably you would save half of that time by writing simply

   foo.update(quux='blah', baz='bearophile', jdd='dict')

Cheers, BB

--
http://mail.python.org/mailman/listinfo/python-list


Re: ABCs -> infix syntax for isinstance() ?

2008-10-09 Thread Boris Borcic

Terry Reedy wrote:

Boris Borcic wrote:

...


- allowing containment tests, ie "x in Number" to invoke isinstance() 
in the background when the container is of type . My brain is 
too muddled by flu at the moment, to see whether Guido's fabled time 
machine allowed him to already provide all the necessities in py26.

Any takers ?


I believe this could be done by adding a __contains__ method to type.
(It does not have one now).  Then x in X should work for all classes 
that are instances of type or a subclass thereof.


Can this be done short of patching the source and recompiling (eg, with ctypes 
perhaps) ?


Cheers, BB

--
http://mail.python.org/mailman/listinfo/python-list


Re: ABCs -> infix syntax for isinstance() ?

2008-10-08 Thread Boris Borcic

Bruno Desthuilliers wrote:

[EMAIL PROTECTED] a écrit :

...

A intriguing wider proposition would be to transpose Ruby's notion of
"Open Classes" to Python built-in metaclasses (or just to type
itself ?).


No, thanks. Even the Ruby guys start to think making evrything open may 
not be such a good idea after all.


Wasn't an all-or-nothing proposition; a good objection is spelled out in PEP 
3119 (ABCs) :




...but there are some good reasons to keep the built-in types immutable (for 
one, they are shared between all Python interpreters running in the same address 
space, as is used by mod_python)




Cheers, BB

--
http://mail.python.org/mailman/listinfo/python-list


Re: ABCs -> infix syntax for isinstance() ?

2008-10-07 Thread Boris Borcic

Bruno Desthuilliers wrote:


Boris Borcic a écrit :


Given the ABC innovation, maybe an infix syntax for isinstance() would
be good.
Possibilities :
- stealing "is" away from object identity. As a motivation, true use
cases for testing object identity are rare;



"x is None" is a *very* common test. (...)
Testing a class identity often happens when writing metaclasses



This kind-of-talks for Terry's proposition : adding a __contains__ to
type,



I said "type identity testing", not isinstance() or issubclass() testing.


Yes, but in the thread's context [of choosing between "is" and "in" as infix 
syntax for isinstance()] you were in effect raising as an objection to the first 
choice that it meant conflict with this use case [of "type identity testing" 
which is "common when writing metaclasses"].


This implied "writing metaclasses" as a background experience to decide the 
issue, what in turn implied a preference for the second solution ("x in Number") 
on *two* counts.


First because it was a proposed alternative to what you were objecting to, and
Second because "x in Number" has this most simple "metaclassy" solution.

(...)


And anyway, I don't see how any of the above address the point that your 
premise that "true identity testing is rare" is just wrong...




I wrote "true use cases for identity testing are rare", it was more of an 
auxiliary assertion that a premise, and nothing you objected really disproved it 
(for an adequate definition of "true use case").


* writing metaclasses is rare, and so is testing class identity in its context.

* "x is None" is arguably not a "true use case", in the sense that it is a case 
of testing identity against a constant that


- doesn't compare equal to anything else
- is the single instance of a singleton class

so that there exists both an equality test and an isinstance() test that are 
equivalents to the identity test.


Cheers, BB






--
http://mail.python.org/mailman/listinfo/python-list


ABCs -> infix syntax for isinstance() ?

2008-10-03 Thread Boris Borcic

Given the ABC innovation, maybe an infix syntax for isinstance() would be good.

Possibilities :

- stealing "is" away from object identity. As a motivation, true use cases for 
testing object identity are rare; forcing the usage of a function or method to 
test it, would dissuade abuse.


- allowing containment tests, ie "x in Number" to invoke isinstance() in the 
background when the container is of type . My brain is too muddled by flu 
at the moment, to see whether Guido's fabled time machine allowed him to already 
provide all the necessities in py26.

Any takers ?

- combining both keywords to create a third one, eg "is in"

Whaddyathink ?

BB

--
http://mail.python.org/mailman/listinfo/python-list


Re: What is not objects in Python?

2008-10-01 Thread Boris Borcic

42, for instance.

Proof :

>>> 42 is not object
True

QED

--
http://mail.python.org/mailman/listinfo/python-list


Re: dict generator question

2008-09-19 Thread Boris Borcic

Gerard flanagan wrote:

George Sakkis wrote:

..


Note that this works correctly only if the versions are already sorted
by major version.



Yes, I should have mentioned it. Here's a fuller example below. There's 
maybe better ways of sorting version numbers, but this is what I do.


Indeed, your sort takes George's objection too litterally, what's needed for a 
correct endresult is only that major versions be grouped together, and this is 
most simply obtained by sorting the input data in (default) string order, is it 
not ?





data = [ "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.1.1.1", "1.3.14.5", 
"1.3.21.6" ]


from itertools import groupby
import re

RXBUILDSORT = re.compile(r'\d+|[a-zA-Z]')

def versionsort(s):
key = []
for part in RXBUILDSORT.findall(s.lower()):
try:
key.append(int(part))
except ValueError:
key.append(ord(part))
return tuple(key)

data.sort(key=versionsort)
print data

datadict = \
dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3]))
print datadict




--
http://mail.python.org/mailman/listinfo/python-list



--
http://mail.python.org/mailman/listinfo/python-list


Re: recursion gotcha?

2008-09-14 Thread Boris Borcic

cnb wrote:

this recursive definition of sum thrumped me, is this some sort of
gotcha or am I just braindead today?
and yes i know this is easy a a for x in xs acc += x or just using the
builtin.

def suma(xs, acc=0):
if len(xs) == 0:
acc
else:
suma(xs[1:], acc+xs[0])

it returns none.


Without return statement, the only recursive solution is a lambda expr :

>>> suma = lambda xs : xs[0]+suma(xs[1:]) if xs else 0

>>> suma(range(101))
5050

Note that suma(xs[1:]) implies copying the remainder of xs, what in turn makes 
the time grow quadratically with the length of xs. So instead of passing a 
superfluous acc second variable, you could pass an index into the list, eg


def suma(xs,pos=0) :
if pos>=len(xs) :
   return 0
else :
   return xs[pos]+suma(xs,pos+1)

Cheers, BB

--
http://mail.python.org/mailman/listinfo/python-list


Re: Injecting new names into the above frame

2008-09-13 Thread Boris Borcic
Why don't you use import and __import__() ? - They seem designed for such an 
application.


I mean, I am not against vicious hacks for the fun of them, but not if they 
serve the illusion that what they do can't (easily) be achieved other ways.


Cheers, BB

Peter Waller wrote:

Dear Pythoners,

I know this will probably be perceived as 'evil voodoo', and fair
enough: it probably is. I guess it is unpythonic.

.. but I want to know how to do it anyway - mostly for my own
interest.

Consider the following snippet of code:

---
def Get( *names ):
if not names: return None

frame = sys._getframe(1)
prevFrameLocals = frame.f_locals

for name in names:
prevFrameLocals[ name ] = FetchObjectNamed( name )

Get("a", "b", "c")

print a, b, c
---

FetchObjectNamed() is an arbitrary function which takes a string and
returns an object it got from some store somewhere.

This works fine at the module level, because names in the locals/
globals dictionary can be played with in this way. The idea is to save
lots of typing, i.e.

a, b, c = Get("a","b","c")

..gets frustrating after much typing for many objects with long names.
This is just an example, there are other instances I have where it
would be nice to inject names into the frame above.

Of course, we hit a road block when we call 'Get' from a function
rather than a module, because the locals dictionary does not get
copied back into the code object automatically, so we have to add this
snippet before the Get() function returns:

from ctypes import pythonapi, py_object, c_int
pythonapi.PyFrame_LocalsToFast( py_object( frame ), 1 )

This copies back the names into the code object, and works fine.. that
is, if the names already exist within the code object.

def MyFunction():
a = None
Get("a")
print a # Works
Get("b")
print b # Name error, b is undefined

Is there any way for Get() to define a new variable within
MyFunction's code object? Or is there any programmatic way to, at
runtime, insert new names into functions?

I don't care how hacky it is and whether it requires making calls to
python's internals with ctypes - maybe the whole code object needs to
be replaced? is it even possible to do that when the Get() function is
about to return to this new code object?

Cheers,

- Peter
--
http://mail.python.org/mailman/listinfo/python-list



--
http://mail.python.org/mailman/listinfo/python-list


''.join woes - Re: max(), sum(), next()

2008-09-13 Thread Boris Borcic

I wrote:

Tino Wildenhain wrote:

[...]

sum(['a','b'],'')


: sum() can't sum strings [use 
''.join(seq) instead]


Yes which is a bit bad anyway. I don't think hard wiring it is such a 
nice idea. You know, walks like a duck, smells like a duck...

If it makes sense to handle things differently for performance, then
please have it doing it silently, e.g. when it detects strings just
use join() internally.

Cheers
Tino


+1

''.join is horrible. And it adds insult to injury that 
S.join(S.split(T)) != T as a rule. The interpreter has no business to 
patronize us into this shamefully contorted neighborhood while it 
understands what we want.


What makes ''.join particularly horrible is that we find ourselves forced to use 
it not only for concatenating arbitrary-length strings in a list, but also to 
convert to a str what's already a sequence of single characters. IOW string 
types fail to satisfy a natural expectation for any S of sequence type :


S == type(S)(item for item in S) == type(S)(list(S))

And this, even though strings are sequence types deep-down-ly enough that they 
achieve to act as such in far-fetched corner cases like


(lambda *x : x)(*'abc')==('a','b','c')

...and even though strings offer not one but two distinct constructors that play 
nicely in back-and-forth conversions with types to which they are much less 
closely related, ie.


'1j' == repr(complex('1j') == str(complex('1j'))
1j == complex(repr(1j)) == complex(str(1j))

Not-so-cheerfully-yours, BB

--
http://mail.python.org/mailman/listinfo/python-list


Re: max(), sum(), next()

2008-09-13 Thread Boris Borcic

Tino Wildenhain wrote:

Hi,

Luis Zarrabeitia wrote:

Quoting Laszlo Nagy <[EMAIL PROTECTED]>:


...

Even better:

help(sum) shows

===
sum(...)
sum(sequence, start=0) -> value
Returns the sum of a sequence of numbers (NOT strings) plus 
the value

of parameter 'start'.  When the sequence is empty, returns start.
===

so the fact that sum([]) returns zero is just because the start value 
is zero...

sum([],object()) would return an object().

BTW, the original code:


sum(s for s in ["a", "b"] if len(s) > 2)


wouldn't work anyway... it seems that sum doesn't like to sum strings:


sum(['a','b'],'')


: sum() can't sum strings [use 
''.join(seq) instead]


Yes which is a bit bad anyway. I don't think hard wiring it is such a 
nice idea. You know, walks like a duck, smells like a duck...

If it makes sense to handle things differently for performance, then
please have it doing it silently, e.g. when it detects strings just
use join() internally.

Cheers
Tino


+1

''.join is horrible. And it adds insult to injury that S.join(S.split(T)) != T 
as a rule. The interpreter has no business to patronize us into this shamefully 
contorted neighborhood while it understands what we want.


Cheers, BB

--
http://mail.python.org/mailman/listinfo/python-list


Re: max(), sum(), next()

2008-09-09 Thread Boris Borcic

castironpi wrote:

On Sep 8, 8:54 am, Boris Borcic <[EMAIL PROTECTED]> wrote:

David C. Ullrich wrote:


(ii) If A is a subset of B then we should have
max(A) <= max(B). This requires that max(empty set)
be something that's smaller than everything else.
So we give up on that.

Er, what about instances of variations/elaborations on

class Smaller(object) : __cmp__ = lambda *_ : -1

?

Cheers, BB


You still don't have the property max(X) is in X.


Frankly, I would favor order-independence over that property.

compare max(X) for

1) X = [set([1]),set([2])]

and

2) X = [set([2]),set([1])]

Shouldn't then max and min in fact return lub and glb, despite their names ? In 
the case X is a non-empty finite set/list of totally ordered values, 
max(X)==lub(X) and min(X)=glb(X) in any case.




And it's the equivalent of a special builtin constant for max on the
empty set.


Of course (except the object might have other uses, who knows). So what ?

Cheers, BB

--
http://mail.python.org/mailman/listinfo/python-list


Re: max(), sum(), next()

2008-09-08 Thread Boris Borcic

David C. Ullrich wrote:


(ii) If A is a subset of B then we should have
max(A) <= max(B). This requires that max(empty set)
be something that's smaller than everything else.
So we give up on that.



Er, what about instances of variations/elaborations on

class Smaller(object) : __cmp__ = lambda *_ : -1

?

Cheers, BB

--
http://mail.python.org/mailman/listinfo/python-list


Re: Lining Up and PaddingTwo Similar Lists

2008-08-29 Thread Boris Borcic

D,T=[dict((x.split('.')[0],x) for x in X) for X in (dat,txt)]
for k in sorted(set(D).union(T)) :
for S in D,T :
print '%-8s' % S.get(k,'None'),
print

HTH

W. eWatson wrote:
Maybe there's some function like zip or map that does this. If not, it's 
probably fairly easy to do with push and pop. I'm just checking to see 
if there's not some known simple single function that does what I want. 
Here's what I'm trying to do.


I have a list dat like (assume the items are strings even thought I'm 
omitting quotes.):

[a.dat, c.dat, g.dat, k.dat, p.dat]

I have another list called txt that looks like:
[a.txt, b.txt, g.txt, k.txt r.txt, w.txt]

What I need is to pair up items with the same prefix and use "None", or 
some marker, to indicate the absence of the opposite item. That is, in 
non-list form, I want:

a.dat a.txt
None  b.txt
c.dat None
g.dat g.txt
k.dat k.txt
p.dat  None
None  r.txt
None  w.txt

Ultimately, what I'm doing is to find the missing member of pairs.


--
http://mail.python.org/mailman/listinfo/python-list


Re: like a "for loop" for a string

2008-08-18 Thread Boris Borcic

Alexnb wrote:

Uhm, "string" and "non-string" are just that, words within the string. Here
shall I dumb it down for you?


string = "yes text1 yes text2 yes text3 no text4 yes text5+more Text yes
text6  no text7 yes text8"

It doesn't matter what is in the string, I want to be able to know exactly
how many "yes"'s there are. 
I also want to know what is after each, regardless of length. So, I want to

be able to get "text1", but not "text4" because it is after "no" and I want
all of "text5+more Text" because it is after "yes". It is like the yeses are
bullet points and I want all the info after them. However, all in one
string.



def list_of_yes_prefixed_possibly_no_suffixed(s) :
return (' '+s).split(' yes ')[1:]

def removed_no_suffixes(t) :
return t.split(' no ')[0]

infos = map(removed_no_suffixes,
list_of_yes_prefixed_possibly_no_suffixed(string))

how_many = len(infos)

or as a one-liner :

infos = [ t.split(' no ')[0] for t in (' '+string).split(' yes ')[1:]]




Fredrik Lundh wrote:

Alexnb wrote:


Basically I want the code to be able to pick out how many strings there
are
and then do something with each, or the number. When I say string I mean
how
many "strings" are in the string "string string string non-string string"

 >

Does that help?
not really, since you haven't defined what "string" and "non-string" are 
   or how strings are separated from each other, and, for some odd 
reason, refuse to provide an actual example that includes both a proper 
sample string *and* the output you'd expect.


please don't use the mailing list to play 20 questions.



--
http://mail.python.org/mailman/listinfo/python-list






--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a faster way to do this?

2008-08-06 Thread Boris Borcic

Is your product ID always the 3rd and last item on the line ?
Else your output won't separate IDs.

And how does

output = open(output_file,'w')
for x in set(line.split(',')[2] for line in open(input_file)) :
output.write(x)
output.close()

behave ?


[EMAIL PROTECTED] wrote:

I have a csv file containing product information that is 700+ MB in
size. I'm trying to go through and pull out unique product ID's only
as there are a lot of multiples. My problem is that I am appending the
ProductID to an array and then searching through that array each time
to see if I've seen the product ID before. So each search takes longer
and longer. I let the script run for 2 hours before killing it and had
only run through less than 1/10 if the file.

Heres the code:
import string

def checkForProduct(product_id, product_list):
for product in product_list:
if product == product_id:
return 1
return 0


input_file="c:\\input.txt"
output_file="c:\\output.txt"
product_info = []
input_count = 0

input = open(input_file,"r")
output = open(output_file, "w")

for line in input:
break_down = line.split(",")
product_number = break_down[2]
input_count+=1
if input_count == 1:
product_info.append(product_number)
output.write(line)
output_count = 1
if not checkForProduct(product_number,product_info):
product_info.append(product_number)
output.write(line)
output_count+=1

output.close()
input.close()
print input_count
print output_count
--
http://mail.python.org/mailman/listinfo/python-list



--
http://mail.python.org/mailman/listinfo/python-list


Re: 2d graphics - what module to use?

2008-07-25 Thread Boris Borcic

Pierre Dagenais wrote:
What is the easiest way to draw to a window? I'd like to draw something 
 like sine waves from a mathematical equation.

Newbie to python.
--
http://mail.python.org/mailman/listinfo/python-list



For very simple things, the standard module turtle might be your best bet.

BB

--
http://mail.python.org/mailman/listinfo/python-list


Re: listcomprehension, add elements?

2008-06-23 Thread Boris Borcic

John Machin wrote:


Instead of sum(a + b for a, b in zip(foo, bar))
why not use sum(foo) + sum(bar)
?


or even sum(foo+bar) as may apply.

Cheers, BB

--
http://mail.python.org/mailman/listinfo/python-list


Re: slicing lists

2008-05-08 Thread Boris Borcic

Yves Dorfsman wrote:


So would it be a worthy addition to python, to add it right in the core 
of the language, and hopefully in an efficient manner ?




Note that the s[0,2:6] syntax is currently allowed because of the distinct 
semantics that the Numeric module and its successors numarray and numpy had for it.


--
http://mail.python.org/mailman/listinfo/python-list


Re: parameters to lambda's executed at run time.

2008-05-06 Thread Boris Borcic

One way :

>>> from functools import partial
>>> def func(item) : print item

>>> llist = [partial(func,item) for item in range(5)]
>>> for thing in llist : thing()

0
1
2
3
4


wyleu wrote:

I'm trying to supply parameters to a function that is called at a
later time as in the code below:

llist = []

for item in range(5):
llist.append(lambda: func(item))

def func(item):
print item

for thing in llist:
thing()

which produces the result

IDLE 1.2.1

 RESTART 


 at 0xb716356c>
 at 0xb71635a4>
 at 0xb71635dc>
 at 0xb7163614>
 at 0xb716364c>

 RESTART 


4
4
4
4
4

How can one allocate a different parameter to each instance of the
function rather than all of them getting the final value of the loop?


--
http://mail.python.org/mailman/listinfo/python-list


Re: computing with characters

2008-05-06 Thread Boris Borcic

Duncan Booth wrote:

Torsten Bronger <[EMAIL PROTECTED]> wrote:


The biggest ugliness though is ",".join().  No idea why this should
be better than join(list, separator=" ").  Besides, ",".join(u"x")
yields an unicode object.  This is confusing (but will probably go
away with Python 3).


It is only ugly because you aren't used to seeing method calls on string 
literals.


An obviously independent cause of uglyness is the inconsistency of eg
','.split() and ','.join()

Cheers, BB
--
http://mail.python.org/mailman/listinfo/python-list


Re: get number that is raised to the power of

2008-05-02 Thread Boris Borcic

Marc 'BlackJack' Rintsch wrote:

On Fri, 02 May 2008 19:19:07 +1000, Astan Chee wrote:


Hi,
Im not sure if this is more of a math question or a python question. I 
have a variable in python:

 >>> v = 10.0**n
is there a way to find the value of n if i know only v aside from 
str(v).split('+')[1] ?


Astan, you could try something like (n for n in range(1,100) if 
10.0**n==v).next() or like len(str(int(v)))-1


that seems like too much of a hack and I was 
wondering if there was a faster way of doing it?


Faster ?! How fast do you need it to be ?



That hack isn't even working properly because ``str(10.0**1)`` has no '+'
in its string representation.


OTOH "%.0e" % (10.0**1) does
...but "%.0e" % (10.0**-1) of course doesn't



Solution:

n = math.log(v, 10)

Ciao,
Marc 'BlackJack' Rintsch


Beware of floating point approximations, though. Eg

>>> assert log(10**3,10)==3

Traceback (most recent call last):
  File "", line 1, in 
assert log(10**3,10)==3
AssertionError

Cheers, BB
--
http://mail.python.org/mailman/listinfo/python-list


Re: __iter__ yield

2008-03-10 Thread Boris Borcic
Paul Hankin wrote:
> On Mar 10, 3:12 am, George Sakkis <[EMAIL PROTECTED]> wrote:
>> On Mar 9, 7:37 pm, Paul Hankin <[EMAIL PROTECTED]> wrote:
>>
>>
>>
>>> On Mar 9, 8:58 pm, duccio <[EMAIL PROTECTED]> wrote:
 Someone knows if it's possible to make this __iter__ function with just
 one 'yield' intead of two?
 ...
  def __iter__(self):
  yield self #1
  for n in self.childs:
  for nn in n.__iter__():
  yield nn #2
>>> Only one yield and shorter (but not really any simpler):
>>> from itertools import chain
>>> class Node:
>>> ...
>>> def __iter__(self):
>>> for x in chain([self], *self.childs):
>>> yield x
>> Actually this doesn't need a yield at all:
>>
>> class Node:
>> ...
>> def __iter__(self):
>> return chain([self], *self.childs)
> 
> The two have slightly different behaviours: without the yield, iter is
> called immediately on every node in the tree as the iterators are
> built. With yield, iterators are built lazily, giving better
> behaviour.

generator expressions allow to save on the 'yield' while keeping the lazy 
behavior, with either :

  def __iter__(self):
 return chain([self],(y for x in self.childs for y in x))

or

  def __iter__(self):
 return (y for x in chain([[self]],self.childs) for y in x)

BB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Making string-formatting smarter by handling generators?

2008-02-27 Thread Boris Borcic
D'Arcy J.M. Cain wrote:
>> I find I hit it mostly with calls to map() where I want to apply 
>> some transform (as above) to all the items in a list of 
>> parameters such as
>>
>>"%s=%s&%s=%s" % map(urllib.quote, params)
> 
> Isn't map() deprecated?  The above can be done with;
> 
> "%s=%s&%s=%s" % tuple([urllib.quote(x) for x in params])
> 
>> Any suggestions?  (even if it's just "get over your hangup with 
>> wrapping the results in list()/tuple()" :)
> 
> Pretty much.  :-)
> 

...except for saving on a level of brackets or parens, since you can actually 
write

"%s=%s&%s=%s" % tuple(urllib.quote(x) for x in params)

instead of the above

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is crawling the stack "bad"? Why?

2008-02-25 Thread Boris Borcic
Paul Rubin wrote:
> Russell Warren <[EMAIL PROTECTED]> writes:
>> That is exactly where I started (creating my own request handler,
>> snagging the IP address and stashing it), but I couldn't come up with
>> a stash location that would work for a threaded server.
> 
> How about a dictionary indexed by by the thread name.

the threading.local class seems defined for that purpose, not that I've ever 
used it ;)

BB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Seemingly odd 'is' comparison.

2008-02-19 Thread Boris Borcic
Duncan Booth wrote:
> Boris Borcic <[EMAIL PROTECTED]> wrote:
>> Arnaud Delobelle wrote:
>>> Whereas when "3.0*1.0 is 3.0" is evaluated, *two* different float
>>> objects are put on the stack and compared (LOAD_CONST 3 / LOAD_CONST
>>> 1 / COMPARE_OP 8).  Therefore the result is False.
>> Looks good, but doesn't pass the sanity check ;) Consider
>>
>>>>> def f():
>>  return 3 is 3, 3*1 is 3
>>
>>>>> import dis
>>>>> dis.dis(f)
>>2   0 LOAD_CONST   1 (3)
>>3 LOAD_CONST   1 (3)
>>6 COMPARE_OP   8 (is)
>>9 LOAD_CONST   3 (3)
>>   12 LOAD_CONST   1 (3)
>>   15 COMPARE_OP   8 (is)
>>   18 BUILD_TUPLE  2
>>   21 RETURN_VALUE
>>>>> f()
>> (True, True)
>>
> 
> s/different/possibly different depending on implementation details/

"0 substitutions made", but whatever

s/on implementation details/on further implementations details/

> Arnaud's point remains valid: in the first comparison you can see that the 
> same object is used, in the second case all bets are off.

Sure, but the issue was to explain the strangeness that

(3.0 is 3.0)!=(3.0*1.0 is 3.0)

and I just pointed out - without drawing any conclusion - that a structurally 
identical explanation would "explain" the contrafactual (3 is 3)!=(3*1 is 3).

Best, BB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Seemingly odd 'is' comparison.

2008-02-19 Thread Boris Borcic
Arnaud Delobelle wrote:
> On Feb 13, 10:19 pm, Tobiah <[EMAIL PROTECTED]> wrote:
> print float(3.0) is float(3.0)
>> True
> print float(3.0 * 1.0) is float(3.0)
>> False
> 
> [You don't need to wrap your floats in float()]
> 
 def f():
> ... return 3.0 is 3.0, 3.0*1.0 is 3.0
> ...
 f()
> (True, False)
 import dis
 dis.dis(f)
>   2   0 LOAD_CONST   1 (3.0)
>   3 LOAD_CONST   1 (3.0)
>   6 COMPARE_OP   8 (is)
>   9 LOAD_CONST   3 (3.0)
>  12 LOAD_CONST   1 (3.0)
>  15 COMPARE_OP   8 (is)
>  18 BUILD_TUPLE  2
>  21 RETURN_VALUE
> 
> As you can see when "3.0 is 3.0" is evaluated the same float object is
> put on the stack twice so the 'is' comparison is True (LOAD_CONST 1 /
> LOAD_CONST 1 / COMPARE_OP 8).
> 
> Whereas when "3.0*1.0 is 3.0" is evaluated, *two* different float
> objects are put on the stack and compared (LOAD_CONST 3 / LOAD_CONST
> 1 / COMPARE_OP 8).  Therefore the result is False.

Looks good, but doesn't pass the sanity check ;) Consider

 >>> def f():
return 3 is 3, 3*1 is 3

 >>> import dis
 >>> dis.dis(f)
   2   0 LOAD_CONST   1 (3)
   3 LOAD_CONST   1 (3)
   6 COMPARE_OP   8 (is)
   9 LOAD_CONST   3 (3)
  12 LOAD_CONST   1 (3)
  15 COMPARE_OP   8 (is)
  18 BUILD_TUPLE  2
  21 RETURN_VALUE
 >>> f()
(True, True)

Cheers, BB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: flattening a dict

2008-02-19 Thread Boris Borcic
Duncan Booth wrote:

> In this particular case I think the lambda does contribute to the
> obfuscation. Yes, they are single expressions, but only because that
> have been contorted to become single expressions.  The first two return
> generators, so if you don't force them into a lambda you can write them
> out as for loops with yield. The last one is an if..else statement.

The key word is "become", and in this particular case the discussion thread is 
witness to the fact that it doesn't apply as you say. The three single 
expressions came about from a (misshappen, OK, but I never pretended otherwise) 
attempt to divide into pieces what was already a single expression in Arnaud's 
code while keeping in the spirit.

BTW, I have a particular issue with your statement :

 >> A lambda which is assigned directly to a variable is a bad code smell.

My problem is that I can't discuss its pure content with which I simply 
disagree, because that would legitimize its abstracted form with which I have 
the strongest issues, although largely OT.

Best, BB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: flattening a dict

2008-02-18 Thread Boris Borcic
Duncan Booth wrote:
> Boris Borcic <[EMAIL PROTECTED]> wrote:
> 
>> It is more elementary in the mathematician's sense, and therefore
>> preferable all other things being equal, imo. I've tried to split
>> 'gen' but I can't say the result is so much better.
>>
>> def flattendict(d) :
>>gen = lambda L : (x for M in exp(L) for x in rec(M))
>>exp = lambda L : (L+list(kv) for kv in L.pop().iteritems())
>>rec = lambda M : gen(M) if isinstance(M[-1],dict) else [M]
>>return dict((tuple(L[:-1]),L[-1]) for L in gen([d]))
> 
> Why, why, why, why are you using lambda here?

Because the 3 lambdas make manifest that they could be combined into a single 
expression and thus reveal that they replace a single expression.

> It only makes the code harder 
> to read

Matter of perceptions. I myself tend to find

def g(...) :
def f(x) :
return (whatever)
return y(f)

a bit hard to follow. So frankly I don't feel it betters anything to write

def flattendict(d) :
   def gen(L) :
   return (x for M in exp(L) for x in rec(M))

   def exp(L) :
   return (L+list(kv) for kv in L.pop().iteritems())

   def rec(M) :
   return gen(M) if isinstance(M[-1],dict) else [M]

   return dict((tuple(L[:-1]),L[-1]) for L in gen([d]))

But whatever to please you

Cheers, BB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: flattening a dict

2008-02-18 Thread Boris Borcic
Arnaud Delobelle wrote:
> On Feb 17, 4:03 pm, Boris Borcic <[EMAIL PROTECTED]> wrote:
>> George Sakkis wrote:
>>> On Feb 17, 7:51 am, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
>>>> BTW, I keep using the idiom itertools.chain(*iterable).  I guess that
>>>> during function calls *iterable gets expanded to a tuple.  Wouldn't it
>>>> be nice to have an equivalent one-argument function that takes an
>>>> iterable of iterables and return the 'flattened' iterable?
>>> Indeed; I don't have any exact numbers but I roughly use this idiom as
>>> often or more as the case where chain() takes a known fixed number of
>>> arguments. The equivalent function you describe is trivial:
>>> def chain2(iter_of_iters):
>>>   for iterable in iter_of_iters:
>>>  for i in iterable:
>>> yield i
>> or fwiw
>>
>> chainstar = lambda iters : (x for it in iters for x in it)
>>
>> - a form that better suggests how to inline it in the calling expression, if
>> applicable.
> 
> Indeed:
> 
> def flattendict(d):
> def gen(d, pfx=()):
> return (x for k, v in d.iteritems()
> for x in (gen(v, pfx+(k,)) if isinstance(v, dict)
>   else ((pfx+(k,), v),)))
> return dict(gen(d))
> 
> I don't know, I find the chain(*...) version more readable,

In this case I could concede that it is, although I find both forms overly
convoluted for easy reading.

> although
> this one is probably better.

It is more elementary in the mathematician's sense, and therefore preferable all
other things being equal, imo. I've tried to split 'gen' but I can't say the
result is so much better.

def flattendict(d) :
   gen = lambda L : (x for M in exp(L) for x in rec(M))
   exp = lambda L : (L+list(kv) for kv in L.pop().iteritems())
   rec = lambda M : gen(M) if isinstance(M[-1],dict) else [M]
   return dict((tuple(L[:-1]),L[-1]) for L in gen([d]))

For fun I've also written a (vaguely prologish) non-recursive generator-based 
version that exploits undocumented (but logical) behavior of list.extend

class iterstack(list) :
 __iter__ = lambda self : self
 def next(self) :
 while self :
 try :
 return self[-1].next()
 except StopIteration :
 self.pop()
 raise StopIteration

def flattendict(d,stk=[]) :
 res={}
 its=iterstack()
 its.extend(stk[-1].iteritems()
for stk[len(its)-1:] in chain([[d]],its)
if isinstance(stk[-1],dict)
or res.update([(stk.pop(),tuple(stk))[::-1]]))
 return res

(testing was minimal)

Challenge for who really has time to waste : replace the iterstack list 
subclass 
definition with a simple list + a generator expression inside flattendict.

Cheers, BB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: flattening a dict

2008-02-17 Thread Boris Borcic
George Sakkis wrote:
> On Feb 17, 7:51 am, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> 
>> BTW, I keep using the idiom itertools.chain(*iterable).  I guess that
>> during function calls *iterable gets expanded to a tuple.  Wouldn't it
>> be nice to have an equivalent one-argument function that takes an
>> iterable of iterables and return the 'flattened' iterable?
> 
> Indeed; I don't have any exact numbers but I roughly use this idiom as
> often or more as the case where chain() takes a known fixed number of
> arguments. The equivalent function you describe is trivial:
> 
> def chain2(iter_of_iters):
>   for iterable in iter_of_iters:
>  for i in iterable:
> yield i

or fwiw

chainstar = lambda iters : (x for it in iters for x in it)

- a form that better suggests how to inline it in the calling expression, if 
applicable.

Cheers, BB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: flattening a dict

2008-02-17 Thread Boris Borcic
Arnaud Delobelle wrote:
> 
> In Python you can do anything, even 

...pass the Turing test with a one-liner. Back after 9/11, when US patriotism 
was the rage, Python knew how to answer correctly the query

filter(lambda W : W not in 'ILLITERATE','BULLSHIT')

And Python 3.0 slated for next August offers it a chance to change its mind 
before the next elections...

Cheers, BB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An idea for fast function composition

2008-02-16 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
> On Feb 16, 3:47 pm, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
>> Hi all,
>>
>> Recently there was a thread about function composition in Python (and
>> this was probably not the first).  The fast way to create a
>> (anonymous) composite function
>>
>>  f1 o f2 o ... o fn
>>
>> in Python is via
>>
>>  lambda x: f1(f2(...fn(x)...)),
>>
>> but according to some this is neither the most compact nor the most
>> readable.  Below I define a 'compose' function such that the above can
>> be written
>>
>>  compose(f1, f2, , fn),
>>
>> the resulting function being as fast as the lambda version (or maybe
>> faster?).  'getcomposer' is a helper function (which in most cases
>> will amount to a dictionary lookup).
>>
>> --
>> def getcomposer(nfunc, _cache={}):
>>  "getcomposer(n) -> lambda f1, ..., fn:(lambda x: f1(...fn(x)...))"
>>  try:
>>  return _cache[nfunc]
>>  except KeyError:
>>  fnames = ['f%s' % i for i in range(nfunc)]
>>  call = ''.join('%s(' % f for f in fnames)
>>  args = ','.join(fnames)
>>  cstr = 'lambda %s:(lambda x:%sx%s)' % (args, call, ')'*nfunc)
>>  composer = _cache[nfunc] = eval(cstr)
>>  return composer
>>
>> def compose(*functions):
>>  "compose(f1, ..., fn) -> lambda x: f1(f2(...fn(x)...))"
>>  return getcomposer(len(functions))(*functions)
>>
>> # Test
>>
>> def double(x): return 2*x
>> def square(x): return x**2
>> def succ(x): return x+1
>>
>> f1 = compose(double, square, succ, float)
>> f2 = lambda x: double(square(succ(float(x
>>
>> def benchmark(f, n=100):
>>  from time import time
>>  from itertools import imap
>>  t0 = time()
>>  for _ in imap(f1, xrange(n)): pass
>>  t1 = time()
>>  return t1-t0
>>
>> print 'compose', benchmark(f1)
>> print 'lambda ', benchmark(f2)
>> --
>>
>> marigold:python arno$ python -i simple_compose.py
>> compose 1.84630298615
>> lambda  1.86365509033
>>  >>> import dis
>>  >>> dis.dis(f1)
>>1   0 LOAD_DEREF   0 (f0)
>>3 LOAD_DEREF   3 (f1)
>>6 LOAD_DEREF   1 (f2)
>>9 LOAD_DEREF   2 (f3)
>>   12 LOAD_FAST0 (x)
>>   15 CALL_FUNCTION1
>>   18 CALL_FUNCTION1
>>   21 CALL_FUNCTION1
>>   24 CALL_FUNCTION1
>>   27 RETURN_VALUE
>>  >>> dis.dis(f2)
>>   23   0 LOAD_GLOBAL  0 (double)
>>3 LOAD_GLOBAL  1 (square)
>>6 LOAD_GLOBAL  2 (succ)
>>9 LOAD_GLOBAL  3 (float)
>>   12 LOAD_FAST0 (x)
>>   15 CALL_FUNCTION1
>>   18 CALL_FUNCTION1
>>   21 CALL_FUNCTION1
>>   24 CALL_FUNCTION1
>>   27 RETURN_VALUE
>>
>> f1 and f2 are almost exaclty the same but array lookups (LOAD_DEREFs)
>> in f1 replace dictionary lookups (LOAD_GLOBALs) in f2.  A C version of
>> 'compose' could easily be written that doesn't require the use of a
>> python lambda-function (as created by 'getcomposer').
>>
>> --
>> Arnaud
> 
> def compose( funcs ):
>def reccompose( *args ):
>   return compose( funcs[:-1] )( funcs[-1]( *args ) ) if funcs else
> funcs[0]( *args )
>return reccompose


 >>> def compose( *funcs ):
def reccompose( *args ):
return compose( funcs[:-1] )( funcs[-1]( *args ) ) if funcs 
else funcs[0]( *args )
return reccompose

 >>> f3 = compose(double, square, succ, float)
 >>> import dis
 >>> dis.dis(f3)
   3   0 LOAD_DEREF   0 (funcs)
   3 JUMP_IF_FALSE   33 (to 39)
   6 POP_TOP
   7 LOAD_GLOBAL  0 (compose)
  10 LOAD_DEREF   0 (funcs)
  13 LOAD_CONST   1 (-1)
  16 SLICE+2
  17 CALL_FUNCTION1
  20 LOAD_DEREF   0 (funcs)
  23 LOAD_CONST   1 (-1)
  26 BINARY_SUBSCR
  27 LOAD_FAST0 (args)
  30 CALL_FUNCTION_VAR0
  33 CALL_FUNCTION1
  36 JUMP_FORWARD14 (to 53)
 >>   39 POP_TOP
  40 LOAD_DEREF   0 (funcs)
  43 LOAD_CONST   2 (0)
  46 BINARY_SUBSCR
  47 LOAD_FAST0 (args)
  50 CALL_FUNCTION_VAR0
 >>   53 RETURN_VALUE


Mmmhhh...

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ways to declare empty set variable

2008-02-16 Thread Boris Borcic
Steve Holden wrote:
> Boris Borcic wrote:
>> [EMAIL PROTECTED] wrote:
>>> ...Missing that, I think dict() and set() and
>>> tuple() and list() look better than using {} for the empty dict and
>>> {/} for the empty set and () for empty tuple (or {} for the empty dict
>>> and set() for the empty set).
>> The problem I have with them is in no way the looks, it is that they are not 
>> strictly equivalent as they imply dictionary lookups. Which shows in 
>> performance, eg
>>
>>  >>> import timeit
>>  >>> timeit.Timer('[]').timeit()
>> 0.22358344426456436
>>  >>> timeit.Timer('list()').timeit()
>> 0.54574505977715049
>>  >>> timeit.Timer('{}').timeit()
>> 0.21328632549668214
>>  >>> timeit.Timer('dict()').timeit()
>> 0.50557906102591232
>>
> But this is "performance" in the abstract. It's hardly going to matter 
> if you use it once in the initialization of your program, but if it 
> occurs deep inside a quadruply-nested loop that is executed 10^12 times 
> it may have an impact on performance.

In that case about 2.89 days, to be exact.

And I don't know about you, but when I write tight nested loops, I can't help 
opening an eye on not gratuitously wasting time in the innermost loops, well 
before I come to the point of measuring performance. And I find the case of [] 
vs list() (or {} vs dict()) to become a specific nuisance in that context.

> Before you have any code is exactly the *wrong* time to be considering 
> performance.

Yeah right, [] and {} are premature optimizations, one should always use list() 
or dict() unless one detains figures to justify the more exotic forms :)

> 
> regards
>   Steve

Cheers, BB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ways to declare empty set variable

2008-02-16 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
> 
> ...Missing that, I think dict() and set() and
> tuple() and list() look better than using {} for the empty dict and
> {/} for the empty set and () for empty tuple (or {} for the empty dict
> and set() for the empty set).

The problem I have with them is in no way the looks, it is that they are not 
strictly equivalent as they imply dictionary lookups. Which shows in 
performance, eg

 >>> import timeit
 >>> timeit.Timer('[]').timeit()
0.22358344426456436
 >>> timeit.Timer('list()').timeit()
0.54574505977715049
 >>> timeit.Timer('{}').timeit()
0.21328632549668214
 >>> timeit.Timer('dict()').timeit()
0.50557906102591232

Cheers, BB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to identify which numbers in a list are within each others' range

2008-02-08 Thread Boris Borcic
Boris Borcic wrote:
> Arnaud Delobelle wrote:
> (...)
>>
>> from itertools import chain
>>
>> def overlaps(lst):
>> bounds = chain(*(((x[1],i), (x[2], i)) for i,x in enumerate(lst)))
> 
> imho, this is a uselessly painful equivalent of
> 
>   bounds = ((x[k],i) for i,x in enumerate(lst) for k in (1,2))

even more readable :

 bounds = ((bound(x),i) for bound in (min,max) for i,x in 
enumerate(lst))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to identify which numbers in a list are within each others' range

2008-02-08 Thread Boris Borcic
Arnaud Delobelle wrote:
(...)
> 
> from itertools import chain
> 
> def overlaps(lst):
> bounds = chain(*(((x[1],i), (x[2], i)) for i,x in enumerate(lst)))

imho, this is a uselessly painful equivalent of

   bounds = ((x[k],i) for i,x in enumerate(lst) for k in (1,2))

Cheers, BB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: future multi-threading for-loops

2008-02-05 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
> On Feb 5, 12:26 am, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
>> On 5 feb, 03:46, [EMAIL PROTECTED] wrote:
>>
>>> Some timing stats: On Windows XP, Python 3.0a2.
(...)
>>> Are threads an OS bottleneck?
>> I don't understand your threading issues, but I would not use 3.0a2
>> for benchmarking anything (except benchmarking Python 3.0 itself).
>> AFAIK the developers are first trying to get it right and stable;
>> speed issues will be addressed later.
>>
>> --
>> Gabriel Genellina
> 
> Multi-threaded control flow is a worthwhile priority.

What he said is that you should apply the idea to the mixing of your thread of 
benchmarking with the thread of python development.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: find nearest time in datetime list

2008-01-30 Thread Boris Borcic
washakie wrote:
> Hello,
> 
> I have a list of datetime objects: DTlist, I have another single datetime
> object: dt, ... I need to find the nearest DTlist[i]  to the dt  is
> there a simple way to do this? There isn't necessarily an exact match... 
> 
> Thanks!
> .john
> 

min(DTlist,key=lambda date : abs(dt-date))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: optional static typing for Python

2008-01-28 Thread Boris Borcic
Wish you'd opted out of typing all that static.

BB

Russ P. wrote:
(...)
> 
> What is that supposed to mean?
> 
> Oh, I almost forgot. I'm supposed to sit here and be polite while
> clueless dolts make wise cracks. Sorry, but I haven't yet mastered
> that level of self-control.
> 
> I would just like to thank you for reminding me about what losers hang
> out perpetually on sites like this one, thinking they are in some kind
> of real "community." Being reminded of that will help prevent me from
> becoming such a loser myself. No, I didn't say that all the "regulars"
> here are losers, but you most certainly are.
> 
> Do you have a job? How about a life? Have you ever been "with" a
> woman? How in the world is it that every time I come to this site, I
> see your sorry ass hanging around yet again? I can't even imagine how
> "pointless" your life must be if you have that much time to spend
> "hanging around" on comp.lang.python -- and being an a--hole to boot.
> 
> Yeah, Lord have mercy -- on losers like you.
> 
> And thanks for reminding me to quit wasting so much time here. I've
> been doing way too much of that lately.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python self-evaluating strings

2008-01-27 Thread Boris Borcic
Now there's always that style :

 >>> print x

Traceback (most recent call last):
   File "", line 1, in 
 eval(x)
   File "", line 2
 Traceback (most recent call last):
  ^
SyntaxError: invalid syntax

 >>> eval(x)

Traceback (most recent call last):
   File "", line 1, in 
 eval(x)
   File "", line 2
 Traceback (most recent call last):
  ^
SyntaxError: invalid syntax
 >>>


Arnaud Delobelle wrote:
> Hi all,
> 
> An earlier post today got me thinking about "quines" (programs that 
> output themselves) in Python.  I tried to find some on the web but 
> didn't find many ([1]).  In particular I didn't find any that 
> corresponded to my instinctive (LISP-induced, probably) criterion:
> 
> def self_evaluating(s):
> "Return True if string s evaluates to itself"
> return s == eval(s)
> 
> Here is the result of my efforts so far:
> 
> 1. Starting from the classic idea (lambda x:x%x)('lambda x:x%x') I got 
> the following
> v=(lambda x:x%('"''""'+x+'"''""'))("""(lambda 
> x:x%%('"''""'+x+'"''""'))(%s)""")
> 
> 2. (Given that if s is a nonempty string, s*2 is a longer string).  
> Starting from the idea "%s %s" % (("%s %s",)*2) I got the following
> u="\"%s\" %% ((r\"%s\",)*2)" % ((r"\"%s\" %% ((r\"%s\",)*2)",)*2)
> 
> Most of my problems in creating these 2 was with finding a suitable way 
> of quoting strings that propagates well. Both u and v are one-liners.  
> I'm hoping for no funky line wrapping here.
> 
> Note: I'm not quoting the string as it makes no difference since they 
> evaluate to themselves:)
> 
> I'd like to know if anyone on the list has indulged in this 
> time-bending/mind-wasting activity before.  If so, it would be nice to 
> create a list of such expressions.
> 
> Quining's-better-than-ironing'ly yours
> 
> --Arnaud
> 
> [1] http://www.nyx.net/~gthompso/self_pyth.txt
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sudoku solver in Python ...

2008-01-25 Thread Boris Borcic

 >> http://norvig.com/sudoku.html
(...)
 > Below is the "winner" of my hacking for an as fast as
> possible 110% pure python (no imports at all!) comprehensive sudoku 
> solver under 50 LOCs, back in 2006. Performance is comparable to the 
> solver you advertize - numbers are slightly better, but platform 
> differences could easily absorb that -

More precise comparisons, after noting that on Norvig's pages there were 
contradictory performance numbers (obviously some 0 inserted or deleted). 
Running on my machine on the "top95" list of hard problems given on Norvig's 
page, my code takes about 7.5 ms/problem while Norvig's takes 42 ms/problem.

So that's a 82% reduction of running time.

Psyco.full() reduces the running time of my code to just about 4 ms/problem 
while it grows Norvig's to 47 ms/problem.

BB

> eg (not counting module 
> initialization and not using psyco) it takes 9.3 ms average on the "AI 
> escargot" problem linked to in Norvig's page, 5.6 ms/problem on some 
> standard "top1465" list of hard problems, and 3.4 ms/problem on the 
> first 1000 on some other "top5" list of relatively hard problems. 
> This on my 2GHz Intel Centrino '05 laptop. Psyco reduces times by about 
> 50%. Dropping performance requirements by half allows reducing LOC count 
> in proportion.
> 
> OTOH, the code although short is nearly unreadable, sorry; should 
> probably feature/comment it on some web page, like the two already 
> proposed in the thread. Will do if/for reviewer. Interface is calling 
> sudoku99(problem) with 'problem' a standard 81 character string with '0' 
> or '.' placeholder for unknowns. Returns same with values filled in.
> 
> Beware that although in practice it solved all well-formed 
> human-solvable problems I could find, it is not guaranteed to deal 
> properly (or even terminate?) for underdetermined problems or determined 
> problems that would require exploring choicepoints with more than 2 
> possibilities (if such exist).
> 
> Cheers, Boris
> 
> 
> 
> w2q = [[n/9,n/81*9+n%9+243,n%81+162,n%9*9+n/243*3+n/27%3+81]
>for n in range(729)]
> q2w = (z[1] for z in sorted((x,y) for y,s in enumerate(w2q) for x in s))
> q2w = map(set,zip(*9*[q2w]))
> w2q2w = [set(w for q in qL for w in q2w[q] if w!=w0) for w0,qL in 
> enumerate(w2q)]
> empty = set(range(729)).copy
> 
> def sudoku99(problem) :
> givens = set(9*j+int(k)-1 for j,k in enumerate(problem) if '0' ws=search(givens,[9]*len(q2w),empty())
> return ''.join(str(w%9+1) for w in sorted(ws))
> 
> def search(w0s,q2nw,free) :
> while 1 :
> while w0s:
> w0 = w0s.pop()
> for q in w2q[w0] : q2nw[q]=100
> wz = w2q2w[w0]&free
> free-=wz
> for w in wz :
> for q in w2q[w] :
> n = q2nw[q] = q2nw[q]-1
> if n<2 :
> ww,=q2w[q]&free
> w0s.add(ww)
> if len(free)==81 : return free
> thres = int((len(free)+52.85)/27.5)
> ix,vmax = -1,0
> try :
> while 1 :
> ix=q2nw.index(2,ix+1)
> for w0 in (q2w[ix]&free)-w0s :
> v = len(w2q2w[w0]&free)
> if v > vmax :
> ixmax = ix
> if v >=thres : break
> vmax = v
> w0s.add(w0)
> else : continue
> break
> except : pass
> w0,w1 = q2w[ixmax]&free
> try :
> w0s.clear()
> w0s.add(w0)
> return search(w0s,q2nw[:],free.copy())
> except ValueError :
> w0s.clear()
> w0s.add(w1)
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sudoku solver in Python ...

2008-01-24 Thread Boris Borcic
Shawn Milochik wrote:
> On Jan 23, 2008, at 10:02 PM, Derek Marshall wrote:
> 
>> This is just for fun, in case someone would be interested and because
>> I haven't had the pleasure of posting anything here in many years ...
>>
>> http://derek.marshall.googlepages.com/pythonsudokusolver
>>
>> Appreciate any feedback anyone who takes the time to have a look would
>> want to give ...
>>
>> Yours with-too-much-time-to-kill-on-the-train'ly,
>> Derek
>> --  
>> http://mail.python.org/mailman/listinfo/python-list
> 
> For those interested in this topic, here's another (much shorter) one:
> 
> http://norvig.com/sudoku.html
> 
> I'm not making any judgements here, though. If anyone takes the time  
> to actually review them, I'd be interested in hearing any educated  
> comparisons.
> 
> Shawn

So would I. Below is the "winner" of my hacking for an as fast as possible 110% 
pure python (no imports at all!) comprehensive sudoku solver under 50 LOCs, 
back 
in 2006. Performance is comparable to the solver you advertize - numbers are 
slightly better, but platform differences could easily absorb that - eg (not 
counting module initialization and not using psyco) it takes 9.3 ms average on 
the "AI escargot" problem linked to in Norwig's page, 5.6 ms/problem on some 
standard "top1465" list of hard problems, and 3.4 ms/problem on the first 1000 
on some other "top5" list of relatively hard problems. This on my 2GHz 
Intel 
Centrino '05 laptop. Psyco reduces times by about 50%. Dropping performance 
requirements by half allows reducing LOC count in proportion.

OTOH, the code although short is nearly unreadable, sorry; should probably 
feature/comment it on some web page, like the two already proposed in the 
thread. Will do if/for reviewer. Interface is calling sudoku99(problem) with 
'problem' a standard 81 character string with '0' or '.' placeholder for 
unknowns. Returns same with values filled in.

Beware that although in practice it solved all well-formed human-solvable 
problems I could find, it is not guaranteed to deal properly (or even 
terminate?) for underdetermined problems or determined problems that would 
require exploring choicepoints with more than 2 possibilities (if such exist).

Cheers, Boris



w2q = [[n/9,n/81*9+n%9+243,n%81+162,n%9*9+n/243*3+n/27%3+81]
for n in range(729)]
q2w = (z[1] for z in sorted((x,y) for y,s in enumerate(w2q) for x in s))
q2w = map(set,zip(*9*[q2w]))
w2q2w = [set(w for q in qL for w in q2w[q] if w!=w0) for w0,qL in 
enumerate(w2q)]
empty = set(range(729)).copy

def sudoku99(problem) :
 givens = set(9*j+int(k)-1 for j,k in enumerate(problem) if '0' vmax :
 ixmax = ix
 if v >=thres : break
 vmax = v
 w0s.add(w0)
 else : continue
 break
 except : pass
 w0,w1 = q2w[ixmax]&free
 try :
 w0s.clear()
 w0s.add(w0)
 return search(w0s,q2nw[:],free.copy())
 except ValueError :
 w0s.clear()
 w0s.add(w1)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why not 'foo = not f' instead of 'foo = (not f or 1) and 0'?

2008-01-23 Thread Boris Borcic

I am surprised nobody pointed out explicitely that

True==1 and False==0

so that for instance

5*(True+True)==10

and even (but implementation-dependent) :

5*(True+True) is 10

BB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: convert pdf to png

2007-12-26 Thread Boris Borcic
Carl K wrote:
> Rob Wolfe wrote:
>> Carl K <[EMAIL PROTECTED]> writes:
>>
>>> I need to take the take the pdf output from reportlab and create a
>>> preview image for a web page.  so png or something.  I am sure
>>> ghostscript will be involved. I am guessing PIL or ImageMagic ?
>>>
>>> all sugestions welcome.
>>
>> Did you try to use `reportPM` from rl_addons [1]_? This is an 
>> extension of the reportlab package.
>>
>> There is also PIL needed and on my linux box
>> I needed some additional fonts [2]_.
>>
>> And then I could create PNG directly from reportlab, e.g:
>>
>> 
>> from reportlab.graphics.shapes import Drawing, String
>> from reportlab.graphics import renderPM
>>
>> d = Drawing(400, 200)
>> d.add(String(150, 100, 'Hello World', fontSize=18))
>> renderPM.drawToFile(d, 'test.png', 'PNG')
>> 
>>
>> .. [1] http://www.reportlab.co.uk/svn/public/reportlab/trunk/rl_addons/
>> .. [2] http://www.reportlab.com/ftp/fonts/pfbfer.zip
> 
> This sounds like what I was looking for.  some how this got missed when 
> I poked around reportlab land.
> 
> Thanks much.
> 
> Carl K

Beware... AFAIK this is only a backend for reportlab graphics drawings, IOW it 
will render drawings and charts from the reportlab.graphics package but will 
not 
render reportlab pdf canvas.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Distinguishing attributes and methods

2007-12-19 Thread Boris Borcic
MonkeeSage wrote:
> what am I missing?

To my eyes, when you write:

 >I think it muddies the water to say that a.a() and a.a are the same
 >thing--obviously they are not. In the common case, the first is a
 >method, and the second is a variable.

What you are most obviously missing is what's shown by

b=a.a
b()

IOW I am tempted to make the prediction that you never use bound methods as 
values :)

Cheers, BB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: .NET and Python Integration Problem and PDF Library (Need Help and Suggestions)

2007-12-18 Thread Boris Borcic
Ravi Kumar wrote:
> - your opinion with available PDF Libraries, that are best among. Also
> which library to use for Windows server platform (there is limitation
> on installing long chain libraries that include other deep
> dependencies too). A pure python PDF library would be good, but which
> one.

Everybody will tell you "reportlab", but AFAIK the open-source kit does not 
provide manipulation of existing pdf file contents - "only" creation. Besides 
it's targeted at CPython and it isn't 100% clear it runs perfectly on other 
implementations; so have a look at itextsharp - it might better fit your needs 
if you decide to use IronPython.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting Excel time-format (hours since 1.1.1901)

2007-12-07 Thread Boris Borcic
Dirk Hagemann wrote:
> (3566839/24)/365 = 407   - YES I did this calculation too and was
> surprised. But if you try this out in MS Excel:
>  ="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0)  (put
> 3566839 in field A1 and switch the format of the result-fieldby right-
> click on it to the
> date format "14.3.01 13:30")
> 
> and then replace 3566839 by, let's say, "2", Excel calculates the date
> 01.10.1901 2:00 AM.

Hum, how can it be that Excel changes from YY to  year display format ? 
What 
does it display in the first case with a  display format ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Python" is not a good name, should rename to "Athon"

2007-12-06 Thread Boris Borcic
Piet van Oostrum wrote:
>> "Adrian Cherry" <[EMAIL PROTECTED]> (AC) wrote:
> 
>> AC> For that matter C# is no better, I thought that # was pronounced 
>> AC> hash, I still refer to C# as C-hash.
> 
> Are you musically illiterate?

Note that the notation for the note (!) isn't universal. French speakers for 
instance write that one do# and call it "do dièze". C# reads as unpronounceable 
linenoise to them.







-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Python" is not a good name, should rename to "Athon"

2007-12-05 Thread Boris Borcic
Russ P. wrote:
> If I had invented Python, I would have called it Newton or Euler,
> arguably the greatest scientist and mathematician ever, respectively.

This makes your taste on the matter dubious.

Such choice of a name implies either a claim to the fame of the Person that's 
devoid of substance. Or else a degree of carelessness about name capture that 
casts doubt on the quality of the language design. Or else a claim by the 
language designers/namers to themselves borrow from the Person while destining 
the language to grunt practitioners not expected to have any (further) need to 
refer to said Person.

Not serious - not even serious marketing, IMHO.







-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Python" is not a good name, should rename to "Athon"

2007-12-05 Thread Boris Borcic
Russ P. wrote:
> Speaking of stupid names, what does "C++" mean?

According to Special Relativity, C++ is a contradiction in terms :)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to write Regular Expression for recursive matching?

2007-11-26 Thread Boris Borcic
lisong wrote:
> Hi All,
> 
> I have problem to split a string like this:
> 
> 'abc.defg.hij.klmnop'
> 
> and I want to get all substrings with only one '.' in mid. so the
> output I expect is :
> 
> 'abc.defg', 'defg.hij', 'hij.klmnop'
> 
> a simple regular expression '\w+.\w' will only return:
> 'abc.defg', 'hij.klmnop'
> 
> is there a way to get 'defg.hij' using regular expression?
> 
> Thanks,
> 

Do you need it to be a regular expression ?

 >>> def f(s) :
ws = s.split('.')
return map('.'.join,zip(ws,ws[1:]))

 >>> f('abc.defg.hij.klmnop')
['abc.defg', 'defg.hij', 'hij.klmnop']

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-26 Thread Boris Borcic
ZeD wrote:
> Grant Edwards wrote:
> 
>> The user-defined xor is operates on "logical" boolean values.
>> The one in the operator module is a bitwise operator.
> 
> def xor(a, b):
> return bool(a) ^ bool(b)
> 
> seems more explicit to me.
> maybe, to make "more" explicit (too much, onestly...)
> 
> from operator import xor as bitwise_xor
> 
> def logical_xor(a, b):
> return bitwise_xor(bool(a), bool(b))
> 

I'd prefer   bool(a)!=bool(b)

or even  bool(a) is not bool(b)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-26 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
> def xor(a, b):
>   return a and not b or b and not a


 >>> from operator import xor
 >>> help(xor)
Help on built-in function xor in module operator:

xor(...)
 xor(a, b) -- Same as a ^ b.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-22 Thread Boris Borcic
Duncan Booth wrote:

> Nice, thank you.

Welcome.

> But why 'count(chunksize)' rather than just 'count()'? 

To number the first chunk 1, etc. using count() starts with 0. Matter of taste.

> Does it make a difference anywhere? And I'd recommend using // rather than 
> / otherwise it breaks if you do 'from __future__ import division':

Right.

> 
> def chunked(chunksize,f) :
>  from itertools import count,groupby
>  counter=count().next
>  return groupby(f,lambda _ : counter()//chunksize)
> 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-22 Thread Boris Borcic
> def chunked(chunksize,f) :
>  from itertools import count,groupby
>  counter=count(chunksize).next
>  return groupby(f,lambda _ : counter()/chunksize)

And more to the point, no "yield" for Alexy to mock :)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-22 Thread Boris Borcic
Duncan Booth wrote:
> import itertools
> def chunks(f, size):
> iterator = iter(f)
> def onechunk(line):
> yield line
> for line in itertools.islice(iterator, size-1):
> yield line
> for line in iterator:
> yield onechunk(line)

Quite simpler, and provides chunk# as well :)

def chunked(chunksize,f) :
 from itertools import count,groupby
 counter=count(chunksize).next
 return groupby(f,lambda _ : counter()/chunksize)

> 
> for chunk in chunks(open('chunks.py'), 3):
> for n, line in enumerate(chunk):
> print "%d:%s" % (n,line.rstrip())
> print "---"
> print "done"
> #eof
> -- end chunks.py 
> 
> Ths output when you run this is:
> 
> C:\Temp>chunks.py
> 0:import itertools
> 1:def chunks(f, size):
> 2:iterator = iter(f)
> ---
> 0:def onechunk(line):
> 1:yield line
> 2:for line in itertools.islice(iterator, size-1):
> ---
> 0:yield line
> 1:for line in iterator:
> 2:yield onechunk(line)
> ---
> 0:
> 1:for chunk in chunks(open('chunks.py'), 3):
> 2:for n, line in enumerate(chunk):
> ---
> 0:print "%d:%s" % (n,line.rstrip())
> 1:print "---"
> 2:print "done"
> ---
> 0:#eof
> ---
> done
> 
> Or change it to do:
> 
>for chunk in chunks(enumerate(open('chunks.py')), 3):
>for n, line in chunk:
> 
> and you get all lines numbered from 0 to 15 instead of resetting the 
> count each chunk.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding lowest value in dictionary of objects, how?

2007-11-19 Thread Boris Borcic
davenet wrote:
> Hi,
> 
> I'm new to Python and working on a school assignment.
> 
> I have setup a dictionary where the keys point to an object. Each
> object has two member variables. I need to find the smallest value
> contained in this group of objects.
> 
> The objects are defined as follows:
> 
> class Block:
>def __init__(self,addr):
>   self.addr = addr
>   self.age = 0
> 
> My dictionary is defined as:
>blocks = {}
> 
> I have added 1000 (will hold more after I get this working) objects. I
> need to find the lowest age in the dictionary. If there is more than
> one age that is lowest (like if several of them are '1', etc), then I
> can just pick randomly any that equal the lowest value.

 >>> help(min)
Help on built-in function min in module __builtin__:

min(...)
 min(iterable[, key=func]) -> value
 min(a, b, c, ...[, key=func]) -> value

 With a single iterable argument, return its smallest item.
 With two or more arguments, return the smallest argument.

 >>> def f(x) : return 3*x**2+10*x-4

 >>> min(f(x) for x in range(-100,100))
-12
 >>> min(range(-100,100), key=f)
-2
 >>> f(-2)
-12

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sorting contacts alphabetically, sorted by surname

2007-11-16 Thread Boris Borcic
Wow

J. Clifford Dyer wrote:
> On Fri, Nov 16, 2007 at 12:31:19PM +, Marie Hughes wrote regarding 
> sorting contacts alphabetically, sorted by surname:
>>HI
>>
>>I have to write a program that contains a text file in the following
>>format:
>>
>>AcademicPositionRoom Ext.   Email
>>Prof Marie Maguire  Head of
>>School  M9002    [EMAIL PROTECTED]
>>
>>And produce a output file where conatcts are sorted alphabetically-
>>sorted by surname.
>>
>>Has anyone any ideas.
> 
> Well, the first thing you need to do is develop a workable understanding of 
> how your data file is formatted.  What separates one field from another?  Is 
> it tab-delimited?  Does the field always start at a given column number?  
> Then you need to read each line of the file, and split the lines up according 
> to the format.  Save to a data structure, sort by last name (you'll have to 
> further parse the name to isolate this information), and reprint the results.
> 
> Depending on the details you uncover about the precise format of your data 
> file, you will find it helpful to read the documentation on string methods, 
> particularly s.split(), and sequence slicing: s[4:14].
> 
> Best of luck with it.
> 
> Cheers,
> Cliff

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sorting contacts alphabetically, sorted by surname

2007-11-16 Thread Boris Borcic
Marie Hughes wrote:
> HI
>  
> I have to write a program that contains a text file in the following format:
>  
> AcademicPositionRoom Ext.   Email
> Prof Marie Maguire  Head of 
> School  M9002    [EMAIL PROTECTED] 
> 
>  
> And produce a output file where conatcts are sorted alphabetically- 
> sorted by surname.
>  
> Has anyone any ideas.

You mean "write a program" or "copy a program" ?




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: implement random selection in Python

2007-11-16 Thread Boris Borcic
Boris Borcic wrote:
> Bruza wrote:
>> No. That does not solve the problem. What I want is a function
>>
>>   def randomPick(n, the_items):
>>
>> which will return n DISTINCT items from "the_items" such that
>> the n items returned are according to their probabilities specified
>> in the (item, pro) elements inside "the_items".
> 
> and in the initial post you wrote :
> 
>  > But how about the general case, for N > 1 and N < len(items)?
> 
> The problem is you need to make "the n items returned are according
> to their probabilities" more precise. "According to their probabilities" 
> implies 
> n INDEPENDENT picks, but this is contradictory with the n picks having to 
> provide DISTINCT results (what clearly constrains picks relative to each 
> other).
> 
> Of course there are obvious ways to combine the results of random choices of 
> single items to obtain a set like you want, but it is not obvious that they 
> are 
> equivalent.
> 
> This is the most simple-minded :
> 
> def randomPick(n, the_items) :
>  assert n  result = set()
>  while len(result)result.add(singlePick(the_items))
>  return sorted(result)
> 
> This is another (but it won't work with your version of singlePick as it is,
> although it would with that provided by the other posters) :
> 
> def randomPick(n, the_items) :
>  result = []
>  items = dict(the_items)
>  for k in range(n) :
>  pick = singlePick(items.items())
>  result.append(pick)
>  del items[pick]
>  return result
> 
> I would be surprised if they had exactly the same statistical properties, 
> IOW, 
> if they did fit the same exact interpretation of "according to their 
> probabilities".
> 
> 

yet another one, constructing a list of n-sets first, and then picking one;
like the other solutions, it doesn't optimize for repeated use.

def pickn(items,n) :
 "yields all n-sublists of (destructed) items"
 if n<=len(items) :
 if n :
 item = items.pop()
 for res in pickn(items[:],n) :
 yield res
 for res in pickn(items,n-1) :
 res.append(item)
 yield res
 else :
 yield []


def randomPick(n,the_items) :
 "randomly pick n distinct members of the_items"
 the_sets = list(pickn(the_items[:],n))
 divisor = len(the_sets)*float(n)/len(the_items)
 for k,s in enumerate(the_sets) :
 the_sets[k] = (sorted(who for who,_ in s),
int(1+sum(p for _,p in s)/divisor)) # mhh...
 return singlePick(the_sets)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: implement random selection in Python

2007-11-16 Thread Boris Borcic
Bruza wrote:
> No. That does not solve the problem. What I want is a function
> 
>   def randomPick(n, the_items):
> 
> which will return n DISTINCT items from "the_items" such that
> the n items returned are according to their probabilities specified
> in the (item, pro) elements inside "the_items".

and in the initial post you wrote :

 > But how about the general case, for N > 1 and N < len(items)?

The problem is you need to make "the n items returned are according
to their probabilities" more precise. "According to their probabilities" 
implies 
n INDEPENDENT picks, but this is contradictory with the n picks having to 
provide DISTINCT results (what clearly constrains picks relative to each other).

Of course there are obvious ways to combine the results of random choices of 
single items to obtain a set like you want, but it is not obvious that they are 
equivalent.

This is the most simple-minded :

def randomPick(n, the_items) :
 assert nhttp://mail.python.org/mailman/listinfo/python-list


Re: implement random selection in Python

2007-11-16 Thread Boris Borcic
Bruza wrote:
> No. That does not solve the problem. What I want is a function
> 
>   def randomPick(n, the_items):
> 
> which will return n DISTINCT items from "the_items" such that
> the n items returned are according to their probabilities specified
> in the (item, pro) elements inside "the_items".
> 
> If I understand correctly, both of the previous replies will output
> one item at a time independently, instead of returning n DISTINCT
> items at a time.
> 

from random import sample
randomPick = lambda n,its : sample(eval('+'.join('[%r]*%r'%p for p in its)),n)

hth :)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using python as primary language

2007-11-09 Thread Boris Borcic
Michel Albert wrote:
> 
> What I meant was that one should be able to "draw" a report template.
> Basically a graphical user interface for RML in this case. I
> personally would opt for writing RML or whatever code myself. But it's
> impossible to convice my boss. The dialog usually goes like this:
> 
> "So, did you find a click-and-play editor for reports" - "Not yet, but
> anyway, writing code is more flexible and easier to manage later on" -
> "Hmmm... but it's code!" - "Sure, but you only write it once for one
> report, you can easily re-use code-snippets, modifying the code does
> not require one additional program, you just use your text-editor of
> choice,..." - "Okay, but it's CODE!"
> 
> and this goes on forever. My boss seems to be allergic to writing code
> by hand. Which is very frustrating. I'm happy that Qt has the
> "designer", although it's very easy to code the GUI's too ;)
> 

Probably worth pointing out that a click-and-point editor for reports can't be 
both fully mimetic (as a GUI designer may be) and practical.

FWIW OpenOffice 2.3 added something of the sort. The kind of tools I'd expect 
to 
lead me to roadblocks. Now OpenOffice *does* allow scripting with python; but 
the couple times I looked into it, the specs&docs on the scripting interface 
scared me completly.

Good luck, BB



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Closure/binding problem or misunderstanding

2007-11-09 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
> If I run the following code:
> 
> class path(object):
> def __init__(self, **subdirs):
> for name, path in subdirs.iteritems():
> def getpath():
> return path
> setattr(self, name, getpath)
> 
> export = path(
> one = 'this is one',
> two = 'this is two',
> )
> 
> print "invoking", export.one, export.one()
> print "invoking", export.two, export.two()
> 
> I get this output:
> 
> invoking  this is one
> invoking  this is one
> 
> So there apparently are two definitions of the function "getpath" (the
> addresses are different, anyway), but they seem to have the same value
> for the binding of "path". It's not clear to me, after reading what I
> can find about python name binding, whether this is the expected
> behavior, or not (although I was surprised).
> 
> Can anyone enlighten me?

Yes this is the expected behavior. Both your getpath() functions return the 
current value of the single path variable at the time of invocation. Perhaps 
this would be the slightest bit clearer if subdir.iteritems() did not provide 
your items in swapped order (so that the returned values would be "this is 
two").

To create distinct bindings to distinct values of path at the distinct 
executions of "def getpath() :...", you should write
"def getpath(path=path) :..."

HTH, BB

> 
> Thanks,
> Bob Sidebotham
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to link different site-packages to different Python?

2007-11-09 Thread Boris Borcic
Davy wrote:
> Hi all,
> 
> I have Python 2.4 and 2.5 in my PC. And PythonWin is installed as IDE.
> 
> When I tried to use site-packages "Numpy", I installed the both
> version (i.e. for 2.4 and 2.5).
> 
> Python 2.4 and Numpy for it work together well.
> 
> But when I type "from numpy import *" in Python 2.5. It throw out an
> error indicate that the numpy library is link to Python 2.4 package?
> How to fix this problem?

Shouldn't occur if you properly installed python+pythonwin+numpy
from their respective installer once for each of python 2.4 and 2.5. You may use
the (Tools/Browse Pythonpath) and (Tools/Edit PythonPath) menu items in each of
Pythonwin 2.4 and 2.5 to sort things out. If your lazyness isn't caused by your
impatience, a possibility is to deinstall and then reinstall everything :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: permuting over nested dicts?

2007-11-08 Thread Boris Borcic
Boris Borcic wrote:
> Christian Meesters wrote:
>> Hoi,
>>
>> I have the following data structure (of variable size actually, to make
>> things simple, just that one):
>> d = {'a': {'x':[1,2,3], 'y':[4,5,6]},
>>  'b': {'x':[7,8,9], 'y':[10,11,12]}}
>> This can be read as a dict of possibilities: The entities 'a' and 'b' 
>> have
>> the parameters 'x' and 'y', each. And d['a']['x'] can be either 1 or 2 or
>> 3. Does anybody know a convenient (and fast) way to permute over all
>> possible nested dicts like
>> {'a': {'x':1, 'y':4},
>>  'b': {'x':7, 'y':10}}
>> and
>> {'a': {'x':2, 'y':4},
>>  'b': {'x':7, 'y':10}}
>> and so forth?
>>
>> Any link or snippet is appreciated.
>>
>> TIA
>> Christian
> 
> def cases(d) :
> import re
> bits = re.split('(\[.*?\])',repr(d))
> vv = [('_%s' % k, ' for _%s in %s' % (k,v))
> for k,v in enumerate(bits[1::2])]
> expr = [p+v for p,(v,_) in zip(bits[::2],vv)]+bits[-1:]+[v for _,v 
> in vv]
> return eval('(%s)' % ''.join(expr))

That's too ugly; here is a simpler version, same behav and caveats.

def cases(d) :
 import re
 d = repr(d)
 k,n = 1,1
 while n :
 d,n = re.subn('\\[(.*?)\\](.*)',
   '_%s \\2 for _%s in (\\1,)' % (k,k),
   d,1)
 k+=1
 return eval('('+d+')')

> 
> for t in cases({'a': {'x':[1,2,3], 'y':[4,5,6]},
>'b': {'x':[7,8,9], 'y':[10,11,12]}}) :
> print t
> 
> 
> {'a': {'y': 4, 'x': 1}, 'b': {'y': 10, 'x': 7}}
> {'a': {'y': 4, 'x': 1}, 'b': {'y': 10, 'x': 8}}
> {'a': {'y': 4, 'x': 1}, 'b': {'y': 10, 'x': 9}}
> {'a': {'y': 4, 'x': 1}, 'b': {'y': 11, 'x': 7}}
> {'a': {'y': 4, 'x': 1}, 'b': {'y': 11, 'x': 8}}
> {'a': {'y': 4, 'x': 1}, 'b': {'y': 11, 'x': 9}}
> {'a': {'y': 4, 'x': 1}, 'b': {'y': 12, 'x': 7}}
> {'a': {'y': 4, 'x': 1}, 'b': {'y': 12, 'x': 8}}
> {'a': {'y': 4, 'x': 1}, 'b': {'y': 12, 'x': 9}}
> {'a': {'y': 4, 'x': 2}, 'b': {'y': 10, 'x': 7}}
> 
> 
> Caveats : (1) assert eval(repr(d))==d
>   (2) no square bracket in either keys or values
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What about a Python Tree container?

2007-11-06 Thread Boris Borcic
Roc Zhou wrote:
> Hello,

Hello,

This post is too long. The right place for such is
as a python reciepe on ActiveState. BTW, I bet you can
find 3+ equivalents to you Tree type in the recorded
reciepes.

Regards, BB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble with for loop

2007-11-06 Thread Boris Borcic
Shriphani wrote:
> On Nov 6, 3:09 pm, Ant <[EMAIL PROTECTED]> wrote:
>> On Nov 6, 9:59 am, Shriphani <[EMAIL PROTECTED]> wrote:
>> ...
>>
>>> My main intention is to state that each of the variables namely a, b,
>>> c, ## can take value from 1 to 9.
>>> How do I go about this ?
>> It sounds like you are after something like:
>>
>> for var in (a, b, c, d, e, f):
>>assert var in [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>
>> but it's hard to tell without some more information from you on
>> exactly what you are trying to achieve.
> 
> I want to obtain a number whose first digit "a" is divisible by 1,
> 10*b +a is divisible by 2, 10^2*c + 10b + a is divisible by 3 and so
> on.

And so on ? up to how many digits ?

10^3 is divisible by 4 and 10^4 is divisible by 5 so that the conditions
on the fourth and fifth digits boil down to 10^2*c+10b+a being divisible
by 4 and 5 in supplement to 3, iow divisible by 60. This implies a==0 but you 
seem to say that a must be in [1, 2, 3, 4, 5, 6, 7, 8, 9].


> I hope my question is a bit clearer now.

Not really :)

> Thanks,
> Shriphani Palakodety
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List to Tuple and Tuple to List?

2007-11-06 Thread Boris Borcic
Davy wrote:
> Hi all,
> 
> I am curious about whether there is function to fransform pure List to
> pure Tuple and pure Tuple to pure List?
> 
> For example,
> 
> I have list L = [[1,2,3],[4,5,6]]
> something list2tuple() will have T=list2tuple(L)=((1,2,3),(4,5,6))
> 
> And the tuple2list()
> 
> Any suggestions are welcome!

D = { list : tuple, tuple : list }

F = lambda x : D[type(x)](map(F,x)) if type(x) in D else x

list2tuple = tuple2list = F
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to use list as key of dictionary?

2007-11-06 Thread Boris Borcic
You could also index on the repr() of your objects, which
is an immutable str value.

Davy wrote:
> And there may be more complex list(vector like 3 or 4 dimentional data
> structure), is there any easy method to tackle this problem?
> 
> Any suggestions are welcome!
> 
> Best regards,
> Davy
> 
> On Nov 6, 4:50 pm, Davy <[EMAIL PROTECTED]> wrote:
>> Hi Matimus and Boris,
>>
>> Thank you :)
>>
>> And a further question about vector above rank 1, how can I use it as
>> the key of dictionary?
>>
>> For example, if I have list like L=[[1,2,3],[4,5,6,7]],
>> Then I do L_tuple = tuple(L)>>> L_tuple = ([1,2,3],[4,5,6,7])
>>
>> But {L_tuple:'hello'} cause an error?
>>
>> Best regards,
>> Davy
>>
>> On Nov 6, 3:09 pm, Matimus <[EMAIL PROTECTED]> wrote:
>>
>>
>>
>>> On Nov 5, 10:53 pm, Davy <[EMAIL PROTECTED]> wrote:
 Hi all,
 We know that list cannot be used as key of dictionary. So, how to work
 around it?
 For example, there is random list like l=[1,323,54,67].
 Any suggestions are welcome!
 Best regards,
 Davy
>>> Use a tuple instead.
>> d = {}
>> d[tuple([1,2,3,4])] = 'hello world'
>> d
>>> {(1, 2, 3, 4): 'hello world'}>>> d[1,2,3,4]
>>> 'hello world'
>>> Matt- Hide quoted text -
>> - Show quoted text -
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to use list as key of dictionary?

2007-11-05 Thread Boris Borcic
Davy wrote:
> Hi all,
> 
> We know that list cannot be used as key of dictionary.

Yeah, but do we know why ?

> So, how to work
> around it?

That's a subsidiary question.

> 
> For example, there is random list like l=[1,323,54,67].

Don't use 1owercase L as a variab1e name, p1ease !

> 
> Any suggestions are welcome!

>>> {tuple([1,323,54,67]):666}
{(1, 323, 54, 67): 666}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new style class

2007-11-02 Thread Boris Borcic
gert wrote:
> Could not one of you just say "@staticmethod" for once damnit :)
> 

I did, did I not ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new style class

2007-11-02 Thread Boris Borcic
gert wrote:
[...]

 Why doesn't this new style class work in python 2.5.1 ?
>>> why should it ?
>> I don't know I thought it was supported from 2.2?
> 
> oops the code is like this but doesn't work
> 
> class Test(object):
> 
> def m1(self,v):
> return v
> 
> def m2(v):
> return v
> 
> if  __name__ == '__main__':
> gert = Test()
> print gert.m1('1')
> print Test.m2('2')
> 

You should put a '@staticmethod' decorator before your m2 method definition


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new style class

2007-11-02 Thread Boris Borcic
gert wrote:
> class Test(object):
> 
> def execute(self,v):
> return v
> 
> def escape(v):
> return v
> 
> if  __name__ == '__main__':
> gert = Test()
> print gert.m1('1')
> print Test.m2('2')
> 
> Why doesn't this new style class work in python 2.5.1 ?
> 

why should it ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help...

2007-11-02 Thread Boris Borcic
Ricardo Aráoz wrote:
 > Boris Borcic wrote:
 >> Ricardo Aráoz wrote:
 >>> Boris Borcic wrote:
 >>>> [EMAIL PROTECTED] wrote:
 >>>>> I want to create a program that I type in a word.
 >>>>>
 >>>>> for example...
 >>>>>
 >>>>> chaos
 >>>>>
 >>>>> each letter equals a number
 >>>>>
 >>>>> A=1
 >>>>> B=20
 >>>>>
 >>>>>  and so on.
 >>>>>
 >>>>> So Chaos would be
 >>>>>
 >>>>> C=13 H=4 A=1 O=7 S=5
 >>>>>
 >>>>> I want to then have those numbers
 >>>>> 13+4+1+7+5 added together to be 30.
 >>>>>
 >>>>> How can I do that?
 >>>>>
 >>>>> Also, just curious, but, how could I then have the 3 and 0 added
 >>>>> together to be 3?
 >>>>>
 >>>>> Please help me out.
 >>>>>
 >>>>> Thank you.
 >>>>>
 >>>>  >>> sum(dict(C=13,H=4,A=1,O=7,S=5)[_] for _ in 'CHAOS')
 >>>> 30
 >>>>  >>> sum(eval(ch) for ch in str(_))
 >>>> 3
 >>>>>> def sumToOneDigit(num) :
 >>>if num < 10 :
 >>>return num
 >>>else :
 >>>return sumToOneDigit(sum(int(i) for i in str(num)))
 >>>
 >>>
 >>>>>> sumToOneDigit(sum(ord(ch) for ch in 'chaos'.upper()))
 >>> 6
 >>>
 >>>
 >>>
 >>> HTH
 >> HTH what ?
 >
 >
 > HTH : Hope that helps
 >
 > Citing your post :

Not me, the OP "[EMAIL PROTECTED]".

 > """
 > Also, just curious, but, how could I then have the 3 and 0 added
 > together to be 3?
 > """
 >
 > you have the function "sumToOneDigit" that adds the digits of a number
 > till you get one digit (isn't that what you where curious about?)

I had provided a solution that conformed to the OP's 2 questions. Your 
non-conform addition simply proved that you hadn't bothered to read.

Or else you meant to read the OP's mind beyond what he specified; but then you 
should adress him, not me.

 >
 > And answering the main question : sum(ord(ch) for ch in 'chaos'.upper())
 > which is inside the "sumToOneDigit" funtion in my answer.

No, you did not adress the original questions.

My "hth what ?" was an invitation to
rectify. Sorry it wasn't enough for you, but the verbosity was probably worth
what you paid for it.

 >
 > Sorry if that is not enough for you, but the answer is probably worth
 > what you paid for it.
 >
 >
 >

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: setting and getting column in numpymatrix

2007-11-01 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
> hi
> i am looking for an efficient way to get a specific column of a
> numpy.matrix ..
> also i want to set  a column  of the matrix with a given set of
> values ..i couldn't find any methods for this in matrix doc..do i have
> to write   the functions from scratch?
> 
> TIA
> dn
> 

 >>> from numpy import matrix
 >>> x=matrix([[1,2,3],[4,5,6],[7,8,9]])
 >>> x[:,1]
matrix([[2],
 [5],
 [8]])
 >>> x[:,1].transpose()
matrix([[2, 5, 8]])
 >>> matrix([11,12,13]).transpose()
matrix([[11],
 [12],
 [13]])
 >>> x[:,1] = matrix([11,12,13]).transpose()
 >>> x
matrix([[ 1, 11,  3],
 [ 4, 12,  6],
 [ 7, 13,  9]])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help...

2007-11-01 Thread Boris Borcic
Ricardo Aráoz wrote:
> Boris Borcic wrote:
>> [EMAIL PROTECTED] wrote:
>>> I want to create a program that I type in a word.
>>>
>>> for example...
>>>
>>> chaos
>>>
>>> each letter equals a number
>>>
>>> A=1
>>> B=20
>>>
>>>  and so on.
>>>
>>> So Chaos would be
>>>
>>> C=13 H=4 A=1 O=7 S=5
>>>
>>> I want to then have those numbers
>>> 13+4+1+7+5 added together to be 30.
>>>
>>> How can I do that?
>>>
>>> Also, just curious, but, how could I then have the 3 and 0 added
>>> together to be 3?
>>>
>>> Please help me out.
>>>
>>> Thank you.
>>>
>>  >>> sum(dict(C=13,H=4,A=1,O=7,S=5)[_] for _ in 'CHAOS')
>> 30
>>  >>> sum(eval(ch) for ch in str(_))
>> 3
> 
> 
>>>> def sumToOneDigit(num) :
>   if num < 10 :
>   return num
>   else :
>   return sumToOneDigit(sum(int(i) for i in str(num)))
> 
>   
>>>> sumToOneDigit(sum(ord(ch) for ch in 'chaos'.upper()))
> 6
> 
> 
> 
> HTH

HTH what ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: permuting over nested dicts?

2007-11-01 Thread Boris Borcic
Christian Meesters wrote:
> Hoi,
> 
> I have the following data structure (of variable size actually, to make
> things simple, just that one):
> d = {'a': {'x':[1,2,3], 'y':[4,5,6]},
>  'b': {'x':[7,8,9], 'y':[10,11,12]}}
> This can be read as a dict of possibilities: The entities 'a' and 'b' have
> the parameters 'x' and 'y', each. And d['a']['x'] can be either 1 or 2 or
> 3. Does anybody know a convenient (and fast) way to permute over all
> possible nested dicts like
> {'a': {'x':1, 'y':4},
>  'b': {'x':7, 'y':10}}
> and
> {'a': {'x':2, 'y':4},
>  'b': {'x':7, 'y':10}}
> and so forth?
> 
> Any link or snippet is appreciated.
> 
> TIA
> Christian

def cases(d) :
 import re
 bits = re.split('(\[.*?\])',repr(d))
 vv = [('_%s' % k, ' for _%s in %s' % (k,v))
 for k,v in enumerate(bits[1::2])]
 expr = [p+v for p,(v,_) in zip(bits[::2],vv)]+bits[-1:]+[v for _,v in vv]
 return eval('(%s)' % ''.join(expr))

for t in cases({'a': {'x':[1,2,3], 'y':[4,5,6]},
'b': {'x':[7,8,9], 'y':[10,11,12]}}) :
print t


{'a': {'y': 4, 'x': 1}, 'b': {'y': 10, 'x': 7}}
{'a': {'y': 4, 'x': 1}, 'b': {'y': 10, 'x': 8}}
{'a': {'y': 4, 'x': 1}, 'b': {'y': 10, 'x': 9}}
{'a': {'y': 4, 'x': 1}, 'b': {'y': 11, 'x': 7}}
{'a': {'y': 4, 'x': 1}, 'b': {'y': 11, 'x': 8}}
{'a': {'y': 4, 'x': 1}, 'b': {'y': 11, 'x': 9}}
{'a': {'y': 4, 'x': 1}, 'b': {'y': 12, 'x': 7}}
{'a': {'y': 4, 'x': 1}, 'b': {'y': 12, 'x': 8}}
{'a': {'y': 4, 'x': 1}, 'b': {'y': 12, 'x': 9}}
{'a': {'y': 4, 'x': 2}, 'b': {'y': 10, 'x': 7}}


Caveats : (1) assert eval(repr(d))==d
   (2) no square bracket in either keys or values
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iteration for Factorials

2007-10-30 Thread Boris Borcic
Py-Fun wrote:
> I'm stuck trying to write a function that generates a factorial of a
> number using iteration and not recursion.  Any simple ideas would be
> appreciated.
> 

fact = lambda n : len(map([1].__imul__,range(1,n+1))[0])

hth :)

BB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need some help...

2007-10-30 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
> I want to create a program that I type in a word.
> 
> for example...
> 
> chaos
> 
> each letter equals a number
> 
> A=1
> B=20
> 
>  and so on.
> 
> So Chaos would be
> 
> C=13 H=4 A=1 O=7 S=5
> 
> I want to then have those numbers
> 13+4+1+7+5 added together to be 30.
> 
> How can I do that?
> 
> Also, just curious, but, how could I then have the 3 and 0 added
> together to be 3?
> 
> Please help me out.
> 
> Thank you.
> 

 >>> sum(dict(C=13,H=4,A=1,O=7,S=5)[_] for _ in 'CHAOS')
30
 >>> sum(eval(ch) for ch in str(_))
3
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >