multinomial combinations

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

I wrote a small generator function that produces multinomial combinations. 
(Python's itertools module does ordinary combinations, but not multinomial
combinations).  The code essentially works, except that the the last
combination in each tuple is not enclosed in a nested tuple:

In [2]: x= multinomial_combinations(range(7),[2,1,2])

In [3]: x.next()
Out[3]: ((0, 1), (2,), 3, 4)

(The 3 and 4 should be enclosed in a nested tuple).

Any suggestions as to what I'm doing wrong will be appreciated.  My code
follows:

def multinomial_combinations(items, ns):

   if len(ns) == 1:
  for c in itertools.combinations(items, ns[0]):
 yield c

   else:
  for c_first in itertools.combinations(items, ns[0]):
 items_remaining= set(items) - set(c_first)
 for c_other in multinomial_combinations(items_remaining, ns[1:]):
yield (c_first,) + c_other
-- 
View this message in context: 
http://old.nabble.com/multinomial-combinations-tp32503896p32503896.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


strange behavior from recursive generator

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

A few weeks ago, I wrote a class that creates an iterator for solving the
general unlabeled-balls-in-labeled boxes occupancy problem. Chris Rebert
converted my code to a generator, which made the code cleaner, and I
subsequently simplified it somewhat further.

My problem is the following: All of these versions of the code work fine for
very small problems, but do not produce the full set of occupancy
distributions for larger problems. The following sample input and output
show what happens with two balls and two boxes (to keep things simple, I've
made the boxes large enough so that each box can hold both balls).

In [6]: x= balls_in_labeled_boxes(2,[2,2])

In [7]: list(x)
balls=2, box_sizes=[2, 2]
About to make recursive call.  balls_in_other_boxes=0, box_sizes=[2]
i=0, distribution_other=(0,)
About to make recursive call.  balls_in_other_boxes=1, box_sizes=[2]
i=0, distribution_other=(1,)
About to make recursive call.  balls_in_other_boxes=2, box_sizes=[2]
i=0, distribution_other=(2,)
Out[7]: [(2, 0), (1, 1), (0, 2)]

Note that Out[7] above gives the correct result, showing all three possible
distributions. Now lets try the same thing with three boxes.

In [8]: x= balls_in_labeled_boxes(2,[2,2,2])

In [9]: list(x)
balls=2, box_sizes=[2, 2, 2]
About to make recursive call.  balls_in_other_boxes=0, box_sizes=[2, 2]
i=0, distribution_other=(0, 0)
About to make recursive call.  balls_in_other_boxes=1, box_sizes=[2, 2]
i=0, distribution_other=(1, 0)
About to make recursive call.  balls_in_other_boxes=2, box_sizes=[2, 2]
i=0, distribution_other=(2, 0)
i=1, distribution_other=(1, 1)
Out[9]: [(2, 0, 0), (1, 1, 0), (0, 2, 0), (0, 1, 1)]

When there are no balls in the initial box, the recursive call should
produce the same three occupancy distributions that we saw above, but one of
them is now missing. If someone can shed light on why this is happening, I'd
be grateful.

Phillip

http://old.nabble.com/file/p32503886/balls_in_labeled_boxes.py
balls_in_labeled_boxes.py 
-- 
View this message in context: 
http://old.nabble.com/strange-behavior-from-recursive-generator-tp32503886p32503886.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-12 Thread Dr. Phillip M. Feldman


Mark Dickinson-2 wrote:
 
 
 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
 
 

You are correct--the case without capacity limits can be handled using the
existing machinery in `itertools`.  BTW--That trick with the dividers is
discussed on page 38 of William Feller's classic text, An Introduction to
Probability Theory and Its Applications.

As per your suggestion, I have opened a feature request and assigned it to
Raymond.  Thanks!
-- 
View this message in context: 
http://old.nabble.com/recursive-algorithm-for-balls-in-numbered-boxes-tp32440187p32449079.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

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: can't generate iterator from list

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

