Invoke a superclass method from a subclass constructor

2011-09-11 Thread Kayode Odeyemi
Hello friends,

An instance of my subclass doesn't invoke its superclass method, except when
it is referenced
directly.

Here is what I mean:

>>> class A(object):
... def log(self, module):
... return str('logged')
...

>>> class B(A):
... def __init__(self, module):
... self.module = A().log(module)
...
>>> c = B('system')
>>> # I expect 'logged' to be printed here
>>> print c.log('system') # why do I have to do this?
>>> 'logged'

Why do I have to make a call to c.log before log() method can be invoked?

My reasoning is such that since I have passed the log() method to B's
constructor, an instance
of B should invoke A's log() method.

What could I be missing in class A or B to have this working as expected?
-- 
Odeyemi 'Kayode O.
http://www.sinati.com. t: @charyorde
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Invoke a superclass method from a subclass constructor

2011-09-11 Thread Thomas Jollans
On 11/09/11 10:18, Kayode Odeyemi wrote:
> Hello friends,
> 
> An instance of my subclass doesn't invoke its superclass method, except
> when it is referenced
> directly. 
> 
> Here is what I mean:
> 
 class A(object):
> ... def log(self, module):
> ... return str('logged')
> ...
> 
 class B(A):
> ... def __init__(self, module):
> ... self.module = A().log(module)
> ...
 c = B('system')
 # I expect 'logged' to be printed here
 print c.log('system') # why do I have to do this?
 'logged'
> 
> Why do I have to make a call to c.log before log() method can be invoked?
> 
> My reasoning is such that since I have passed the log() method to B's
> constructor, an instance
> of B should invoke A's log() method.
> 
> What could I be missing in class A or B to have this working as expected?

It is working:

>>> class A(object):
... def log (self, module):
... return str ('logged')
...
>>> class B(A):
... def __init__(self, module):
... self.module = A().log(module)
...
>>> c = B('system')
>>> c.module
'logged'

In B's constructor, you create a new instance of A (a pointless
excersise - you already have an instance of A, "self"), call its log()
method, and store the return value of that method in the attribute "module".

This is how you'd usually call a superclass's method:

>>> class B2(A):
... def __init__(self, module):
... # This is the way to call a superclass method:
... self.log (module)
...
>>> c2 = B2 ('system')
>>>

That's what inheritance is. If B is derived from A, any B *is* also an A.

Now, something that might be closer to what you're actually heading for,
to think about. Please note that I'm using Python 3: explicitly deriving
a class from object is no longer necessary, and the "super" function is
now simpler. If you want to use Python 2, I'll leave looking up how to
use its "super" function as an excersise to the reader.

>>> class ModuleLogger:
... def __init__(self, module):
... self.module = module
... print ('module logged: {0}'.format (module))
...
>>> class Foo (ModuleLogger):
... def __init__(self, module):
... # calling a superclass constructor here, in Python 3 syntax:
... super().__init__(module)
...
>>> f = Foo ('system')
module logged: system
>>>

Using super() is always necessary when calling a superclass' method that
is also implemented in the subclass - self.__init__ would just invoke
the Foo constructor, you need super() to get to the ModuleLogger
constructor.

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


Re: optionparse: how to add a line break to the help text

2011-09-11 Thread Tim Chase

On 09/10/11 22:07, Gelonida N wrote:

http://bytes.com/topic/python/answers/734066-how-output-newline-carriage-return-optparse


It works (of course ;-) ) like a charm. Good to know, that I'm
not the only one who want's to structure the help text a
little nicer.

Considering, that you posted the snippet in 2007 and this is
very probably a reocurring problem for any slighty more
complicated help text it is really a pity, that it did not
become of part of the standard optparse library :-(


Even at the time, the optparse library wasn't readily patchable 
as the inline documentation gave some dire warning about "don't 
edit this directly, as this file is generated from some other 
source"—I never was able to dig up that source to patch against.


As Ben Finney replied, optparse is now deprecated, replaced in 
part by argparse. Unfortunately, argparse wasn't backported to 
the standard library for earlier 2.x series (I think it became 
available in 2.7, and may run in earlier versions if manually 
added like I had to do on my Debian Py2.6 install). But that 
makes it hard for those of us who want to use a built-in 
option-parsing library across a wide variety of Python versions. 
 I don't strongly care which I use except that I want it to be 
broadly available with minimal fuss.


-tkc


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


Re: Invoke a superclass method from a subclass constructor

2011-09-11 Thread Kayode Odeyemi
On Sun, Sep 11, 2011 at 11:41 AM, Thomas Jollans  wrote:

> On 11/09/11 10:18, Kayode Odeyemi wrote:
> > Hello friends,
> >
> > An instance of my subclass doesn't invoke its superclass method, except
> > when it is referenced
> > directly.
> >
> > Here is what I mean:
> >
>  class A(object):
> > ... def log(self, module):
> > ... return str('logged')
> > ...
> >
>  class B(A):
> > ... def __init__(self, module):
> > ... self.module = A().log(module)
> > ...
>  c = B('system')
>  # I expect 'logged' to be printed here
>  print c.log('system') # why do I have to do this?
>  'logged'
> >
> > Why do I have to make a call to c.log before log() method can be invoked?
> >
> > My reasoning is such that since I have passed the log() method to B's
> > constructor, an instance
> > of B should invoke A's log() method.
> >
> > What could I be missing in class A or B to have this working as expected?
>
> It is working:
>
> >>> class A(object):
> ... def log (self, module):
> ... return str ('logged')
> ...
> >>> class B(A):
> ... def __init__(self, module):
> ... self.module = A().log(module)
> ...
> >>> c = B('system')
> >>> c.module
> 'logged'
>
> Why do you have to do c.module? I'm expecting an output just by creating an
instance of B.
Could this be a limitation in Py2+?


> In B's constructor, you create a new instance of A (a pointless
> excersise - you already have an instance of A, "self"), call its log()
> method, and store the return value of that method in the attribute
> "module".
>
> This is how you'd usually call a superclass's method:
>
> >>> class B2(A):
> ... def __init__(self, module):
> ... # This is the way to call a superclass method:
> ... self.log (module)
> ...
> >>> c2 = B2 ('system')
> >>>
>
> That's what inheritance is. If B is derived from A, any B *is* also an A.
>
> Now, something that might be closer to what you're actually heading for,
> to think about. Please note that I'm using Python 3: explicitly deriving
> a class from object is no longer necessary, and the "super" function is
> now simpler. If you want to use Python 2, I'll leave looking up how to
> use its "super" function as an excersise to the reader.
>
> >>> class ModuleLogger:
> ... def __init__(self, module):
> ... self.module = module
> ... print ('module logged: {0}'.format (module))
> ...
> >>> class Foo (ModuleLogger):
> ... def __init__(self, module):
> ... # calling a superclass constructor here, in Python 3 syntax:
> ... super().__init__(module)
> ...
> >>> f = Foo ('system')
> module logged: system
> >>>
>
> I'm on Py2.7.

class ModuleLogger is not the same as class A (the one I'm using as an
example). I need the log()
method to be an instance of class A. I don't want it declared in class A
constructor because I don't
want to have access to it when class A is instantiated.

Using super() is always necessary when calling a superclass' method that
> is also implemented in the subclass - self.__init__ would just invoke
> the Foo constructor, you need super() to get to the ModuleLogger
> constructor.
>

