Question about generators

2009-07-12 Thread Cameron Pulsford
Hey everyone, I have this small piece of code that simply finds the  
factors of a number.


import sys

def factor(n):
primes = (6*i+j for i in xrange(1, n) for j in [1, 5] if (i+j)%5 ! 
= 0)


factors = []

for i in [2, 3, 5]:
while n % i == 0:
n /= i
factors.append(i)
for i in primes:
while n % i == 0:
n /= i
factors.append(i)
print factors

factor(int(sys.argv[1]))

My question is, is it possible to combine those two loops? The primes  
generator I wrote finds all primes up to n, except for 2, 3 and 5, so  
I must check those explicitly. Is there anyway to concatenate the hard  
coded list of [2,3,5] and the generator I wrote so that I don't need  
two for loops that do the same thing?


I tried writing a primes function using yield statements, but it  
didn't work like I thought it would.

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


Re: Question about generators

2009-07-12 Thread Cameron Pulsford

itertools.chain() did it, thanks!

As far as the primes generator, it does not generate any non-primes.  
All primes (except 2, 3 and 5) are in the form (6*x + 1, 6*x + 5)  
where is x is [1, 2, ..., n]. The only time it doesn't generate a  
prime is when x + (1 or 5) % 5 == 0. Which is what that last part is  
making sure doesn't happen. I'm not a mathematician or anything so  
correct me if I'm wrong, but that's what I've read.


Also sorry if this was piggy backed, I started the thread as a fresh e- 
mail to python-list@python.org, sorry if I messed something up!


On Jul 12, 2009, at 8:15 PM, Terry Reedy wrote:


Cameron Pulsford wrote:

When you start a new thread, you should start a new thread and not  
piggyback on an existing thread.


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


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


Re: Question about generators

2009-07-12 Thread Cameron Pulsford
I read it on the haskell site in their sieves/prime wheel section, I  
guess I misunderstood something. (east to do over there...) I did  
verify it against established list of primes and other generators I've  
written that use more normal methods, but I only hand verified it.


It is at least interesting though, I can probably extend it to check  
for primality by using a more normal sieve method. It might be pretty  
fast too because generally it does only generate primes, and the few  
non primes it does generate could be caught quickly using a scratching  
out technique.


When I was initially looking at it there are some interesting patterns  
I might be able to extend into a generator that would yield only  
correct sets of numbers for the 6x + n pattern.



On Jul 12, 2009, at 10:26 PM, John Machin wrote:


On Jul 13, 11:24 am, Cameron Pulsford cameron.pulsf...@gmail.com
wrote:


As far as the primes generator, it does not generate any non-primes.
All primes (except 2, 3 and 5) are in the form (6*x + 1, 6*x + 5)
where is x is [1, 2, ..., n]. The only time it doesn't generate a
prime is when x + (1 or 5) % 5 == 0. Which is what that last part is
making sure doesn't happen. I'm not a mathematician or anything so
correct me if I'm wrong, but that's what I've read.


Where did you read that? Have you tried to verify it, like this:

|  [6*i+j for i in range(1, 21) for j in (1, 5) if (i+j) % 5]
| [7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 49, 53, 59, 61, 67,
71, 73, 77, 79, 83, 89, 91, 97, 101, 103, 107, 109, 113, 119, 121]

49, 77, 91, and 121 are not prime.

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


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


Problem with list of dicts and copying

2009-07-08 Thread Cameron Pulsford
Hello all, I'm redoing a sudoku solver of mine and I ran into an issue with
lists of dicts. Bear with me for a second before I get to the actual
problem... I'm representing the board as a dictionary, where the keys are
(x, y) positions, and the values are candidates. So my program goes along
picking numbers from the list of candidates and then propagating the
constraints. So it might place a 6, which would then remove 6 as a candidate
from that row column and grid. However, that might leave a spot with no
candidates, which means we placed a legal but not correct number. This is
where my problem arises. I keep a running list of the boards which is
updated every time I find a legal number that doesn't invalidate the boards.
I add onto this list by doing boards.append(self.board.copy()). When I
place a legal but invalid number I do self.board = boards[-1].copy() to
return the board to the last known good state. And when I completely exhaust
the candidates for a spot and must backtrack to a different spot (instead of
simply trying a different candidate of the current spot) I do self.board =
boards[-1].copy() and then del boards[-1]
Basically my boards list should be copies of good boards, and when I need to
refresh the current board, I want to pull off a copy of the correct one.
Essentially (after watching the debugging output) it looks like this isn't
happening. I am always modifying the same board. The algo follows, and I can
post the rest of the code if necessary. So am I using the dict.copy() wrong?
Am I guessing I have a tricky problem with the = in self.board =
boards[-1].copy()