Very nice explanation!  I've circumvented the problem by returning a
`deepcopy` of the list.  I've also added an acknowledgment.  The revised
code is attached.

I'd like to see both balls in numbered boxes (this code) and balls in
unnumbered (indistinguishable) boxes in Python's `itertools` module, but
don't know whom to contact about this.  Also, I haven't yet worked out a
good algorithm for balls in unnumbered boxes.  Any suggestions will be
appreciated.

Phillip http://old.nabble.com/file/p32439307/balls_in_numbered_boxes.py
balls_in_numbered_boxes.py 
-- 
View this message in context: 
http://old.nabble.com/can%27t-generate-iterator-from-list-tp32435519p32439307.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: can't generate iterator from list

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

I just realized that there is a defect in my algorithm, so I will try to code
this using a recursive algorithm instead.

-- 
View this message in context: 
http://old.nabble.com/can%27t-generate-iterator-from-list-tp32435519p32439439.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


recursive algorithm for balls in numbered boxes

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

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?

Phillip

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

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


Re: can't generate list from iterator

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

The title should have been can't generate list from iterator.
-- 
View this message in context: 
http://old.nabble.com/can%27t-generate-iterator-from-list-tp32435519p32435569.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


can't generate iterator from list

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

It is supposed to be possible to generate a list representation of any
iterator that produces a sequence of finite length, but this doesn't always
work. Here's a case where it does work:

Input:

from itertools import combinations
list(combinations(range(4),2))

Output:

[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

When I define my own classes that produce iterators, conversion to a list
works for some of these classes but not for others. Here's a case where it
doesn't work:

In:  list(balls_in_numbered_boxes(2, [3,3,3]))

Out:

[array([0, 0, 1]),
 array([0, 0, 1]),
 array([0, 0, 1]),
 array([0, 0, 1]),
 array([0, 0, 1])]

Note that if I apply the `next` method to the object, the output is correct:

In [5]: x=balls_in_numbered_boxes(3,[3,3,3])

In [6]: x.next()
Out[6]: array([3, 0, 0])

In [7]: x.next()
Out[7]: array([2, 1, 0])

In [8]: x.next()
Out[8]: array([1, 2, 0])

In [9]: x.next()
Out[9]: array([0, 3, 0])

In [10]: x.next()
Out[10]: array([0, 2, 1])

In [11]: x.next()
Out[11]: array([0, 1, 2])

In [12]: x.next()
Out[12]: array([0, 0, 3])

In [13]: x.next()
---
StopIteration Traceback (most recent call last)

Code is attached (see below). Any suggestions as to what's going wrong will
be appreciated.

class balls_in_numbered_boxes(object):
   
   OVERVIEW

   This class generates an iterator that produces all distinct distributions
of
   indistinguishable balls among numbered boxes with specified capacity
limits.
   (This is a generalization of the most common formulation of the problem,
   where each box is sufficiently large to accommodate all of the balls, and
is
   an important example of a class of combinatorics problems called 'weak
   composition' problems).


   CONSTRUCTOR INPUTS

   n: the number of balls

   limits: This argument is a list of length 1 or greater.  The length of
the
   list corresponds to the number of boxes.  `limits[i]` is a positive
integer
   that specifies the maximum capacity of the ith box.  If `limits[i]`
equals
   `n` (or greater), then the ith box can accommodate all `n` balls and thus
   effectively has unlimited capacity.
   

   def __init__(self, n=None, limits=None):
  if n  0 or not isinstance(n,int):
 raise BadInput(The number of balls n must be a non-negative
integer.)

  if not isinstance(limits,list) or len(limits)1:
 raise BadInput(`limits` must be a non-empty list.)
  for limit in limits:
 if not isinstance(limit,int) or limit1:
raise BadInput(Items in `limits` must be positive integers.)

  # Copy constructor inputs to object attributes.  We make a `deepcopy`
of
  # `limits` to protect against the possibility of the calling program
  # modifying it before all calls to the `next` method have been
completed.
  self.n= n
  self.limits= deepcopy(limits)
  self.distribution= None


   def __iter__(self):
  return self


   def next(self):

  # If `self.distribution` is `None`, this is the initial call to
`next`,
  # in which case we generate the initial distribution by assigning as
many
  # balls as possible to the first box, as many balls that remain to the
  # next box, and so on.
  if self.distribution is None:
 self.distribution= zeros(len(self.limits), dtype='i4')

 balls= self.n

 for box in xrange(len(self.limits)):

# Store as many balls as possible in the current box:
self.distribution[box]= min(balls,self.limits[box])
balls-= self.distribution[box]
if balls == 0: break

 else:

# We fell through the above loop, which means that it was
impossible
# to distribute all of the balls:
raise BadInput(The total capacity of the boxes is less than the

  number of balls to be distributed.)

 # Make first box the current box, i.e., the box from which a ball
 # will be moved when the `next` method is invoked:
 self.box= 0

 return self.distribution

  # `self.distribution` is not `None`, which means that this is not the
  # initial invocation of `next`.  We create the next distribution by
moving
  # one ball to the right, unless this is impossible.

  self.distribution[self.box]-= 1

  for box in xrange(self.box+1,len(self.limits)):

 # If this box is full, advance to the next one:
 if self.distribution[box] == self.limits[box]: continue
 self.distribution[box]+= 1
 break

  else:

 # We fell through the above loop, which means that it was
impossible
 # to find a new home for the ball that we were trying to move.
 raise StopIteration

  # If the current box--the box from which we have been removing balls--
is
  # empty, advance to the next box:
  if self.distribution[self.box] == 0: self.box+= 1

  return 

Re: Turtle graphics speed(). Seems broken

2010-02-27 Thread Dr. Phillip M. Feldman


Stefan Behnel-3 wrote:
 
 alexander@gmail.com wrote:
 I think the speed function may be broken from the turtle graphics package
 
 
 from turtle import *
 
 speed('fastest')
 
 forward(50)
 
 
 I have tried all of the different speed settings, but I get no change
 in the turtle's speed does anyone know how to fix this?
 
 Use xturtle? :)
 
 http://ada.rg16.asn-wien.ac.at/~python/xturtle/
 
 Stefan
 -- 
 http://mail.python.org/mailman/listinfo/python-list
 
 

The Python library's implementation of turtle graphics is slow to the point
that many applications are simply impractical.  I recently converted a
program to Python/turtle graphics that was originally written by my son
using Processing; the result of the conversion is that the time to draw the
balls increased by a factor of roughly 50!  (The Processing version takes
less than 0.1 seconds to generate the image, while the Python version takes
almost 5 seconds on the same computer).  It would be good if this
performance problem can be fixed, either by patching the current
implementation of turtle graphics, or by replacing it with xturtle if that
is better. http://old.nabble.com/file/p27732940/balls.py balls.py 

-- 
View this message in context: 
http://old.nabble.com/Turtle-graphics-speed%28%29.-Seems-broken-tp15504443p27732940.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: how to convert string function to string method?

2009-12-07 Thread Dr. Phillip M. Feldman

Bruno- You've made some excellent suggestions, and I'm always grateful for
the opportunity to learn.  My revised code appears below.  Philllip

def strip_pairs(s, open='([{\'', close=')]}\''):
   
   OVERVIEW

   This function strips matching pairs of characters from the beginning and
   end of the input string `s`.  If `s` begins with a character in `open`
and
   ends with the corresponding character in `close` (see below), both are
   removed from the string. This process continues until no further matching
   pairs can be removed.

   INPUTS

   `open` and `close`: These arguments, which must be equal-length strings,
   specify matching start-of-scope and end-of-scope characters.  The same
   character may appear in both `open` and `close`; single and double quotes
   conventionally match themselves.  By default, `open` contains a left
   parenthesis, left square bracket, left curly bracket, single quote, and
   double quote), and `close` contains the corresponding characters.

   if not isinstance(s,(str,unicode)):
  raise TypeError, '`s` must be a string (str or unicode).'

   if not isinstance(open,(str,unicode)) or not