Well, I did try using super(), but I got this:
>>> class B(A):
... def __init__(self, module):
... super(A, self).log('system')
...
>>> c = B('module')
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in __init__
AttributeError: 'super' object has no attribute 'log'

I hope a reader on Py2+ can help with this.

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



-- 
Odeyemi 'Kayode O.
http://www.sinati.com. t: @charyorde
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Invoke a superclass method from a subclass constructor

2011-09-11 Thread Thomas Jollans
On 11/09/11 13:17, Kayode Odeyemi wrote:
> On Sun, Sep 11, 2011 at 11:41 AM, Thomas Jollans  > wrote:
> 
> It is working:
> 
> >>> class A(object):
> ... def log (self, module):
> ... return str ('logged')
> ...
> >>> class B(A):
> ... def __init__(self, module):
> ... self.module = A().log(module)
> ...
> >>> c = B('system')
> >>> c.module
> 'logged'
> 
> Why do you have to do c.module? I'm expecting an output just by creating
> an instance of B.
> Could this be a limitation in Py2+?
>  

I believe I already answered that question. You quoted my answer
directly below your question:

> 
> In B's constructor, you create a new instance of A (a pointless
> excersise - you already have an instance of A, "self"), call its log()
> method, and store the return value of that method in the attribute
> "module".
> 
> This is how you'd usually call a superclass's method:
> 
> >>> class B2(A):
> ... def __init__(self, module):
> ... # This is the way to call a superclass method:
> ... self.log (module)
> ...
> >>> c2 = B2 ('system')
> >>>
> 
> That's what inheritance is. If B is derived from A, any B *is* also
> an A.
> 
> Now, something that might be closer to what you're actually heading for,
> to think about. Please note that I'm using Python 3: explicitly deriving
> a class from object is no longer necessary, and the "super" function is
> now simpler. If you want to use Python 2, I'll leave looking up how to
> use its "super" function as an excersise to the reader.
> 
> >>> class ModuleLogger:
> ... def __init__(self, module):
> ... self.module = module
> ... print ('module logged: {0}'.format (module))
> ...
> >>> class Foo (ModuleLogger):
> ... def __init__(self, module):
> ... # calling a superclass constructor here, in Python 3 syntax:
> ... super().__init__(module)
> ...
> >>> f = Foo ('system')
> module logged: system
> >>>
> 
> I'm on Py2.7.
> 
> class ModuleLogger is not the same as class A (the one I'm using as an
> example). I need the log()
> method to be an instance of class A. I don't want it declared in class A
> constructor because I don't
> want to have access to it when class A is instantiated.

Then do it differently. I was merely offering an example that I hoped
might help you acheive your goals.

> 
> Using super() is always necessary when calling a superclass' method that
> is also implemented in the subclass - self.__init__ would just invoke
> the Foo constructor, you need super() to get to the ModuleLogger
> constructor.
> 
> 
> Well, I did try using super(), but I got this: 
 class B(A):
> ... def __init__(self, module):
> ... super(A, self).log('system')
> ...
 c = B('module')
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 3, in __init__
> AttributeError: 'super' object has no attribute 'log'
> 
> I hope a reader on Py2+ can help with this.

If you'd read my previous response carefully, you'd know that in this
case, you don't need super(), and you'd also know how to use the
superclass' method.


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


Re: Deadlock problem using multiprocessing

2011-09-11 Thread Kushal Kumaran
2011/9/11 蓝色基因 :
> This is my first touch on the multiprocessing module, and I admit not
> having a deep understanding of parallel programming, forgive me if
> there's any obvious error. This is my test code:
>
> # deadlock.py
>
> import multiprocessing
>
> class MPTask:
>        def __init__(self):
>                self._tseq= range(10)   # task sequence
>                self._pool= multiprocessing.Pool(2)     # process pool
>        def _exe(self, num):
>                return num**2
>        def run(self):
>                result= self._pool.map_async(self._exe, self._tseq)
>                return result.get()
>
> result= MPTask().run()
> print(result)
>
> And seemingly it creates a deadlock, I have to manually kill the
> processes in the system monitor, yet it would be OK if the _exe()
> function was defined outside the MPTask class:
>
> # no_deadlock.py
> import multiprocessing
>
> def _exe(num):
>        return num**2
>
> class MPTask:
>        def __init__(self):
>                self._tseq= range(10)   # task sequence
>                self._pool= multiprocessing.Pool(2)     # process pool
>        def run(self):
>                result= self._pool.map_async(_exe, self._tseq)
>                return result.get()
>
> result= MPTask().run()
> print(result)
>
> This would give the correct answer without any deadlock. My questions:
>
> 1. Why is this, where did the deadlock come from?
>
> 2. Besides, is there any material I can refer to about how to avoid
> deadlocks when using multiple processes in the program?
>

I get this exception when I run the first program:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python3.1/threading.py", line 516, in _bootstrap_inner
self.run()
  File "/usr/lib/python3.1/threading.py", line 469, in run
self._target(*self._args, **self._kwargs)
  File "/usr/lib/python3.1/multiprocessing/pool.py", line 231, in _handle_tasks
put(task)
  File "/usr/lib/python3.1/pickle.py", line 1349, in dumps
Pickler(f, protocol, fix_imports=fix_imports).dump(obj)
_pickle.PicklingError: Can't pickle : attribute lookup
builtins.method failed

There is no deadlock.  You are hitting this problem:
http://stackoverflow.com/questions/1816958/cant-pickle-type-instancemethod-when-using-pythons-multiprocessing-pool-map

-- 
regards,
kushal
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Invoke a superclass method from a subclass constructor

2011-09-11 Thread Dave Angel

On 01/-10/-28163 02:59 PM, Kayode Odeyemi wrote:

Hello friends,

An instance of my subclass doesn't invoke its superclass method, except when
it is referenced
directly.

Here is what I mean:


class A(object):

... def log(self, module):
... return str('logged')
...


class B(A):

... def __init__(self, module):
... self.module = A().log(module)
...

c = B('system')
# I expect 'logged' to be printed here
print c.log('system') # why do I have to do this?
'logged'

Why do I have to make a call to c.log before log() method can be invoked?

My reasoning is such that since I have passed the log() method to B's
constructor, an instance
of B should invoke A's log() method.

What could I be missing in class A or B to have this working as expected?

What makes you think that A.log() was not invoked???

You have no print statement, so you can't tell that way.  All the method 
does is to modify a temporary object of type A, so you can't tell that way.


Perhaps you mean to write
  self.module = A.log(self, module)

So that the return value could do some good.

DaveA

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


Re: Idioms combining 'next(items)' and 'for item in items:'

2011-09-11 Thread Tim Chase

On 09/10/11 14:36, Terry Reedy wrote:

1. Process first item of an iterable separately.

A traditional solution is a flag variable that is tested for each item.

first = True

for item in iterable:
if first:
  
  first = False
else:
  

(I have seen code like this posted on this list several times, including
today.)

Better, to me, is to remove the first item *before* the loop.

items = iter(iterable)



I like to use this one for processing CSV files where I need to 
clean up the headers:


  r = csv.reader(f)
  headers = r.next()
  header_map = dict(
(header.strip().upper(), i)
for i, header
in enumerate(headers)
)
  for row in r:
item = lambda s: row[header_map[s]].strip()
thing = item("THING")
whatever = item("WHATEVER")

It's mostly like a DictReader, but it isn't as sensitive to the 
spaces/capitalization that clients love to mess with.


-tkc



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


Re: recursive algorithm for balls in numbered boxes

2011-09-11 Thread Peter Otten
Dr. Phillip M. Feldman wrote:

> I've written a recursive class that creates an iterator to solve a general
> formulation of the combinatorics problem known as "balls in numbered
> boxes"
> (also known as "indistinguishable balls in distinguishable boxes").  The
> code has been extensively tested and appears to work, but isn't terribly
> elegant.  Any suggestions about how to improve it will be appreciated.
 

Does the following do what you want?

>>> from itertools import product
>>> def binb(balls, boxsizes):
... return (fill for fill in product(*[range(bs+1) for bs in boxsizes]) 
if sum(fill) == balls)
...
>>> for item in binb(10, [4, 3, 2, 1, 2]):
... print item
...
(2, 3, 2, 1, 2)
(3, 2, 2, 1, 2)
(3, 3, 1, 1, 2)
(3, 3, 2, 0, 2)
(3, 3, 2, 1, 1)
(4, 1, 2, 1, 2)
(4, 2, 1, 1, 2)
(4, 2, 2, 0, 2)
(4, 2, 2, 1, 1)
(4, 3, 0, 1, 2)
(4, 3, 1, 0, 2)
(4, 3, 1, 1, 1)
(4, 3, 2, 0, 1)
(4, 3, 2, 1, 0)

If so, your implementation misses a few configurations:

>>> from balls_in_numbered_boxes import balls_in_numbered_boxes as bb
>>> for item in bb(10, [4, 3, 2, 1, 2]):
... print item
...
[4 3 2 1 0]
[3 3 2 1 1]
[2 3 2 1 2]

> Also, I'd like to get this functionality into the Python's `itertools`
> module (the present set of combinatorics functions in `itertools` does not
> include "balls in boxes").  Does anyone know whom I should contact about
> this?

Basically you have to convince Raymond Hettinger. I recommend that you post 
your suggestion on python-ideas for a general discussion rather than 
approaching him directly.


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


Re: Doctest failing

2011-09-11 Thread Tigerstyle
On 10 Sep, 19:59, Terry Reedy  wrote:
> On 9/10/2011 7:20 AM, Tigerstyle wrote:
>
> > Hi guys.
>
> > I'm strugglin with some homework stuff and am hoping you can help me
> > out here.
>
> We appreciate you saying so instead of hiding that this is homework.
>
>
>
>
>
>
>
>
>
> > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on')
>
> > def book_title(title):
> >      """ Takes a string and returns a title-case string.
> >      All words EXCEPT for small words are made title case
> >      unless the string starts with a preposition, in which
> >      case the word is correctly capitalized.
> >      >>>  book_title('DIVE Into python')
> >      'Dive into Python'
> >      >>>  book_title('the great gatsby')
> >      'The Great Gatsby'
> >      >>>  book_title('the WORKS OF AleXANDer dumas')
> >      'The Works of Alexander Dumas'
> >      """
> >      new_title = []
> >      title_split = title.strip().lower().split()
> >      for word in title_split:
> >          if title_split[0] in small_words:
> >              new_title.append(word.title())
> >          elif word in small_words:
> >              new_title.append(word.lower())
> >          else:
> >              new_title.append(word.title())
>
> The key issue is that you want to treat the first word one way (.title
> it) and the rest differently (conditionally .title or not) . So
> immediately separate the first from the rest and then process each.
> There are at least three ways to do the split. Perhaps I should stop
> with this hint, and certainly you should think a bit before reading
> further, but here is what I consider to be the most elegant 3.2 code.
> .
> ,
> ,
> ,
> .
> .
> .
>      first, *rest = title.strip().lower().split()
>      new_title = [first.title()]
>      for word in rest:
>          if word not in small_words:
>              word = word.title()
>          new_title.append(word)
>
> >      return(' '.join(new_title))
>
> doctest.testmod() now passes (there is no 'refactory' here)
>
> > def _test():
> >      import doctest, refactory
> >      return doctest.testmod(refactory)
> > if __name__ == "__main__":
> >      _test()
>
> --
> Terry Jan Reedy

Thank you Terry,

I went for this solution as it was the easiest for me to understand
and comment myself keeping in mind what level I am at right now.
Thanks a ton to everyone for sharing so much information and making it
easy to read and understand your thoughts. This was surely very very
educating read the replies from so many talented people.

Thanks and looking forward to hanging around here more :)

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


Re: Idioms combining 'next(items)' and 'for item in items:'

2011-09-11 Thread Peter Otten
Terry Reedy wrote:

> 3. Process the items of an iterable in pairs.
> 
> items = iter(iterable)
> for first in items:
>  second = next(items)
>  
> 
> This time, StopIteration is raised for an odd number of items. Catch and 
> process as desired. One possibility is to raise ValueError("Iterable 
> must have an even number of items").
 
Another way is zip-based iteration:

(a) silently drop the odd item

items = iter(iterable)
for first, second in zip(items, items): # itertools.izip in 2.x
   ...

(b) add a fill value

for first, second in itertools.zip_longest(items, items):
...

(c) raise an exception

Unfortunately there is no zip_exc() that guarantees that all iterables are 
of the same "length", but I've written a recipe some time ago

http://code.activestate.com/recipes/497006-zip_exc-a-lazy-zip-that-ensures-
that-all-iterables/

that achieves near-C speed.

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


Re: import packet.module without importing packet.__init__ ?

2011-09-11 Thread Gelonida N
Hi Steven,

Thanks again for your answer.


On 09/11/2011 06:51 AM, Steven D'Aprano wrote:
> Gelonida N wrote:

> 
> In your example, you stated that kitchen explicitly imports kitchen.pans and
> kitchen.knives. So in that case, take it up with the designer of the
> kitchen package -- it was his decision to import them, just like he
> imported re and math and httplib. (For example.) 

Exactly. Thus my conclusion, that too many imports (just for commodity)
in __init__.py might not be such a good idea if one wants to allow
leaf-only imports.
> 
> If kitchen is your package, then it is your choice: if you want to have
> control over when sub-packages get imported, then don't automatically
> import them in __init__.py. 

Agreed. This is however my problem: Up to my understanding rpc4django
insists on putting code into __init__.py

> 
> 
>> One package in question is a huge django application.
>>
>> Within the package is one module defining some constants and tiny
>> functions, which I would like to reuse from some command line tools,
>> which should start quickly without loading any of the django specific
>> modules. (the startup penalty and the memory overhead would be noticable)
>>
>> I am using rpc4django, which expects, that __init__.py of the django
>> application exports some all rpc functions
>> which will basically import 95% of the django application and the entire
>> django frame work (none of which were required by my command tool,
>> support utility for this application)
>>
>>
>> I could of course create a separate package just for this tiny sub
>> module, but somehow it doesn't feel right to me.
> 
> Why should it be a package? Just make it a stand-alone module.

True

> Or do something like this:
> 
> my_app/
> +--  __init__.py  # lightweight, nearly empty
> +--  cmd_tools.py
> +--  module1.py
> +--  module2.py
> +--  rpc/
>  +-- __init__.py  # huge, imports my_app.module1, my_app.module2, etc.
> 
> then point rpc4django at my_app.rpc instead of my_app.
> 

Up to my knowledge rpc4django just imports all __inits__ of all django
applications to find look for functions with a certain decorator.

I'm not sure, whether django allows nested appllications, but this might
be a solution.


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


Re: optionparse: how to add a line break to the help text

2011-09-11 Thread Gelonida N
Thanks Ben,

On 09/11/2011 07:20 AM, Ben Finney wrote:
> Gelonida N  writes:
> 
>> Considering, that you posted the snippet in 2007 and this is very
>> probably a reocurring problem for any slighty more complicated help
>> text it is really a pity, that it did not become of part of the
>> standard optparse library :-(
> 
> The ‘optparse’ library is, as the online documentation shows
> http://docs.python.org/library/optparse.html>, deprecated for new
> code:
> 
> The optparse module is deprecated and will not be developed further;
> development will continue with the argparse module.

This explains the reluctance to fix optparse. In 2007 however python 2.7
wasn't really that common though
> 
> The standard library ‘argparse’ module has a feature you might prefer
> http://docs.python.org/library/argparse.html#formatter-class>.

Most of my code has to run on python 2.5 / 2.6.

I just checked, that argparse can be installed (pip install argparse)
(didn't check functionality though) for python 2.5 / 2.6

So depending on the situation I had to decide whether I oblige users of
my scripts to  install argparse or whether I stick with optparse and
just add Tim's custom formatter.

Probably I'll go for optparse and Tim's custom formatter for tiny
scripts with no dependencies except standard libraries and
for  argparse for new bigger projects with external module dependencies.






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


Re: recursive algorithm for balls in numbered boxes

2011-09-11 Thread Mark Dickinson
On Sep 11, 1:43 am, "Dr. Phillip M. Feldman"
 wrote:
> I've written a recursive class that creates an iterator to solve a general
> formulation of the combinatorics problem known as "balls in numbered boxes"
> (also known as "indistinguishable balls in distinguishable boxes").  The
> code has been extensively tested and appears to work, but isn't terribly
> elegant.  Any suggestions about how to improve it will be appreciated.
>
> Also, I'd like to get this functionality into the Python's `itertools`
> module (the present set of combinatorics functions in `itertools` does not
> include "balls in boxes").  Does anyone know whom I should contact about
> this?

Note that for the version without size limits on individual boxes, the
itertools.combination function already provides most of what's
needed.  For example:

import itertools

def balls_in_boxes(nballs, nboxes):
n, k = nballs + nboxes - 1, nboxes - 1
for comb in itertools.combinations(range(n), k):
yield [y - x - 1 for y, x in zip(comb + (n,), (-1,) +
comb)]

print "5 balls in 3 boxes"
for combination in balls_in_boxes(5, 3):
print combination
assert len(combination) == 3
assert sum(combination) == 5


This is a well-known trick:  to divide 5 (unlabeled) balls amongst 3
(labeled) boxes, you write down sequences of 5 o's and 2 x's, where
the o's represent the 5 balls and the 'x's represent dividers:

ooxooxo  -> [2, 2, 1]
xoooxoo  -> [0, 3, 2]

And 'combinations(7, 2)' yields successively all the possible
different placements for the 2 dividers in the 7 symbols.


This question seems to come up often enough (without the box size
limit twist) that maybe it would be useful to include something like
this recipe in the itertool documentation.


For getting this into itertools, I'd suggest opening a feature request
on bugs.python.org and assigning it to Raymond Hettinger.

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


Re: Deadlock problem using multiprocessing

2011-09-11 Thread Jacky Liu
>
> I get this exception when I run the first program:
>
> Exception in thread Thread-1:
> Traceback (most recent call last):
>   File "/usr/lib/python3.1/threading.py", line 516, in _bootstrap_inner
>     self.run()
>   File "/usr/lib/python3.1/threading.py", line 469, in run
>     self._target(*self._args, **self._kwargs)
>   File "/usr/lib/python3.1/multiprocessing/pool.py", line 231, in 
> _handle_tasks
>     put(task)
>   File "/usr/lib/python3.1/pickle.py", line 1349, in dumps
>     Pickler(f, protocol, fix_imports=fix_imports).dump(obj)
> _pickle.PicklingError: Can't pickle : attribute lookup
> builtins.method failed
>
> There is no deadlock.  You are hitting this 
> problem:http://stackoverflow.com/questions/1816958/cant-pickle-type-instancem...
>
> --
> regards,
> kushal


You're right. I just realized that I was running the program through
my Vim plug-in which would use the subprocess module to open the
process, wait for its termination and get the output. It seems that
multi-process program would act quite differently such that my Vim
plug-in had been halted without getting any error information, so I
was to falsely take it as a deadlock.

The thread in stackoverflow you referenced is great, now I'm trying to
fit the solution in my own program, thanks a lot!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doctest failing

2011-09-11 Thread Tigerstyle
On 10 Sep, 13:50, Thomas Jollans  wrote:
> On 10/09/11 13:20, Tigerstyle wrote:
>
> > Hi guys.
>
> > I'm strugglin with some homework stuff and am hoping you can help me
> > out here.
>
> > All tests are failing even though I am getting the correct output on
> > the first two tests. And the last test still gives me "Of" instead of
> > "of"
>
> Cannot reproduce. I only get the one, expected, failure.
>
> % python -m doctest books.py
> **
> File "books.py", line 12, in books.book_title
> Failed example:
>     book_title('the WORKS OF AleXANDer dumas')
> Expected:
>     'The Works of Alexander Dumas'
> Got:
>     'The Works Of Alexander Dumas'
> **
> 1 items had failures:
>    1 of   3 in books.book_title
> ***Test Failed*** 1 failures.
>
>
>
> > def _test():
> >     import doctest, refactory
> >     return doctest.testmod(refactory)
> > if __name__ == "__main__":
> >     _test()
>
> What is this "refactory"? Are you testing the right code? What is the
> output of your test - does it make sense for the module?
>
> Thomas

Still struggling with my test failing. All 3 tests fail. I'm using
Ecplipse and I think Eclipse is what causing this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doctest failing

2011-09-11 Thread Tigerstyle
On 10 Sep, 13:43, Mel  wrote:
> Tigerstyle wrote:
> > Hi guys.
>
> > I'm strugglin with some homework stuff and am hoping you can help me
> > out here.
>
> > This is the code:
>
> > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on')
>
> > def book_title(title):
> >     """ Takes a string and returns a title-case string.
> >     All words EXCEPT for small words are made title case
> >     unless the string starts with a preposition, in which
> >     case the word is correctly capitalized.
> >     >>> book_title('DIVE Into python')
> >     'Dive into Python'
> >     >>> book_title('the great gatsby')
> >     'The Great Gatsby'
> >     >>> book_title('the WORKS OF AleXANDer dumas')
> >     'The Works of Alexander Dumas'
> >     """
> >     new_title = []
> >     title_split = title.strip().lower().split()
> >     for word in title_split:
> >         if title_split[0] in small_words:
> >             new_title.append(word.title())
> >         elif word in small_words:
> >             new_title.append(word.lower())
> >         else:
> >             new_title.append(word.title())
> >     return(' '.join(new_title))
>
> > def _test():
> >     import doctest, refactory
> >     return doctest.testmod(refactory)
> > if __name__ == "__main__":
> >     _test()
>
> > All tests are failing even though I am getting the correct output on
> > the first two tests. And the last test still gives me "Of" instead of
> > "of"
>
> > Any help is appreciated.
>
> I don't know about doctest -- I suspect it wants a structured docstring to
> specify the tests -- but this
>
>         if title_split[0] in small_words:
>             new_title.append(word.title())
>
> can't be what you want.
>
>         Mel.

Agreed. Not what I need.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doctest failing

2011-09-11 Thread Tigerstyle
On 10 Sep, 17:56, Chris Angelico  wrote:
> On Sat, Sep 10, 2011 at 10:24 PM, Alister Ware
>
>  wrote:
> > Ignoring the docttests my process would be to process each word & then
> > manually capitalize he 1st word, .I would als0 use a comprehension as
> > makes for cleaner code:-
>
> > def capitalize(word):
> >    if word in small_words:
> >        return word
> >    else:
> >        return word.title()
>
> And I'd do this with a lambda, but that's just me. Of course, if your
> logic is more complicated, it makes more sense to keep it in a named
> function, but a single conditional call can fit nicely into a lambda.
>
> ChrisA

Lambda is too complicated for me to understand yet. Will get there
after a little while. Where would you put this piece of code?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Idioms combining 'next(items)' and 'for item in items:'

2011-09-11 Thread Terry Reedy

On 9/11/2011 12:01 AM, Ian Kelly wrote:

On Sat, Sep 10, 2011 at 1:36 PM, Terry Reedy  wrote:

The statement containing the explicit next(items) call can optionally be
wrapped to explicitly handle the case of an empty iterable in whatever
manner is desired.

try:

except StopIteration:
raise ValueError("iterable cannot be empty")


The only time that's optional


This is an opinion, or rather, a programming philosophy based on 
technical facts, rather than a fact itself. You do raise an important issue.



is when you're writing an iterator and
the try-except would end up looking like this:

try:
 # do stuff with next(items)
except StopIteration:
 raise StopIteration

And even then, it's probably a good idea to clearly document that
you're allowing a StopIteration from one iterator to propagate up as a
StopIteration for another.


In the yield-pairs example,

def pairs(iterable):
it = iter(iterable)
for i in it:
yield i, next(it)

ignoring StopIteration from the get-even explicit next means ignoring an 
odd item. If pairs() were in a general purpose library, it should have a 
doc string that specifies that, and a test case with an odd number of 
items. I would consider a comment in the code itself to be optional, 
depending on the intended or expected human audience and the context of 
presentation. In this context, the explanation is in the text that 
surrounds the code.



Apart from that case, whenever you call next() you should always be
prepared to catch a StopIteration.


To me, it depends on the contract or specification of the function. If 
the behavior for an empty input iterator is not specified, then there is 
no basis for writing the body of an except clause.


While in the past few months I have written examples of all of the three 
explicit-next use cases I gave, I was prompted to write them up now by 
Tigerstyle's 'Doctest failing' thread. The specification by example 
(perhaps given by an instructor) did not include an empty title that 
would lead to an empty list of title words. Certainly, the doc for


def fix_title(title):
small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on')
twords = iter(title.strip().lower().split())
new_title = [next(twords)]
for word in twords:
if word not in small_words:
word = word.title()
new_title.append(word)
return(' '.join(new_title))

should start "Given a title with at least one word, ...".

The Agile Programming Test-Driven-Development maxim, 'Write the minimum 
code needed to pass the test' says that the extra lines needed to catch 
and process StopIteration should *not* be written until there is a test 
case leading to such.



Letting a StopIteration propagate
up the stack to parts unknown is bad juju because it's a flow control
exception, not an error-signaling exception.  If it happens to
propagate up to another for loop, then it will break out of the for
loop, and the exception will simply be swallowed.


What you are saying is a) that the following code

for title in ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']:
print(fix_title(title))

will print 'Amazing', 'A Hell of a Fight', and stop; b) that this is the 
worst choice of how to handle the empty title; and c) that in real world 
world programming, *someone* should decide whether fix_title('') returns 
'' or raises ValueError.