def solve(self):
previousValue = dict((blank, 0) for blank in self.blanks())
self.fillInCandidates()
continuing, boards, guesses = False, [self.board.copy()], 0
while len(self.blanks())  0:
if continuing == False:
cp = self.mrv()
continuing = False
nl = self.nextLegal(cp, previousValue[cp])
previousValue[cp] = nl
if nl != 0:
self.board[cp] = nl
guesses += 1
self.update(nl, cp[0], cp[1])
if self.isNotLegal():
continuing = True
self.board = boards[-1].copy()
else:
boards.append(self.board.copy())
else:
previousValue[cp] = 0
self.board = boards[-1].copy()
del boards[-1]
-- 
http://mail.python.org/mailman/listinfo/python-list


Help with dictionaries and multidimensial lists

2009-06-23 Thread Cameron Pulsford
Hey all, I have a dictionary that looks like this (small example version)
{(1, 2): 0} named a

so I can do a[1,2] which returns 0. What I also have is a list of
coordinates into a 2 dimensional array that might look like this b =
[[1,2]]. Is there anyway I can call a[b[0]] and have it return 0?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with dictionaries and multidimensial lists

2009-06-23 Thread Cameron Pulsford
Thanks!

On Tue, Jun 23, 2009 at 11:29 AM, Jaime Fernandez del Rio 
jaime.f...@gmail.com wrote:

 On Tue, Jun 23, 2009 at 4:45 PM, Cameron
 Pulsfordcameron.pulsf...@gmail.com wrote:
  Hey all, I have a dictionary that looks like this (small example version)
  {(1, 2): 0} named a
 
  so I can do a[1,2] which returns 0. What I also have is a list of
  coordinates into a 2 dimensional array that might look like this b =
  [[1,2]]. Is there anyway I can call a[b[0]] and have it return 0?

 a[tuple(b[0])] should do it...

 Jaime

 --
 (\__/)
 ( O.o)
 (  ) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus
 planes de dominación mundial.

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


Pythonic way to overwrite a file

2009-06-17 Thread Cameron Pulsford
Hey all, hopefully a simple question.
I'm writing a simple python tool that opens a file, and does something like

for line in file.readlines():
temp.write(line.doStuff())

However, I want to provide the option do this in place, as in have the
destination file be the same as the source file. Currently, I am writing to
a temp file and then using os.system('mv %s %s' % (dstfile, srcfile)) to
copy the destination file onto the soruce file. This is extremely ugly
though, and will only work on unix based systems (I'm guessing, unless
windows has mv too). Is there a more pythonic way to do this? Ideally I'd
like to change the file as I go through it and not deal with a second file
at all. That wouldn't have any atomicity though... What would be the most
pythonic+safest way to do this?

Thanks in advance
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic way to overwrite a file

2009-06-17 Thread Cameron Pulsford
Essentially it just cleans up a source file of erroneous spaces and tabs and
can also convert tabs to spaces so loading the whole file into memory is
possibly an option. I am making this utility for personal use, and that
would definitely be fine, but if it turned out well I'd open source it and
then I wouldn't be so sure. This is only supposed to handle text files, so
when would reading it all into memory become too much for most computers?
I'm guessing there aren't many source files of too great a size.

On Wed, Jun 17, 2009 at 2:09 PM, Jean-Michel Pichavant 
jeanmic...@sequans.com wrote:

 Cameron Pulsford wrote:

 Hey all, hopefully a simple question.

 I'm writing a simple python tool that opens a file, and does something
 like

 for line in file.readlines():
temp.write(line.doStuff())

 However, I want to provide the option do this in place, as in have the
 destination file be the same as the source file. Currently, I am writing to
 a temp file and then using os.system('mv %s %s' % (dstfile, srcfile)) to
 copy the destination file onto the soruce file. This is extremely ugly
 though, and will only work on unix based systems (I'm guessing, unless
 windows has mv too). Is there a more pythonic way to do this? Ideally I'd
 like to change the file as I go through it and not deal with a second file
 at all. That wouldn't have any atomicity though... What would be the most
 pythonic+safest way to do this?
 Thanks in advance


 Altering directly the file is dangerous, what if something goes wrong
 during the process ?
 Create a temp file and copying it if successful is your best bet.

 I guess using python modules like tempfile and shutil are  a pythonic way
 to do it :

 import tempfile
 import shutil

 In [14]: tempfile.NamedTemporaryFile?
 Definition: tempfile.NamedTemporaryFile(mode='w+b', bufsize=-1,
 suffix='', prefix='tmp', dir=None)
 Docstring:
   Create and return a temporary file.
   Arguments:
   'prefix', 'suffix', 'dir' -- as for mkstemp.
   'mode' -- the mode argument to os.fdopen (default w+b).
   'bufsize' -- the buffer size argument to os.fdopen (default -1).
   The file is created as mkstemp() would do it.

   Returns an object with a file-like interface; the name of the file
   is accessible as file.name.  The file will be automatically deleted
   when it is closed.


 In [7]: shutil.copy?
 Definition: shutil.copy(src, dst)
 Docstring:
   Copy data and mode bits (cp src dst).

   The destination may be a directory.



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


Reading and setting file permissions programmatically

2009-06-17 Thread Cameron Pulsford
Sorry to flood the list but my google fu isn't up to par today I guess.
Basically, is it possible to read the permissions on one file and then set
the permissions of another file to the ones we just read? os.dup2 seemed
like it would work but I might not be using it correctly.