isinstance(close,(str,unicode)):
  raise TypeError, '`open` and `close` must be strings (str or
unicode).'

   if len(open) != len(close): raise ValueError, \
 '\'open\' and \'close\' arguments must be equal-length strings.'

   while len(s) = 2:

  # Check whether first character of `s` is in `open`:
  i= open.find(s[0])

  # If `s` does not begin with a character from `open`, there are no
more
  # pairs to be stripped:
  if i == -1: break

  # If `s` does not begin and end with matching characters, there are no
  # more pairs to be stripped:
  if s[-1] != close[i]: break

  # Strip the first and last character from `s`:
  s= s[1:-1]

   return s
-- 
View this message in context: 
http://old.nabble.com/how-to-convert-string-function-to-string-method--tp26673209p26688035.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: How to create a docstring for a module?

2009-12-06 Thread Dr. Phillip M. Feldman



Steven D'Aprano-7 wrote:
 
 On Sun, 06 Dec 2009 10:55:50 +0100, Andreas Waldenburger wrote:
 
 On Sat, 5 Dec 2009 23:04:42 -0800 (PST) Dr. Phillip M. Feldman
 pfeld...@verizon.net wrote:
 
 
 If I create a module xyz.py with a docstring xyz does everything you
 could possibly want. at the top, the command ?xyz issued at the
 IPython prompt does not display this docstring.  What am I doing wrong?
 
 Stab in the dark: You have imported the module first, right?
 
 Also: Never, EVER, ask a question like this on any technical forum
 without posting your code (or rather: a minimal version of it that still
 exhibits the problem). That way, people can help you directly instead of
 taking wild guesses at what your problem might be.
 
 In fairness, Phillip's description of the problem is pretty straight-
 forward: he has a module xyz.py with a docstring. The minimal version of 
 the code is no code at all, just a docstring:
 
 xyz does everything you could possibly want.
 
 His problem isn't an error when running the code, but an error with 
 IPython's command ?xyz.
 
 What he didn't say is what IPython prints instead of the expected 
 docstring. Over to you Phillip, don't just tell us what IPython doesn't 
 do, tell us what it does do.
 
 My guesses are:
 
 * He hasn't imported the module, so he gets an error of some sort.
 
 * He hasn't actually defined a docstring. Docstrings have to be string 
 literals, you can't do this:
 
 %s does everything you could possibly want. % xyz
 
 Nor can you have anything except comments and whitespace between the top 
 of the module and the string.
 
 * He has another module called xyz which is shadowing the module he 
 expects, and so he sees that module's docstring instead.
 
 
 -- 
 Steven
 -- 
 http://mail.python.org/mailman/listinfo/python-list
 
 

My bad.  This is working for me now.  I could swear that I imported the
module previously, but perhaps I didn't .  My apologies, and thanks for the
help!

-- 
View this message in context: 
http://old.nabble.com/How-to-create-a-docstring-for-a-module--tp26662729p26668719.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: How to create a docstring for a module?

2009-12-06 Thread Dr. Phillip M. Feldman

OK.  I was able to reproduce the problem.  My difficulty was that the command
that I issued initially was from xyz import * rather than just import
xyz.  If I say import xyz, then the docstring is defined; if I say from
xyz import *, it isn't.  I'm not sure whether this is a bug or expected
behavior.
-- 
View this message in context: 
http://old.nabble.com/How-to-create-a-docstring-for-a-module--tp26662729p26668758.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


how to convert string function to string method?

2009-12-06 Thread Dr. Phillip M. Feldman

I wrote a handy-dandy function (see below) called strip_pairs for stripping
matching pairs of characters from the beginning and end of a string.  This
function works, but I would like to be able to invoke it as a string method
rather than as a function.  Is this possible?