A counter-argument could be 1. that when a function's contract is 
violated, invoking unspecified behavior, anything is allowed; or 2. that 
titles are checked for actual content before the case fixup is called, 
and the time and mental energy required to define and test behavior for 
impossible input is wasted and better spent on something more useful.


--
Terry Jan Reedy

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


Re: Doctest failing

2011-09-11 Thread Tigerstyle
On 11 Sep, 08:18, Dennis Lee Bieber  wrote:
> On Sat, 10 Sep 2011 16:25:42 -0700, Dennis Lee Bieber
>  declaimed the following in
> gmane.comp.python.general:
>
>
>
> > in the language documentation... It will give you a simple way to know
> > if you are looking at the first word. Basically, you want to title-case
> > the word IF it is the first word OR the word is NOT in the list of
> > lowercase words; anything else goes through as lower case...
>
>         Of course, most of this can be done in a single line (including
> taking into account that some words may have a punctuation mark which
> would confuse the original).
>
> >>> smalls = ['into', 'the', 'a', 'of', 'at', 'in', 'for', 'on' ]
> >>> punct = ".,;:?!;'\"(){}[]"
> >>> def recase(str = "physicist odd-affection, or how i was taught to stop 
> >>> fretting and adore the weapon of mass destruction"):
>
> ...     return " ".join( w.title() if i == 0 or w.strip(punct) not in
> smalls else w
> ...                     for i,w in enumerate(str.lower().strip().split()) )
> ...>>> recase()
>
> 'Physicist Odd-Affection, Or How I Was Taught To Stop Fretting And Adore
> the Weapon of Mass Destruction'>>> recase("what? me worry?")
> 'What? Me Worry?'
> >>> recase("the end of the matter is, to be blunt, a confusion")
>
> 'The End of the Matter Is, To Be Blunt, a Confusion'>>> recase("the end of 
> the matter is in, to be blunt, a confusion")
>
> 'The End of the Matter Is in, To Be Blunt, a Confusion'>>> smalls = ['into', 
> 'the', 'a', 'of', 'at', 'in', 'for', 'on', "and", "is", "to" ]
> >>> recase()
>
> 'Physicist Odd-Affection, Or How I Was Taught To Stop Fretting and Adore
> the Weapon of Mass Destruction'>>> recase("the end of the matter is in, to be 
> blunt, a confusion")
>
> 'The End of the Matter is in, to Be Blunt, a Confusion'
>
>
>
>         Of course, explaining what this construct is doing is the trick to
> justifying it for a homework assignment.
> --
>         Wulfraed                 Dennis Lee Bieber         AF6VN
>         [email protected]    HTTP://wlfraed.home.netcom.com/

Too much destruction in this post man, and yeah I would not be able to
explain the code for my homework.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doctest failing

2011-09-11 Thread Tigerstyle
On 11 Sep, 04:12, [email protected] wrote:
> On Sep 10, 7:47 am, Peter Otten <[email protected]> wrote:
>
>
>
>
>
>
>
>
>
> > Tigerstyle wrote:
> > > I'm strugglin with some homework stuff and am hoping you can help me
> > > out here.
>
> > > This is the code:
>
> > > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on')
> > >     new_title = []
> > >     title_split = title.strip().lower().split()
> > >     for word in title_split:
> > >         if title_split[0] in small_words:
> > >             new_title.append(word.title())
> > >         elif word in small_words:
> > >             new_title.append(word.lower())
> > >         else:
> > >             new_title.append(word.title())
>
> > The logic of the for-loop is flawed; the expression
>
> > title_split[0] in small_words
>
> > will always evaluate to True if the first word is a "small word", even when
> > the loop is already past the first word. You can work around that with a
> > flag along these lines
>
> > first = True
> > for word in title_split:
> >     if first:
> >         # special treatment for the first word
> >         first = False
> >     else:
> >         # put checks for all words but the first here
> >     new_title.append(fixed_word) # assuming you have stored the titlecased
> >                                  # or lowercased word in the fixed_word
> >                                  # variable
>
> Another way to tackle this is to just capitalize the entire sentence
> before returning it.
>
> new_title = []
> title_split = title.strip().lower().split()
> for word in title_split:
>   if word in small_words:
>     new_title.append(word.lower())
>   else:
>     new_title.append(word.title())
> return(''.join(new_title).capitalize())
>
> However, I'm only helping with your homework, because I want to point
> out that doctest comments should be *readable*. Don't just throw them
> in, take the extra 10-15 seconds to make them easier on the eyes. In
> the workplace, months will pass before you review this code again, so
> you want to make it easier for an older version of yourself to
> remember it.
>
> And it takes very little effort to make it readable. Here's your
> doctest string, reformatted with just a tiny bit more whitespace. I
> even cut out a sentence.
>
> def book_title(title):
>   """
>   All words EXCEPT for small words are made title case
>   unless the string starts with a preposition, in which
>   case the word is correctly capitalized.
>
>   >>> book_title('DIVE Into python')
>   'Dive into Python'
>   >>> book_title('the great gatsby')
>   'The Great Gatsby'
>   >>> book_title('the WORKS OF AleXANDer dumas')
>   'The Works of Alexander Dumas'
>   """
> --
> // T.Hsu

It capitalises the phrase, but still the rest of the phrase is in
lower case.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doctest failing

2011-09-11 Thread Terry Reedy

On 9/11/2011 7:46 AM, Tigerstyle wrote:


Thank you Terry,



I went for this solution as it was the easiest for me to understand
and comment myself keeping in mind what level I am at right now.
Thanks a ton to everyone for sharing so much information and making it
easy to read and understand your thoughts. This was surely very very
educating read the replies from so many talented people.


You are welcome. For more, see my thread "Idioms combining 'next(items)' 
and 'for item in items:'" and the responses.


--
Terry Jan Reedy

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


Re: Idioms combining 'next(items)' and 'for item in items:'

2011-09-11 Thread Terry Reedy

On 9/11/2011 9:41 AM, Peter Otten wrote:

Terry Reedy wrote:


3. Process the items of an iterable in pairs.

items = iter(iterable)
for first in items:
  second = next(items)
  

This time, StopIteration is raised for an odd number of items. Catch and
process as desired. One possibility is to raise ValueError("Iterable
must have an even number of items").


Another way is zip-based iteration:

(a) silently drop the odd item

items = iter(iterable)
for first, second in zip(items, items): # itertools.izip in 2.x
...


In practice, I would use this rather than the loop above. However, I 
wanted to introduce the idea then used in the intermittent pairing of 
surrogates.



(b) add a fill value

for first, second in itertools.zip_longest(items, items):
 ...

(c) raise an exception

Unfortunately there is no zip_exc() that guarantees that all iterables are
of the same "length", but I've written a recipe some time ago

http://code.activestate.com/recipes/497006-zip_exc-a-lazy-zip-that-ensures-
that-all-iterables/

that achieves near-C speed.


Interesting. It took a moment to see the general idea. For some reason, 
you timeit examples in the comment now all have "data = [range(1000)]3", 
missing '*'.


--
Terry Jan Reedy

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


Re: Invoke a superclass method from a subclass constructor

2011-09-11 Thread Andreas Perstinger

On 2011-09-11 13:17, Kayode Odeyemi wrote:

On Sun, Sep 11, 2011 at 11:41 AM, Thomas Jollans  wrote:

 It is working:

 >>>  class A(object):
 ... def log (self, module):
 ... return str ('logged')
 ...
 >>>  class B(A):
 ... def __init__(self, module):
 ... self.module = A().log(module)
 ...
 >>>  c = B('system')
 >>>  c.module
 'logged'


Why do you have to do c.module? I'm expecting an output just by creating an
instance of B.


Why do you expect an output? In B.__init__ you are just assigning the 
return value from A.log() to the attribute "module" and in A.log() there 
is no output either.


Bye, Andreas

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


Re: Doctest failing

2011-09-11 Thread Ethan Furman

Chris Angelico wrote:

On Sat, Sep 10, 2011 at 10:24 PM, Alister Ware
 wrote:

Ignoring the docttests my process would be to process each word & then
manually capitalize he 1st word, .I would als0 use a comprehension as
makes for cleaner code:-

def capitalize(word):
   if word in small_words:
   return word
   else:
   return word.title()


And I'd do this with a lambda, but that's just me. Of course, if your
logic is more complicated, it makes more sense to keep it in a named
function, but a single conditional call can fit nicely into a lambda.


Lambdas are great when needed, but if don't *need* it, and you have more 
than a few, debugging can be a nightmare... "Okay, so this is function 
... and that is function ... and over here we also have 
function ... ARGH!"


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


Re: using python in web applications

2011-09-11 Thread Tim Roberts
"Littlefield, Tyler"  wrote:
>
>I don't much care for PHP, but the thing that can be said for it is it's 
>pretty quick. How does Python compare?

PHP is quick for development, in that you can slap together some schlock
and have it mostly work.  The result, however, is usually schlock.  The
performance of the language itself is almost entirely irrelevant; the
execution time is swamped by the network overhead.

>I'm also curious what databases are suggested? I've always 
>done most of my work in MYSql, but from what I understand postgresql is 
>becoming more popular to.

Well, that's a religious argument.  Personally, I've always been confused
by the draw of MySql.  From the very beginning, Postgres has always been
more powerful, more reliable, more standard-compliant, and more
professional.
-- 
Tim Roberts, [email protected]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Idioms combining 'next(items)' and 'for item in items:'

2011-09-11 Thread Ethan Furman

Terry Reedy wrote:

On 9/11/2011 12:01 AM, Ian Kelly wrote:

On Sat, Sep 10, 2011 at 1:36 PM, Terry Reedy  wrote:

The statement containing the explicit next(items) call can optionally be
wrapped to explicitly handle the case of an empty iterable in whatever
manner is desired.

try:

except StopIteration:
raise ValueError("iterable cannot be empty")


The only time that's optional


This is an opinion, or rather, a programming philosophy based on 
technical facts, rather than a fact itself. You do raise an important 
issue.



is when you're writing an iterator and
the try-except would end up looking like this:

try:
 # do stuff with next(items)
except StopIteration:
 raise StopIteration

And even then, it's probably a good idea to clearly document that
you're allowing a StopIteration from one iterator to propagate up as a
StopIteration for another.


In the yield-pairs example,

def pairs(iterable):
it = iter(iterable)
for i in it:
yield i, next(it)

ignoring StopIteration from the get-even explicit next means ignoring an 
odd item. If pairs() were in a general purpose library, it should have a 
doc string that specifies that, and a test case with an odd number of 
items. I would consider a comment in the code itself to be optional, 
depending on the intended or expected human audience and the context of 
presentation. In this context, the explanation is in the text that 
surrounds the code.



Apart from that case, whenever you call next() you should always be
prepared to catch a StopIteration.


To me, it depends on the contract or specification of the function. If 
the behavior for an empty input iterator is not specified, then there is 
no basis for writing the body of an except clause.


While in the past few months I have written examples of all of the three 
explicit-next use cases I gave, I was prompted to write them up now by 
Tigerstyle's 'Doctest failing' thread. The specification by example 
(perhaps given by an instructor) did not include an empty title that 
would lead to an empty list of title words. Certainly, the doc for


def fix_title(title):
small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on')
twords = iter(title.strip().lower().split())
new_title = [next(twords)]
for word in twords:
if word not in small_words:
word = word.title()
new_title.append(word)
return(' '.join(new_title))

should start "Given a title with at least one word, ...".

The Agile Programming Test-Driven-Development maxim, 'Write the minimum 
code needed to pass the test' says that the extra lines needed to catch 
and process StopIteration should *not* be written until there is a test 
case leading to such.



Letting a StopIteration propagate
up the stack to parts unknown is bad juju because it's a flow control
exception, not an error-signaling exception.  If it happens to
propagate up to another for loop, then it will break out of the for
loop, and the exception will simply be swallowed.


What you are saying is a) that the following code

for title in ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']:
print(fix_title(title))

will print 'Amazing', 'A Hell of a Fight', and stop; b) that this is the 
worst choice of how to handle the empty title; and c) that in real world 
world programming, *someone* should decide whether fix_title('') returns 
'' or raises ValueError.