I know there is os.chmod, but I haven't found the equivalent to read
permissions. Preferably this would work on unix and windows too.
-- 
http://mail.python.org/mailman/listinfo/python-list


NameError function not found

2009-05-29 Thread Cameron Pulsford
Hey everyone, I am extremely stumped on this. I have 2 functions..

def _determinant(m):
   return m[0][0] * m[1][1] - m[1][0] * m[0][1]

def cofactor(self):
   Returns the cofactor of a matrix.
   newmatrix = []
   for i, minor in enumerate(self.minors()):
   newmatrix.append(_determinant(minor.matrix) * ((i%2) * -1))
   return newmatrix

And I get the following error when I try to run a.cofactor()...

NameError: global name '_determinant' is not defined

When I put the _determinant function nested within the cofactor function it
works fine. Normally I would do this, but a lot of other methods use the
_determinant method. They are both in the same class, and they are at the
same level, they are even in that order so I know it should be  able to see
it. I have a lot of functions that call other functions in this class and
everything is fine. [Also for the picky, I know my cofactor method isn't
mathematically correct yet ;-) ] Am I missing something obvious here? Also
if it helps the rest of the code is here
http://github.com/dlocpuwons/pymath/blob/d1997329e4473f8f6b5c7f11635dbd719d4a14fa/matrix.py
though
it is not the latest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with objects copying each other in memory

2009-02-12 Thread Cameron Pulsford
Thanks, that did it! Why is that the case though? Or rather, why do  
the assignments to temp.x and temp.y not effect the self.x and self.y?  
How come I only run into the problem with the list?



On Feb 12, 2009, at 5:15 PM, andrew cooke wrote:



you're setting the new knight's sl to the value self.sl and then  
adding

values to it.  that's the same list - so you are adding values to the
self.sl list when you add them to the knight's sl.

this is easier to understand just by seeing the fix, which is to use:

temp = Knight(self.x, self.y, self.g, self.h, self.gp, list(self.sl))

which will make a new copy of the list, so you are only adding to  
the sl

in the (new) knight.

andrew



dlocpuwons wrote:

Using Python 2.6.1...

I am (attempting) to make an A* search for a chess problem, but I am
running into a really annoying shared memory issue in my successor
function. Here it is stripped down to the important parts that relate
to my problem.

def successors(self):
result = []
moves = [[2, 1], [2, -1], [-2, 1], [-2, -1], [1, 2], [1, -2], 
[-1,
2], [-1, -2]] #possible moves for a knight

for i in moves:
temp = Knight(self.x, self.y, self.g, self.h, self.gp, 
self.sl)
temp.x += i[0]
temp.y += i[1]
			temp.sl.append([temp.x, temp.y]) #Adds the new current state to  
the

visited states list
result.append(temp)
return result

The method creates a temporary Knight object, increments it to the  
new

position and then adds this new position to its list of visited
states. Then it returns a list of these 8 new objects. The problem
seems to be with the result.sl.append() line. As the method chugs
along and creates the new objects the temp.sl lines seems to stay  
in

memory, so when the method is done all the new objects have all the
new states that were made over the course of the method instead of
just their own created in the loop. For example when I try to get
successors for a piece that is initially at (2,2) with no previously
visited states, the method prints this out for the sl (state list)
value

[[2, 2], [4, 3], [4, 1], [0, 3], [0, 1], [3, 4], [3, 0], [1, 4], [1,
0]]
[[2, 2], [4, 3], [4, 1], [0, 3], [0, 1], [3, 4], [3, 0], [1, 4], [1,
0]]
[[2, 2], [4, 3], [4, 1], [0, 3], [0, 1], [3, 4], [3, 0], [1, 4], [1,
0]]
[[2, 2], [4, 3], [4, 1], [0, 3], [0, 1], [3, 4], [3, 0], [1, 4], [1,
0]]
[[2, 2], [4, 3], [4, 1], [0, 3], [0, 1], [3, 4], [3, 0], [1, 4], [1,
0]]
[[2, 2], [4, 3], [4, 1], [0, 3], [0, 1], [3, 4], [3, 0], [1, 4], [1,
0]]
[[2, 2], [4, 3], [4, 1], [0, 3], [0, 1], [3, 4], [3, 0], [1, 4], [1,
0]]
[[2, 2], [4, 3], [4, 1], [0, 3], [0, 1], [3, 4], [3, 0], [1, 4], [1,
0]]

but what it should print out is

[[2, 2], [4, 3]]
[[2, 2], [4, 1]]
[[2, 2], [0, 3]]
[[2, 2], [0, 1]]
[[2, 2], [3, 4]]
[[2, 2], [3, 0]]
[[2, 2], [1, 4]]
[[2, 2], [1, 0]]

It sort of seems like python is trying to be too smart and is trying
to keep things in memory. Is there anyway to work around this?
--
http://mail.python.org/mailman/listinfo/python-list







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