def strip_pairs(s=None, open='([{\'', close=')]}\''):
   This function strips matching pairs of characters from the beginning
and
   end of the input string `s`.  `open` and `close` specify corresponding
pairs
   of characters, and must be equal-length strings.  If `s` begins with a
   character in `open` and ends with the corresponding character in `close`,
   both are removed from the string.  This process continues until no
further
   matching pairs can be removed.

   if len(open) != len(close): raise Exception, \
 '\'open\' and \'close\' arguments must be strings of equal length.'

   # If input is missing or is not of type `str` (or `unicode`), return
None:
   if s is None or not isinstance(s,(str,unicode)): return None

   while len(s) = 2:

  # Check whether first character of `s` is in `open`:
  i= open.find(s[0])

  # If `s` does not begin with a character from `open`, there are no
more
  # pairs to be stripped:
  if i == -1: break

  # If `s` does not begin and end with matching characters, there are no
  # more pairs to be stripped:
  if s[-1] != close[i]: break

  # Strip the first and last character from `s`:
  s= s[1:-1]

   return s
-- 
View this message in context: 
http://old.nabble.com/how-to-convert-string-function-to-string-method--tp26673209p26673209.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


How to create a docstring for a module?

2009-12-05 Thread Dr. Phillip M. Feldman

If I create a module xyz.py with a docstring xyz does everything you could
possibly want. at the top, the command ?xyz issued at the IPython prompt
does not display this docstring.  What am I doing wrong?
-- 
View this message in context: 
http://old.nabble.com/How-to-create-a-docstring-for-a-module--tp26662729p26662729.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


How to find number of line that is currently executing?

2009-10-09 Thread Dr. Phillip M. Feldman

I would like to put a statement on line N of my program that prints the line
number that is currently executing. This may sound fairly trivial, but I
don't want to hard code the line number because N will change if lines are
inserted or deleted above that point. Any advice will be appreciated.
-- 
View this message in context: 
http://www.nabble.com/How-to-find-number-of-line-that-is-currently-executing--tp25830766p25830766.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Is there a better way to code variable number of return arguments?

2009-10-08 Thread Dr. Phillip M. Feldman

I'm amazed that this works.  I had not realized that

x,y= [3,4]

is equivalent to

x= 3; y= 4

Python is rather clever.

Thanks!

snip

To elaborate on Paul's answer, returning the list will also unpack it if 
you have it set up that way.  E.g.

def func(alist):
return alist

some_list = [1, 2]
this, that = func(alist)

At least, in 2.5.4 this works.  :-)

Mind you, if you don't have the correct number of return names to match 
the unpacking you'll get the normal errors from that.

Hope this helps!

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



-- 
View this message in context: 
http://www.nabble.com/Is-there-a-better-way-to-code-variable-number-of-return-arguments--tp25803294p25813206.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


comparison on list yields surprising result

2009-08-28 Thread Dr. Phillip M. Feldman

In [21]: x
Out[21]: [1, 2, 3, 5]

In [22]: x6
Out[22]: True

Is this a bug?
-- 
View this message in context: 
http://www.nabble.com/comparison-on-list-yields-surprising-result-tp25195170p25195170.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: comparison on list yields surprising result

2009-08-28 Thread Dr. Phillip M. Feldman

It looks as though what I should have done is the following:

In [23]: array(x)  6
Out[23]: array([False, False, False, False], dtype=bool)
-- 
View this message in context: 
http://www.nabble.com/comparison-on-list-yields-surprising-result-tp25195170p25195893.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Python 'for' loop is memory inefficient

2009-08-14 Thread Dr. Phillip M. Feldman

I wrote the following correct but inefficient test of primality for purposes
of demonstrating that the simplest algorithm is often not the most
efficient.  But, when I try to run the following code with a value of n that
is large enough to produce a significant amount of running time, I get an
out-of-memory error!

def is_prime(n):
   for j in range(2,n):
  if (n % j) == 0: return False
   return True