A counter-argument could be 1. that when a function's contract is 
violated, invoking unspecified behavior, anything is allowed; or 2. that 
titles are checked for actual content before the case fixup is called, 
and the time and mental energy required to define and test behavior for 
impossible input is wasted and better spent on something more useful.



Having spent hours tracking down errors because somebody did not address 
 a corner case, I find counter-argument 1 unhelpful.


Counter-argument 2 I can at least partially agree with; however, in this 
case where the uncaught exception can mess up flow control elsewhere I 
do not -- the StopIteration should be caught and changed to something 
appropriate, such as EmptyTitle (assuming blank titles are errors -- 
which they probably should be... "Hello, do you have the book '' for 
sale here?")


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


Re: using python in web applications

2011-09-11 Thread Laurent
+1 for PostgreSQL. It's faster than MySQL for years now, and is much more 
seriously featured.
If you don't need ACID properties (transactions stuff) you should also give 
Document-based databases like MongoDB a try. It changed my code life.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recursive algorithm for balls in numbered boxes

2011-09-11 Thread Dr. Phillip M. Feldman

Hello Peter,

When I run my code, I get the same 14 configurations that your code
produces; the only different that I can see in the output is that the
configurations are produced in a different order.  Note that your code is
not creating an iterator, so thus doesn't do what I want.  Also, generating
the product set and then testing whether the total number of balls is
correct will potentially consider a huge number of cases that must be
rejected because the sum is wrong; this is too inefficient.

Phillip

In [2]: list(balls_in_numbered_boxes(10,[4,3,2,1,2]))
Out[2]:
[(4, 3, 2, 1, 0),
 (4, 3, 2, 0, 1),
 (4, 3, 1, 1, 1),
 (4, 3, 1, 0, 2),
 (4, 3, 0, 1, 2),
 (4, 2, 2, 1, 1),
 (4, 2, 2, 0, 2),
 (4, 2, 1, 1, 2),
 (4, 1, 2, 1, 2),
 (3, 3, 2, 1, 1),
 (3, 3, 2, 0, 2),
 (3, 3, 1, 1, 2),
 (3, 2, 2, 1, 2),
 (2, 3, 2, 1, 2)]
-- 
View this message in context: 
http://old.nabble.com/recursive-algorithm-for-balls-in-numbered-boxes-tp32440187p32443548.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: recursive algorithm for balls in numbered boxes

2011-09-11 Thread Dr. Phillip M. Feldman

Chris,

Your code is much cleaner than mine.  I will have to figure out exactly how
it is working.

Thanks!

Phillip


-- 
View this message in context: 
http://old.nabble.com/recursive-algorithm-for-balls-in-numbered-boxes-tp32440187p32443579.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: using python in web applications

2011-09-11 Thread hidura
I am agree with postgresql i don' t have any problem, also is better for big 
applications. And Python is always better language than PHP if you' re going to 
create a web app.
Sent from my BlackBerry® wireless device

-Original Message-
From: Tim Roberts 
Sender: [email protected]
Date: Sun, 11 Sep 2011 11:48:01 
To: 
Subject: Re: using python in web applications

"Littlefield, Tyler"  wrote:
>
>I don't much care for PHP, but the thing that can be said for it is it's 
>pretty quick. How does Python compare?

PHP is quick for development, in that you can slap together some schlock
and have it mostly work.  The result, however, is usually schlock.  The
performance of the language itself is almost entirely irrelevant; the
execution time is swamped by the network overhead.

>I'm also curious what databases are suggested? I've always 
>done most of my work in MYSql, but from what I understand postgresql is 
>becoming more popular to.

Well, that's a religious argument.  Personally, I've always been confused
by the draw of MySql.  From the very beginning, Postgres has always been
more powerful, more reliable, more standard-compliant, and more
professional.
-- 
Tim Roberts, [email protected]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recursive algorithm for balls in numbered boxes

2011-09-11 Thread Peter Otten
Dr. Phillip M. Feldman wrote:

> When I run my code, I get the same 14 configurations that your code
> produces; 

I'm sorry, I ran the buggy code from

http://old.nabble.com/file/p32439307/balls_in_numbered_boxes.py

without realizing it was not 

http://old.nabble.com/file/p32440187/balls_in_numbered_boxes.py

> the only different that I can see in the output is that the
> configurations are produced in a different order.  Note that your code is
> not creating an iterator, so thus doesn't do what I want.  

The outer loop is in a generator expression and thus evaluates lazily.

> Also,
> generating the product set and then testing whether the total number of
> balls is correct will potentially consider a huge number of cases that
> must be rejected because the sum is wrong; this is too inefficient.

Indeed; I should have added a disclaimer to make that clear.

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


Re: optionparse: how to add a line break to the help text

2011-09-11 Thread Robert Kern

On 9/11/11 6:05 AM, Tim Chase wrote:


As Ben Finney replied, optparse is now deprecated, replaced in part by argparse.
Unfortunately, argparse wasn't backported to the standard library for earlier
2.x series (I think it became available in 2.7, and may run in earlier versions
if manually added like I had to do on my Debian Py2.6 install). But that makes
it hard for those of us who want to use a built-in option-parsing library across
a wide variety of Python versions. I don't strongly care which I use except that
I want it to be broadly available with minimal fuss.


argparse.py can be simply dropped into your codebase, if you want. That's about 
as minimal of fuss as you can ask for.


  http://pypi.python.org/pypi/argparse

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Idioms combining 'next(items)' and 'for item in items:'

2011-09-11 Thread Chris Angelico
On Mon, Sep 12, 2011 at 2:47 AM, Terry Reedy  wrote:
> What you are saying is a) that the following code
>
> for title in ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']:
>    print(fix_title(title))
>