It seems as though Python is actually expanding range(2,n) into a list of
numbers, even though this is incredibly wasteful of memory. There should be
a looping mechanism that generates the index variable values incrementally
as they are needed.
-- 
View this message in context: 
http://www.nabble.com/Python-%27for%27-loop-is-memory-inefficient-tp24980842p24980842.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


trouble with reload

2009-08-13 Thread Dr. Phillip M. Feldman

According to the Python documentation, 'reload' reloads a previously imported
module (so that changes made via an external editor will be effective). 
But, when I try to use this command, I get the following error message:

TypeError: reload() argument must be module

Any suggestions will be appreciated.
-- 
View this message in context: 
http://www.nabble.com/trouble-with-reload-tp24956946p24956946.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: trouble with reload

2009-08-13 Thread Dr. Phillip M. Feldman

Actually, I've tried both of these, and I get (different) errors in both
cases:

In [1]: from mymath import *

In [2]: reload(mymath)
NameError: name 'mymath' is not defined

In [3]: reload('mymath')
TypeError: reload() argument must be module


Rami Chowdhury wrote:
 
 Could you please clarify how you're calling it? E.g.
   reload('foo')
 or
   reload(foo)
 
 ?
 
 On Thu, 13 Aug 2009 12:05:26 -0700, Dr. Phillip M. Feldman  
 pfeld...@verizon.net wrote:
 
 According to the Python documentation, 'reload' reloads a previously  
 imported
 module (so that changes made via an external editor will be effective).
 But, when I try to use this command, I get the following error message:

 TypeError: reload() argument must be module

 Any suggestions will be appreciated.
 
 
 
 -- 
 Rami Chowdhury
 Never attribute to malice that which can be attributed to stupidity --  
 Hanlon's Razor
 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)
 -- 
 http://mail.python.org/mailman/listinfo/python-list
 
 

-- 
View this message in context: 
http://www.nabble.com/trouble-with-reload-tp24956946p24965811.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


How to comment on a Python PEP?

2009-08-06 Thread Dr. Phillip M. Feldman

Is there a mechanism for submitting comments on a Python PEP?
-- 
View this message in context: 
http://www.nabble.com/How-to-comment-on-a-Python-PEP--tp24840417p24840417.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


trouble with complex numbers

2009-08-05 Thread Dr. Phillip M. Feldman

When I try to compute the phase of a complex number, I get an error message:

In [3]: from cmath import *
In [4]: x=1+1J
In [5]: phase(x)
snip
NameError: name 'phase' is not defined
snip
AttributeError: 'complex' object has no attribute 'phase'

Any advice will be appreciated.
-- 
View this message in context: 
http://www.nabble.com/trouble-with-complex-numbers-tp24821423p24821423.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: trouble with complex numbers

2009-08-05 Thread Dr. Phillip M. Feldman

I am using Python 2.5, and most of the cmath functions are not yet available
in this version.  Thanks!

Phillip

P.S. In your code, that should be x+= 0J

P.P.S. I wish that the documentation indicated anything that is new.


Christian Heimes-2 wrote:
 
 snip
 
 phase() has been added to Python 2.6 and 3.0. It's not available in 
 Python 2.5 and earlier. If you'd used cmath.phase() instead of the ugly 
 from cmath import * statement you'd have seen the correct error message.
 
 You can write your own phase() function. This function is mostly correct 
 unless either the real and/or the imag part is NaN or INF.
 
 from math import atan2
 
 def phase(z):
  z += 1j # convert int, long, float to complex
  return atan2(z.imag, z.real)
 
 -- 
 http://mail.python.org/mailman/listinfo/python-list
 
 

-- 
View this message in context: 
http://www.nabble.com/trouble-with-complex-numbers-tp24821423p24835436.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


possible to round number and convert to string?

2009-07-31 Thread Dr. Phillip M. Feldman

I'd like to be able to convert a float to a string representation in which
the number is rounded to a specified number of digits.  If num2str is a
hypothetical function that does this, then num2str(pi,3) would be '3.142'
(not '3.141').  I've been told that there is no such function in Python.  I
tried to write this myself, but wasn't successful.  Any suggestions will be
appreciated.
-- 
View this message in context: 
http://www.nabble.com/possible-to-round-number-and-convert-to-string--tp24763821p24763821.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: possible to round number and convert to string?

2009-07-31 Thread Dr. Phillip M. Feldman

This was very close to what I wanted.  Thanks!  My final code looks like
this:

def num2str(x,f=4):
   Convert x (int or float) to a string with f digits to right of
   the decimal point.  f may be zero or negative, in which case the decimal
   point is suppressed.
   s= str(round(x,f))
   if f=0:
  # Delete decimal point:
  i= s.find('.')
  if i0: s= s[:i]
   return s
-- 
View this message in context: 
http://www.nabble.com/possible-to-round-number-and-convert-to-string--tp24763821p24764948.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


delayed sys.exit?

2009-07-29 Thread Dr. Phillip M. Feldman

In the attached  http://www.nabble.com/file/p24726902/test.py test.py code,
it appears that additional statements execute after the call to sys.exit(0). 
I'll be grateful if anyone can shed light on why this is happening.  Below
is a copy of some sample I/O.  Note that in the last case I get additional
output after what should be the final error message.

In [126]: run test
Input a string: 1,2
[1, 2]

In [127]: run test
Input a string: 1-3
[1, 2, 3]

In [128]: run test
Input a string: 1,4,5-12
[1, 4, 5, 6, 7, 8, 9, 10, 11, 12]

In [129]: run test
Input a string: 0
ERROR: 0 is invalid; run numbers must be positive.
ERROR: '0' is not a valid run number.


-- 
View this message in context: 
http://www.nabble.com/delayed-sys.exit--tp24726902p24726902.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: list vs. tuple [Re: len() should always return something]

2009-07-24 Thread Dr. Phillip M. Feldman

isinstance(x, (int, float, complex))

is certainly very compact, and does what I want.  Thanks!
-- 
View this message in context: 
http://www.nabble.com/len%28%29-should-always-return-something-tp24639361p24654347.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: len() should always return something

2009-07-24 Thread Dr. Phillip M. Feldman

As far as I know, there is no programming language which treats scalars like
ints as if they were 
vectors of length 1

Actually, Matlab does:

 length(5)
ans =
 1
 
-- 
View this message in context: 
http://www.nabble.com/len%28%29-should-always-return-something-tp24639361p24654358.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: len() should always return something

2009-07-24 Thread Dr. Phillip M. Feldman

Here's a simple-minded example:

def dumbfunc(xs):
   for x in xs:
  print x

This function works fine if xs is a list of floats, but not if it is single
float.  It can be made to work as follows:

def dumbfunc(xs):
   if isinstance(xs,(int,float,complex)): xs= [xs]
   for x in xs:
  print x

Having to put such extra logic into practically every function is one of the
annoying things about Python.

Phillip


Diez B. Roggisch-2 wrote:
 
 Dr. Phillip M. Feldman schrieb:
 Some aspects of the Python design are remarkably clever, while others
 leave
 me perplexed. Here's an example of the latter: Why does len() give an
 error
 when applied to an int or float? len() should always return something; in
 particular, when applied to a scalar, it should return a value of 1. Of
 course, I can define my own function like this:
 
 def mylen(x):
if isinstance(x,int) or isinstance(x,float): return 1
return len(x)
 
 But, this shouldn't be necessary.
 
 Can you show some example of where that is actually making a piece of 
 code more elegant?
 
 Diez
 -- 
 http://mail.python.org/mailman/listinfo/python-list
 
 

-- 
View this message in context: 
http://www.nabble.com/len%28%29-should-always-return-something-tp24639361p24654439.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: missing 'xor' Boolean operator

2009-07-17 Thread Dr. Phillip M. Feldman

Suppose that 'xor' returns the value that is true when only one value is
true, and False otherwise.  This definition of xor doesn't have the standard
associative property, that is,