At least in Python 3.2, this isn't the case. StopIteration breaks the
loop only if it's raised during the assignment, not during the body.

>>> x=iter([1,2,3,4,5])
>>> for i in x:
print("%d - %d"%(i,next(x)))

1 - 2
3 - 4
Traceback (most recent call last):
  File "", line 2, in 
print("%d - %d"%(i,next(x)))
StopIteration

Compare with:

>>> def pair(it):
while True:
yield next(it),next(it)

>>> x=iter([1,2,3,4,5])
>>> for i,j in pair(x):
print("%d - %d"%(i,j))

1 - 2
3 - 4

In this case, the StopIteration bubbles up and quietly terminates the loop.

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


Re: Idioms combining 'next(items)' and 'for item in items:'

2011-09-11 Thread Terry Reedy

On 9/11/2011 6:41 PM, Chris Angelico wrote:

On Mon, Sep 12, 2011 at 2:47 AM, Terry Reedy  wrote:

What you are saying is a) that the following code

for title in ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']:
print(fix_title(title))



At least in Python 3.2, this isn't the case. StopIteration breaks the
loop only if it's raised during the assignment, not during the body.


It breaks the loop *silently* only if ...


x=iter([1,2,3,4,5])
for i in x:

print("%d - %d"%(i,next(x)))