(a xor b) xor c

will not necessarily equal

a xor (b xor c)

To see that this is the case, let a= 1, b= 2, and c= 3.

(a xor b) xor c

yields 3, while

a xor (b xor c)

yields 1.  So, I'd prefer an xor operator that simply returns True or False.

Phillip


MRAB-2 wrote:
 
 
 snip
 
 What values should 'xor' return? IMHO, if only one of the values is true
 then it should return that value, otherwise it should return False.
 
  1 xor 0 = 1
  0 xor 2 = 2
  1 xor 2 = False
  0 xor 0 = False
 
 This is because it's a Boolean operator, so it should fall back to
 Boolean values when necessary, like 'not':
 
  not 0 = True
  not 1 = False
 
 Also:
 
  x and y and z = (x and y) and z
  x or y or z = (x or y) or z
 
 therefore:
 
  x xor y xor z = (x xor y) xor z
 -- 
 http://mail.python.org/mailman/listinfo/python-list
 
 

-- 
View this message in context: 
http://www.nabble.com/missing-%27xor%27-Boolean-operator-tp24485116p24543805.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


PDF version of Python Tutorial?

2009-07-17 Thread Dr. Phillip M. Feldman

Does anyone know if there is a PDF version of the Python Tutorial (URL=
http://www.python.org/doc/current/tutorial/)?
-- 
View this message in context: 
http://www.nabble.com/PDF-version-of-Python-Tutorial--tp24543817p24543817.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: missing 'xor' Boolean operator

2009-07-15 Thread Dr. Phillip M. Feldman

I did initially ask for an infix xor operator, but eventually gave up on
this.  I like the first of your two one-line solutions below; this is clean
and easy to understand.  Thanks!  I'd still like to be able to write an
expression like '(a and b) xor (c and d) xor (e and f)', but it looks as
though that can't be done.



snip

Well, that's not exactly what you originally asked for.  But it's
still a one-liner:

def xor(*args): return bool(sum(map(bool, args)) % 2)

or perhaps

def xor(*args): return bool(len(filter(None, args))  1)
-- 
View this message in context: 
http://www.nabble.com/missing-%27xor%27-Boolean-operator-tp24485116p24503248.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: missing 'xor' Boolean operator

2009-07-14 Thread Dr. Phillip M. Feldman

I appreciate the effort that people have made, but I'm not impressed with any
of the answers.  For one thing, xor should be able to accept an arbitrary
number of input arguments (not just two), and should return True if and only
if the number of input arguments that evaluate to True is odd (see
www.mathworld.com article on xor).  Here's my code:

def xor(*args):
   xor accepts an arbitrary number of input arguments, returning True
   if and only if bool() evaluates to True for an odd number of the input
   arguments.

   result= False

   for arg in args:
  if bool(arg): result= not result

   return result



MRAB-2 wrote:
 
 Ethan Furman wrote:
 Robert Kern wrote:
 On 2009-07-14 14:56, Dr. Phillip M. Feldman wrote:

 != does do what I want, except that it doesn't indicate to someone 
 reading
 the code that the operands are being treated as logicals.  
 (Readability is
 supposed to be one of the major selling points of Python).  But, this
 is
 probably good enough.


 In the words of those greater than myself, Not every one-liner needs 
 to be in the standard library.

 def xor(a, b):
 return bool(a) != bool(b)

 
 Let's see...
 
   and returns the last object that is true
   or  returns the first object that is true
 
 so should xor return the only object that is true, else False/None?
 
 def xor(a, b)
 if a and b:
 return None
 elif a:
 return a
 elif b:
 return b
 else:
 return None
 
 How about:
 
 def xor(a, b):
  return not b and a or not a and b
 -- 
 http://mail.python.org/mailman/listinfo/python-list
 
 

-- 
View this message in context: 
http://www.nabble.com/missing-%27xor%27-Boolean-operator-tp24485116p24491580.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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