1 - 2
3 - 4
Traceback (most recent call last):
   File "", line 2, in
 print("%d - %d"%(i,next(x)))
StopIteration


whereas, you are right, it breaks it noisily in the body. So Ian's claim 
that StopIteration must be caught to avoid silent termination is not 
true. Thanks for pointing out what I saw but did not cognize the full 
implication of before. A better exception and an error message with an 
explaination might still be a good idea, though.


--
Terry Jan Reedy

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


Re: Doctest failing

2011-09-11 Thread Chris Angelico
On Mon, Sep 12, 2011 at 4:43 AM, Ethan Furman  wrote:
> Chris Angelico wrote:
>>
>> And I'd do this with a lambda, but that's just me. Of course, if your
>> logic is more complicated, it makes more sense to keep it in a named
>> function, but a single conditional call can fit nicely into a lambda.
>
> Lambdas are great when needed, but if don't *need* it, and you have more
> than a few, debugging can be a nightmare... "Okay, so this is function
> ... and that is function ... and over here we also have
> function ... ARGH!"

Yeah, they can be like the Bruces sketch at times.

A lambda is basically a function defined in an expression. For instance:

def add_one(x):
   return x+1

is (practically) the same as:

add_one = lambda x: x+1

In each case, you can call that function and will get back a value.
The advantage of lambdas is that, in a list comprehension or map call,
the code is right there instead of being elsewhere in a def statement.
But as you can see, they quickly become hard to read:

[j+2 for i in [[1,2,3],[4,5,6],[7,8,9]] for j in (lambda x: [q+10 for
q in x])(i)]

Their main advantage isn't in list comps, where you can already use
arbitrary expressions, but in calls that require a function as an
argument. The map() function is very similar to a generator
expression, but it can iterate over multiple iterables at once:

>>> list(map(lambda x,y: x+y,[1,2,3],[40,50,60]))
[41, 52, 63]

Note how the lambda keeps the code right there, whereas a def would
separate it out. It's obvious from this one expression that it's
adding successive corresponding pairs.

Hope that helps!

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


Re: Doctest failing

2011-09-11 Thread Ben Finney
Chris Angelico  writes:

> A lambda is basically a function defined in an expression. For instance:
>
> def add_one(x):
>return x+1
>
> is (practically) the same as:
>
> add_one = lambda x: x+1

Those are only practically the same if you ignore the practical worth of
a function knowing the name it was defined with. The latter does not
have that, hence I don't see it as practically the same as the former.

-- 
 \ “The Vatican is not a state.… a state must have territory. This |
  `\ is a palace with gardens, about as big as an average golf |
_o__) course.” —Geoffrey Robertson, 2010-09-18 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doctest failing

2011-09-11 Thread Chris Angelico
On Mon, Sep 12, 2011 at 11:37 AM, Ben Finney  wrote:
> Those are only practically the same if you ignore the practical worth of
> a function knowing the name it was defined with. The latter does not
> have that, hence I don't see it as practically the same as the former.
>

I know, but in the context of explaining what "lambda" means, it's
practically the same. Lambdas can't (afaik) have docstrings either,
etc, etc, but in terms of defining lambda, the two are more-or-less
equivalent.

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


Re: Doctest failing

2011-09-11 Thread Steven D'Aprano
On Mon, 12 Sep 2011 01:06 pm Chris Angelico wrote:

> On Mon, Sep 12, 2011 at 11:37 AM, Ben Finney 
> wrote:
>> Those are only practically the same if you ignore the practical worth of
>> a function knowing the name it was defined with. The latter does not
>> have that, hence I don't see it as practically the same as the former.
>>
> 
> I know, but in the context of explaining what "lambda" means, it's
> practically the same. Lambdas can't (afaik) have docstrings either,
> etc, etc, but in terms of defining lambda, the two are more-or-less
> equivalent.


>>> f = lambda x: x+1
>>> f.__name__ 
''
>>> f.__doc__ = "Return x+1"
>>> f.__name__ = "add_one"
>>> help(f)

Help on function add_one in module __main__:

add_one(x)
Return x+1



Lambdas are functions, no more, no less. The only difference is that the
*syntax* of the lambda statement only allows a single expression rather
that the full block of a def, and no name. But because it returns an
ordinary function object, you can post-process it just like any other
function.

Unfortunately, tracebacks ignore the function.__name__ and print the code
object name:

>>> f

>>> f("x")
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in 
TypeError: cannot concatenate 'str' and 'int' objects


and the code object name is read-only:

>>> f.func_code.co_name
''
>>> f.func_code.co_name = "add_one"
Traceback (most recent call last):
  File "", line 1, in 
TypeError: readonly attribute


-- 
Steven

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


What do you guys think about adding a method "to_json"

2011-09-11 Thread Juan Pablo Romero Méndez
Hello,

What do you guys think about adding a method "to_json" to dictionaries
and sequence types? Perhaps through a module import?

Regards,

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


Re: What do you guys think about adding a method "to_json"

2011-09-11 Thread Chris Rebert
2011/9/11 Juan Pablo Romero Méndez :
> Hello,
>
> What do you guys think about adding a method "to_json" to dictionaries
> and sequence types? Perhaps through a module import?

Why? We already have json.dumps(); seems to cover the use case.

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


Re: What do you guys think about adding a method "to_json"

2011-09-11 Thread Adam Jorgensen
Perhaps an actual use-case would clarify the need for this?

2011/9/12 Chris Rebert 

> 2011/9/11 Juan Pablo Romero Méndez :
> > Hello,
> >
> > What do you guys think about adding a method "to_json" to dictionaries
> > and sequence types? Perhaps through a module import?
>
> Why? We already have json.dumps(); seems to cover the use case.
>
> Cheers,
> Chris
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list