Re: some OT: how to solve this kind of problem in our program?

2006-12-24 Thread Paul McGuire
"oyster" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> 1. first of all, what is the English jargon (Optimize? But I think
> this is not a very good keyword :( )for this problem? So I can use it
> to search on the internet
> 2. is there any free/open lib for this?
> 3. I know for some questions(case 1, case 2, and sudoku), we can use
> bundles of "FOR...NEXT" loop to program. however I think it is clumsy
> and inconvenient, especially when there is many vars
> 4. I don't know how to deal with case 3 and case 4
>
>
> case:
> 1. choose x0~x9 from 1~9, and must use all of 1~9, let
> x0/(10*x1+x2)+x3/(10*x4+x5)+x6/(10*x7+x8)=1/2
>

Since you are working with permutations of [1..9], here is a general 
framework for problems using those permutations - put your problem 
definition in the function func, which is successively passed each of the 
362880 permutations of the numbers 1-9.  On my system, your original code 
ran in about 11 seconds, and after factoring out invariants, got down to 
about 1.8 seconds.  This little framework takes about 4.5 seconds, but with 
psyco, cuts down to about 1.3 seconds.

-- Paul


import time
try:
  import psyco
  psyco.full()
except:
  pass

def prod(lst):
return reduce(lambda a,b:a*b,lst,1)

def perms(setSize, sampleSize):
return prod(xrange(setSize-sampleSize+1,setSize+1))

def permutation(k, s):
fact = 1
s = s[:]
for j in xrange( 2, len(s)+1):
fact = fact * (j-1)
idx1 = j - ((k / fact) % j)-1
idx2 = j-1
s[idx1],s[idx2] = s[idx2],s[idx1]
return s

def permutations(s,sampleSize=None):
if sampleSize is None:
sampleSize = len(s)
k = perms(len(s),sampleSize)
for i in xrange(k):
yield permutation(i,s)

d0,d1 = 1,2
def func(p):
a0,a1,a2,b0,b1,b2,c0,c1,c2 = p

# do application evaluation here
b1b2 = 10*b1+b2
a1a2 = 10*a1+a2
c1c2 = 10*c1+c2
if d1*a0*b1b2*c1c2 + d1*b0*a1a2*c1c2 + d1*c0*a1a2*b1b2 == 
d0*a1a2*b1b2*c1c2:
return sorted( [[a0, a1, a2], [b0, b1, b2], [c0, c1, c2]] )
else:
return None

st = time.time()
result = []
for p in permutations(range(1,10)):
aresult = func(p)
if aresult is not None and aresult not in result:
result.append(aresult)

et=time.time()
print 'time elapsed: %.4f s' % (et-st)
for [[a0, a1, a2], [b0, b1, b2], [c0, c1, c2]] in result:
  print '  %0d %0d %0d %0d' % (a0, b0, c0, d0)
  print '--- + --- + --- = ---'
  print ' %0d%0d%0d%0d%0d%0d %0d' %(a1, a2, b1, b2, c1,c2, d1)
  print


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


Re: Newbie: what is a usefull IDE for Python on Windows ?

2006-12-24 Thread Riquelme
Eclipse + Editplus

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


Re: some OT: how to solve this kind of problem in our program?

2006-12-24 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, oyster wrote:

> 1. first of all, what is the English jargon (Optimize? But I think
> this is not a very good keyword :( )for this problem? So I can use it
> to search on the internet
> 2. is there any free/open lib for this?
> 3. I know for some questions(case 1, case 2, and sudoku), we can use
> bundles of "FOR...NEXT" loop to program. however I think it is clumsy
> and inconvenient, especially when there is many vars
> 4. I don't know how to deal with case 3 and case 4
> 
> 
> case:
> 1. choose x0~x9 from 1~9, and must use all of 1~9, let
> x0/(10*x1+x2)+x3/(10*x4+x5)+x6/(10*x7+x8)=1/2
> 
> 2. choose x0~x15 from 1~16, and must use all of 1~16, let
> +-+-+-+-+
> |  x0 |  x1 |  x2 |  x3 |
> +-+-+-+-+
> |  x4 |  x5 |  x6 |  x7 |
> +-+-+-+-+
> |  x8 |  x9 | x10 | x11 |
> +-+-+-+-+
> | x12 | x13 | x14 | x15 |
> +-+-+-+-+
> 
> sum of every column =sum of of every row
> = x0+x5+x10+x11 =x3+x6+x9+x12

The first two can be solved by a finite domain constraint solver.  Logilab
has a pure-python package:

http://www.logilab.org/view?rql=Any%20X%20WHERE%20X%20eid%20852

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: consequence and life

2006-12-24 Thread Lester Mosley
I alway wondered if you are smelling a flower in a dream while on some
crazy herbal medication. are you smelling the flower that is in the
drug or a a flower that you once smelled when you were three years old
on your daddy's knee ofr when you were bent over in the park looking
for your lost keys.


marika wrote:
> 'The mind can make
> >Substance, and people planets of its own
> >With beings brighter than have been, and give
> >A breath to forms which can outlive all flesh.'
> >
> >Byron - 'The
> Dream' 1816 st.1

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


Re: split string with hieroglyphs

2006-12-24 Thread Belize
Steven, thanks! Very nice algorithm.
Here is code:


#!/usr/bin/env python
# -*- coding: utf_8 -*-

# Thanks Steven D'Aprano for hints

import unicodedata
import MySQLdb

#MySQL variables
mysql_host = "localhost"
mysql_user = "dict"
mysql_password = "passwd"
mysql_db = "dictionary"

try:
mysql_conn = MySQLdb.connect(mysql_host, mysql_user, mysql_password,
mysql_db)
cur = mysql_conn.cursor()
cur.execute("""SET NAMES UTF8""")
except:
print "unable insert to MySQL, check connection"

jap_text = "BZツーリTVツキDVD?"
jap_text = unicode(jap_text, 'utf-8') # fight with
full-width, half-width katakana madness :-)
jap_text = unicodedata.normalize('NFKC', jap_text)  #
jap_text = jap_text.encode('utf-8')   #

def translate_hieroglyph(jap_text):
eng_text = ""
mysql_translate_query = "SELECT Eng FROM dictionary where Jis='%s'
collate utf8_unicode_ci LIMIT 1" % jap_text
cur.execute(mysql_translate_query)
mysql_trans_data = cur.fetchall()
for line in mysql_trans_data:
eng_text = line[0]
if not eng_text:
eng_text = jap_text
return eng_text

def islatin(s):
try:
unicode(s, 'ascii')
except UnicodeError:
pass
else:
return True

def split_fragments(s):
fragments = []
latin = []
nonlatin = []
for c in s:
if islatin(c):
if nonlatin:
fragments.append(''.join(nonlatin))
nonlatin = []
latin.append(c)
else:
if latin:
fragments.append(''.join(latin))
latin = []
nonlatin.append(c)
if latin:  # without
this we lose last fragment
fragments.append(''.join(latin)) #
else: #
fragments.append(''.join(nonlatin)) #
return fragments

fragments = split_fragments(jap_text)

def join_fragments(fragments):
accumulator = []
for fragment in fragments:
if islatin(fragment):
accumulator.append(fragment)
else:
accumulator.append(translate_hieroglyph(fragment))
return ' '.join(accumulator)

print join_fragments(fragments)


[EMAIL PROTECTED] ~/Src/Code $ python translate.py
BZ navigation TV display DVD?

Work as needed :-) Thanks again!

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

Connection python with C

2006-12-24 Thread Χρυσάνθη Αϊναλή
Hi..

I want to connect a script in python with a source code in C. Any
ideas about it?

Thank you!

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


Re: Connection python with C

2006-12-24 Thread Fredrik Lundh
Χρυσάνθη Αϊναλή wrote:

> I want to connect a script in python with a source code in C. Any
> ideas about it?

http://docs.python.org/lib/module-ctypes.html
http://docs.python.org/ext/ext.html
http://effbot.org/pyfaq/extending-index.htm



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

Re: some OT: how to solve this kind of problem in our program?

2006-12-24 Thread bearophileHUGS
Paul McGuire:
> This little framework takes about 4.5 seconds, but with
> psyco, cuts down to about 1.3 seconds.
>
> st = time.time()
> result = []
> for p in permutations(range(1,10)):
> aresult = func(p)
> if aresult is not None and aresult not in result:
> result.append(aresult)
>
> et=time.time()
> print 'time elapsed: %.4f s' % (et-st)
> for [[a0, a1, a2], [b0, b1, b2], [c0, c1, c2]] in result:
>   print '  %0d %0d %0d %0d' % (a0, b0, c0, d0)
>   print '--- + --- + --- = ---'
>   print ' %0d%0d%0d%0d%0d%0d %0d' %(a1, a2, b1, b2, c1,c2, d1)
>   print

If you want to more speed, put long loops always inside functions, not
inside the main body:

def main():
st = clock()
result = []
for p in permutations(range(1, 10)):
aresult = func(p)
if aresult is not None and aresult not in result:
result.append(aresult)

et = clock()
print 'time elapsed: %.4f s' % (et-st)
for [[a0, a1, a2], [b0, b1, b2], [c0, c1, c2]] in result:
  print '  %0d %0d %0d %0d' % (a0, b0, c0, d0)
  print '--- + --- + --- = ---'
  print ' %0d%0d%0d%0d%0d%0d %0d' %(a1, a2, b1, b2,
c1,c2, d1)
  print

main()

If you have a bit of time you can test the speed of this code on your
computer.

Bye,
bearophile

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


Re: removing the header from a gzip'd string

2006-12-24 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> Essentially, they note that the NCD does not always bevave like a
> metric and one reason they put forward is that this may be due to the
> size of the header portion (they were using the command line gzip and
> bzip2 programs) compared to the strings being compressed (which are on
> average 48 bytes long).

gzip datastreams have a real header, with a file type identifier, 
optional filenames, comments, and a bunch of flags.

but even if you strip that off (which is basically what happens if you 
use zlib.compress instead of gzip), I doubt you'll get representative 
"compressability" metrics on strings that short.  like most other 
compression algorithms, those algorithms are designed for much larger 
datasets.



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


Re: Help please using telnetlib module

2006-12-24 Thread Birdman
Simplest explanation is that you can't do a 'show run' from global
configuration mode

try something like

#exit global configuration mode
tn.write('end\n')
print tn.read_until('#')

#disable pause after 24 lines
tn.write('term len 0\n')
tn.read_until('#')

#now show the entire running-config
tn.write('show run\n')
print tn.read_until('#')

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


Re: some OT: how to solve this kind of problem in our program?

2006-12-24 Thread BJörn Lindqvist
On 12/24/06, oyster <[EMAIL PROTECTED]> wrote:
> 1. first of all, what is the English jargon (Optimize? But I think
> this is not a very good keyword :( )for this problem? So I can use it
> to search on the internet

The first problem is a magic square. The general term for all your
problems are constraint satisfaction problems.

> 2. is there any free/open lib for this?

Yes, this for example: http://labix.org/python-constraint

> 3. I know for some questions(case 1, case 2, and sudoku), we can use
> bundles of "FOR...NEXT" loop to program. however I think it is clumsy
> and inconvenient, especially when there is many vars

Yes. I think it is also very much unoptimal. For solving problems such
as magic squares and sudoku puzzles you want a recursive backtracking
constraint solver.

> case:
> 1. choose x0~x9 from 1~9, and must use all of 1~9, let
> x0/(10*x1+x2)+x3/(10*x4+x5)+x6/(10*x7+x8)=1/2

Using the linked to constraint solver, you could write something like this:

p = Problem()
# Ten variables named 0..9 all with values in the domain 0..9
p.addVariables(range(10), range(10))
p.addConstraint(AllDifferentConstraint(), range(10))

def eqConstraint(*x):
t = x[0]/(10*x[1] + x[2]) + x[3]/(10 * x[4] + x[5]) + x[5](10 * x[7] + x[8])
# Convert to int to get rid of rounding errors
t = int(t * 2)
return t == 1
p.addConstraint(eqConstraint, range(10))
p.getSolutions()

> 2. choose x0~x15 from 1~16, and must use all of 1~16, let
> +-+-+-+-+
> |  x0 |  x1 |  x2 |  x3 |
> +-+-+-+-+
> |  x4 |  x5 |  x6 |  x7 |
> +-+-+-+-+
> |  x8 |  x9 | x10 | x11 |
> +-+-+-+-+
> | x12 | x13 | x14 | x15 |
> +-+-+-+-+
>
> sum of every column =sum of of every row
> = x0+x5+x10+x11 =x3+x6+x9+x12

Similar to above, just enter all the constraints and let the library
do the hard work:

def lineConstraint(*l):
s1 = sum(l[:4])
s2 = sum(l[4:])
return s1 == s2

# For magic squares, recursive backtracking solves are the best
p = Problem(RecursiveBacktrackingSolver())
p.addConstraint(AllDifferentConstraint())
p.addConstraint(lineConstraint, [0, 5, 10, 11, 3, 6, 9, 12])
... add more constraints...
p.getSolution()

HTH

-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


[pyOpenGL]Demo cannot run on Python2.5

2006-12-24 Thread sweetmelon
(I'm a newbie in Python and pyOpenGL.)
Environment:
WinXP SP2
Python ver. 2.5
WingIDE
easy_install is installed
PIL, pyNum is installed
Download PyOpenGL-3.0.0a5-py2.5.egg
run: easy_install PyOpenGL-3.0.0a5-py2.5.egg
pyOpenGL is installed in
D:\Python25\Lib\site-packages\PyOpenGL-3.0.0a5-py2.5.egg\

I tried to run a example ".\OpenGL\Demo\da\dots.py", but it fails in
the line:
 from OpenGL.GL import *
with errors:
 AttributeError: 'WinFunctionType' object has no attribute
'returnValues'

Traceback (innermost last):

File "OpenGL\Demo\da\dots.py", line 1, in 
  #!/usr/bin/python
File "OpenGL\Demo\da\dots.py", line 24, in 
  from OpenGL.GL import *
File "OpenGL\GL\__init__.py", line 3, in 
  from OpenGL.raw.GL.annotations import *
File "OpenGL\raw\GL\annotations.py", line 19, in 
  'textures',
File "OpenGL\arrays\arrayhelpers.py", line 68, in setInputArraySizeType
  if not hasattr( function, 'returnValues' ):
File "OpenGL\wrapper.py", line 64, in __getattr__
  return getattr( self.wrappedOperation, key )

It seems that pyOpenGL reimplements the module "ctypes" internally, but
not finished I cannot find "self.wrappedOperation" with any
attribute with the name of 'returnValues'. How to go through this
problem? Did I make some simple mistakes at the beginning of the
installation of pyOpenGL?

Thank you!

ShenLei

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

Re: merits of Lisp vs Python

2006-12-24 Thread Juan R.
Fuzzyman ha escrito:

> Perhaps only with the addendum that although 'Lisp roolz', no-one uses
> for anything of relevance anymore and it is continuing it's geriatric
> decline into obscurity. ;-)

I do not think that i cannot agree with the contrary of this but i do
not think the contrary neither.

I am being said that LISP is being actively pursued by a number of
joung hackers as Graham and Tilton. Do not believe?

Ken Tilton has noticed that Dalai Lama has becomed interested in LISP
also.

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


problem with PIPE

2006-12-24 Thread Dhika Cikul
Hello,

I'm new in Python, i don't know my subject is correct or wrong. I have
problem with my script. I want to change password with passwd password
in python without user submitted anything from keyboard. I get
tutorial that i must use pipe to process this. And this is my code :

[code]

   1.
   2. #!/usr/bin/python
   3.
   4. import os
   5.
   6. COMMAND = 'passwd'
   7. PASSWD  = 'mypassword'
   8.
   9. # open a pipe to passwd program and
  10. # write the data to the pipe
  11. p = os.popen("%s" % COMMAND, 'w')
  12. p.write(PASSWD)
  13. p.write('\n')
  14. p.write(PASSWD)
  15. p.close()
  16.
[/code]


but i got this error :

[output]
[EMAIL PROTECTED] cp]$ ./password
Changing password for user cp.
Changing password for cp
(current) UNIX password: passwd: Authentication token manipulation error
[/output]

Anyone can help me how to write to pipe.. i try several method, and always fail.

Thank's
-- 
Dhika Cikul
-- 
http://mail.python.org/mailman/listinfo/python-list


Help with small program

2006-12-24 Thread smartbei
Hello, I am a newbie with python, though I am having a lot of fun using
it. Here is one of the excersizes I am trying to complete:
the program is supposed to find the coin combination so that with 10
coins you can reach a certain amoung, taken as a parameter. Here is the
current program:

coins = (100,10,5,1,0.5)
anslist = []
def bar(fin, hist = {100:0,10:0,5:0,1:0,0.5:0}):
s = sum(x*hist[x] for x in hist)
l = sum(hist.values())
if s < fin and l < 10:
for c in coins:
if (s+c) <= fin:
hist[c] += 1
bar(fin, hist)
hist[c] -= 1
elif l==10 and s==fin and not hist in anslist:
#p1
anslist.append(hist)

bar(50)
print anslist

The problem is that if I run it, anslist prints as [{0.5: 0, 1: 0, 10:
0, 100: 0, 5: 0}], which doesnt even add up to 50. When I check how
many times the program has reached the #p1 by sticking a print there,
it only reaches it once, and it comes out correct. why is it that this
result is replaced by the incorrect final one?

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


Re: regular expression

2006-12-24 Thread Dustan

Kleine Aap wrote:
> Asper Faner wrote:
>
> > I seem to always have hard time understaing how this regular expression
> > works, especially how on earth do people bring it up as part of
> > computer programming language. Natural language processing seems not
> > enough to explain by the way. Why no eliminate it ?
>
> I.M.H.O. anyone that is not capable to grasp the concept of regular
> expressions should not attempt to write computer programs at all! My
> suggestion to you would be to find a job that involves working with your
> hands...

Your humble opinion doesn't get much ruder...

Perhaps you meant "anyone that is not capable to grasp the concept of
regular expressions after some experience with programming should not
attempt to write computer programs at all!" Then at least newbies would
have a leg to stand on.

Otherwise, you're practically cutting off all entrances into the world
of programming! The concept of regular expressions isn't exactly the
simplest one out there. Just because you understood it immediately
(which I'm guessing you did, considering your harsh response), doesn't
mean others find the concept that simple.

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


Re: regular expression

2006-12-24 Thread js
I'm a great fan of regexp because it has great power and flexibility.
if you don't like it I suggest you to read "Mastering Regular Expressions".
http://www.oreilly.com/catalog/regex3/

Yes, sometimes it might be hard to understand bites you but
if you use it correctly, it works great.

On 18 Dec 2006 20:25:32 -0800, Asper Faner
<[EMAIL PROTECTED]> wrote:
> I seem to always have hard time understaing how this regular expression
> works, especially how on earth do people bring it up as part of
> computer programming language. Natural language processing seems not
> enough to explain by the way. Why no eliminate it ?
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with small program

2006-12-24 Thread Felix Benner
smartbei schrieb:
> Hello, I am a newbie with python, though I am having a lot of fun using
> it. Here is one of the excersizes I am trying to complete:
> the program is supposed to find the coin combination so that with 10
> coins you can reach a certain amoung, taken as a parameter. Here is the
> current program:
> 
> coins = (100,10,5,1,0.5)
> anslist = []
> def bar(fin, hist = {100:0,10:0,5:0,1:0,0.5:0}):
>   s = sum(x*hist[x] for x in hist)
>   l = sum(hist.values())
>   if s < fin and l < 10:
>   for c in coins:
>   if (s+c) <= fin:
>   hist[c] += 1
>   bar(fin, hist)
>   hist[c] -= 1
>   elif l==10 and s==fin and not hist in anslist:
>   #p1
>   anslist.append(hist)
> 
> bar(50)
> print anslist
> 
> The problem is that if I run it, anslist prints as [{0.5: 0, 1: 0, 10:
> 0, 100: 0, 5: 0}], which doesnt even add up to 50. When I check how
> many times the program has reached the #p1 by sticking a print there,
> it only reaches it once, and it comes out correct. why is it that this
> result is replaced by the incorrect final one?
> 

hist is stored in anslist as a pointer only, therfore the hist[c] -= 1
operates on the same dict as is stored in the anslist. Try the following
in the python interpreter:

a = { 'key' : 1 }
l = [a]
l[0]['key'] -= 1
a

instead use:

anslist.append(dict(hist.items))

which will copy the dict.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with PIPE

2006-12-24 Thread Felix Benner
Dhika Cikul schrieb:
> Hello,
> 
> I'm new in Python, i don't know my subject is correct or wrong. I have
> problem with my script. I want to change password with passwd password
> in python without user submitted anything from keyboard. I get
> tutorial that i must use pipe to process this. And this is my code :
> 
> [code]
> 
>   1.
>   2. #!/usr/bin/python
>   3.
>   4. import os
>   5.
>   6. COMMAND = 'passwd'
>   7. PASSWD  = 'mypassword'
>   8.
>   9. # open a pipe to passwd program and
>  10. # write the data to the pipe
>  11. p = os.popen("%s" % COMMAND, 'w')
>  12. p.write(PASSWD)
>  13. p.write('\n')
>  14. p.write(PASSWD)
>  15. p.close()
>  16.
> [/code]
> 
> 
> but i got this error :
> 
> [output]
>[EMAIL PROTECTED] cp]$ ./password
>Changing password for user cp.
>Changing password for cp
>(current) UNIX password: passwd: Authentication token manipulation error
> [/output]
> 
> Anyone can help me how to write to pipe.. i try several method, and
> always fail.
> 
> Thank's

I guess the passwd program doesn't allow changing passwords from a pipe
since it is a potential security hole.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: some OT: how to solve this kind of problem in our program?

2006-12-24 Thread bearophileHUGS
Using Psyco this version is much faster, you can test it on your PC
compared to the other one (the whole running time, Psyco compilation
too):
Psyco is unable to speed up generator functions, so you have to return
true lists.
Giving the func to the permutation function, you can avoid lot of list
copying and unpacking.


try:
import psyco
psyco.full()
except ImportError:
pass

d0, d1 = 1, 2


def func(p):
a0,a1,a2,b0,b1,b2,c0,c1,c2 = p
# do application evaluation here
b1b2 = 10*b1+b2
a1a2 = 10*a1+a2
c1c2 = 10*c1+c2
if d1*a0*b1b2*c1c2 + d1*b0*a1a2*c1c2 + d1*c0*a1a2*b1b2 \
   == d0*a1a2*b1b2*c1c2:
return sorted( [[a0, a1, a2], [b0, b1, b2], [c0, c1, c2]] )
else:
return None


def accepted_permutations(alist, func):
# func must return None for the unacceptable results
# Algoritm from Phillip Paul Fuchs, modified
result = []
items = alist[:]
n = len(alist)
p = range(n+1)
i = 1
r = func(alist)
if r is not None: result.append(r)
while i < n:
p[i] -= 1
if i & 1:
j = p[i]
else:
j = 0
alist[j], alist[i] = alist[i], alist[j]
r = func(alist)
if r is not None: result.append(r)
i = 1
while p[i] == 0:
p[i] = i
i += 1
return result


def main():
  result = []
  for aresult in accepted_permutations(range(1, 10), func):
if aresult not in result:
  result.append(aresult)
  [[a0, a1, a2], [b0, b1, b2], [c0, c1, c2]] = aresult
  print '  %0d %0d %0d %0d' % (a0, b0, c0, d0)
  print '--- + --- + --- = ---'
  print ' %0d%0d%0d%0d%0d%0d
%0d'%(a1,a2,b1,b2,c1,c2,d1)
  print

main()

Bye,
bearophile

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


Re: Connection python with C

2006-12-24 Thread vasudevram

Fredrik Lundh wrote:
> Χρυσάνθη Αϊναλή wrote:
>
> > I want to connect a script in python with a source code in C. Any
> > ideas about it?
>
> http://docs.python.org/lib/module-ctypes.html
> http://docs.python.org/ext/ext.html
> http://effbot.org/pyfaq/extending-index.htm
>
> 

Just a suggestion: another way could be to use XML-RPC. It's a
lightweight distributed computing technology. Python standard library
has an XML-RPC module. I'm not sure, but I think there may be a similar
module for C. I'm almost certain there is one for C++. Try xmlrpc.com
or xml-rpc.com and also Google for appropriate patterns, e.g. "XML-RPC
library for C". Try a few variations on the pattern, that helps.

Yet another way - might be suitable only if your Python script and your
C program can both read/write standard input/output, and one is a
producer and the other is the related consumer.
In this case you can just use:

$ python my_python_script | my_C_binary
or the other way around, as per need.

HTH
Vasudev
~
Vasudev Ram
Dancing Bison Enterprises
http://www.dancingbison.com
Check out the cool Snap.com link preview feature
on my site. Free sign-up at www.snap.com
I'm not affiliated with Snap.com
~

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

Re: regular expression

2006-12-24 Thread Stef Mientki
Dustan wrote:
> Kleine Aap wrote:
>> Asper Faner wrote:
>>
>>> I seem to always have hard time understaing how this regular expression
>>> works, especially how on earth do people bring it up as part of
>>> computer programming language. Natural language processing seems not
>>> enough to explain by the way. Why no eliminate it ?
>> I.M.H.O. anyone that is not capable to grasp the concept of regular
>> expressions should not attempt to write computer programs at all! My
>> suggestion to you would be to find a job that involves working with your
>> hands...
> 
> Your humble opinion doesn't get much ruder...
> 
> Perhaps you meant "anyone that is not capable to grasp the concept of
> regular expressions after some experience with programming should not
> attempt to write computer programs at all!" Then at least newbies would
> have a leg to stand on.
> 
> Otherwise, you're practically cutting off all entrances into the world
> of programming! The concept of regular expressions isn't exactly the
> simplest one out there. Just because you understood it immediately
> (which I'm guessing you did, considering your harsh response), doesn't
> mean others find the concept that simple.
> 
I agree, and in addition:

(large) regular expressions are easy to write,
but can be almost impossible to read back !

I once had a program to generate and evaluate regular expressions,
but can't find it anymore :-(

If someone has links to regex generators/evaluators,
I'ld be much obliged.

cheers.
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Saw a possibly interesting Python PDF library - pyPDF

2006-12-24 Thread vasudevram

Saw a possibly interesting Python PDF library - pyPDF.
For merging/splitting PDFs and related operations.

It's at http://pybrary.net/pyPdf/

HTH
Vasudev
~
Vasudev Ram
Dancing Bison Enterprises
http://www.dancingbison.com
Check out the cool Snap.com link preview feature
on my site. Free sign-up at www.snap.com
I'm not affiliated with Snap.com 
~

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


file/directory format/size help

2006-12-24 Thread moishyyehuda
Hi

I am writing a script to upload images. How do I check the format of
the file? How can I tell if the file is an image, movie, or text file?
I would also like to put a limit on how much a user can upload. So how
can I check how many bits, bytes, mb, gb are in a folder.

So that sums up to

#1 What type of file is the file? Is it a movie, image, or text
document?
#2 What particular form is the file jpeg, bmp, gif etc.?
#3 The size of a directory?

Thanks

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


Re: regular expression

2006-12-24 Thread Rad [Visual C# MVP]
On Sun, 24 Dec 2006 16:36:31 +0100, Stef Mientki wrote:

> Dustan wrote:
>> Kleine Aap wrote:
>>> Asper Faner wrote:
>>>
 I seem to always have hard time understaing how this regular expression
 works, especially how on earth do people bring it up as part of
 computer programming language. Natural language processing seems not
 enough to explain by the way. Why no eliminate it ?
>>> I.M.H.O. anyone that is not capable to grasp the concept of regular
>>> expressions should not attempt to write computer programs at all! My
>>> suggestion to you would be to find a job that involves working with your
>>> hands...
>> 
>> Your humble opinion doesn't get much ruder...
>> 
>> Perhaps you meant "anyone that is not capable to grasp the concept of
>> regular expressions after some experience with programming should not
>> attempt to write computer programs at all!" Then at least newbies would
>> have a leg to stand on.
>> 
>> Otherwise, you're practically cutting off all entrances into the world
>> of programming! The concept of regular expressions isn't exactly the
>> simplest one out there. Just because you understood it immediately
>> (which I'm guessing you did, considering your harsh response), doesn't
>> mean others find the concept that simple.
>> 
> I agree, and in addition:
> 
> (large) regular expressions are easy to write,
> but can be almost impossible to read back !
> 
> I once had a program to generate and evaluate regular expressions,
> but can't find it anymore :-(
> 
> If someone has links to regex generators/evaluators,
> I'ld be much obliged.
> 
> cheers.
> Stef Mientki

A good tool to write, test and analyse regexes is the Regulator, available
here http://sourceforge.net/projects/regulator/ 

A good reference site is http://www.regular-expressions.info/, with
tutorials, examples and tools
-- 
Bits.Bytes
http://bytes.thinkersroom.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Merry Christmas and a happy new year!

2006-12-24 Thread Thomas Ploch
I wish everybody a merry Christmas and a happy new year.

Have a good and beautiful new year.

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


turbogears app deployment

2006-12-24 Thread rick
I am trying to host a TuboGears app using Apache and mod_python on a 
machine running Windows XP SP2 Professional.

Version info: apache_2.2.3-win32-x86-no_ssl.msi, python-2.4.4.msi, 
mod_python-3.2.10.win32-py2.4-apache2.2.exe, mpcp-1.5.tar.gz, 
turbogears-1.0b2-py2.4

=
1. Installed Apache.

2. Installed python, turbogears, mod_python.
   Added LoadModule python_module modules/mod_python.so
   to conf\httpd.conf. The mod_python example is working.

3. In order to host a simple TG application, I am using the bookmarker 
application which is in the TurboGears book (v1 from Chap 4).
   That works when I run it locally on my machine (also a WinXP SP2 box).
   Copied the application to "C:\Program Files\Apache Software 
Foundation\Apache2.2\htdocs"

4. Made the following changes to conf\httpd.conf
   Changed AllowOverride for .htaccess to:   AllowOverride All

5. Renamed start file to bookmarker_start.py. Created a file called 
.htaccess in bookmarker directory which has the following

SetHandler mod_python
PythonHandler mpcp
PythonDebug On
PythonOption cherrysetup bookmarker_start::mp_setup

6. Copied mpcp.py to the bookmarker directory (tried with installing it 
using  easy_install -Z mpcp, didn't help).

7. Changed bookmarker_start.py

#turbogears.start_server(Root())<--- commented this line and 
added the lines below.

def mp_setup():
pass

if __name__ == "__main__":
cherrypy.server.start()
=

I have restarted the Apache daemon multiple times. When I try to connect 
to http://machine/bookmarker, I get:

Mod_python error: "PythonHandler mpcp"

Traceback (most recent call last):

  File "C:\Python24\Lib\site-packages\mod_python\apache.py", line 299, 
in HandlerDispatch
result = object(req)
  File "C:/Program Files/Apache Software 
Foundation/Apache2.2/htdocs/bookmarker/mpcp.py", line 38, in handler
setup(req, options)
  File "C:/Program Files/Apache Software 
Foundation/Apache2.2/htdocs/bookmarker/mpcp.py", line 22, in setup
cherrypy.server.start(init_only=True, server_class=None)
  File 
"c:\python24\lib\site-packages\CherryPy-2.2.1-py2.4.egg\cherrypy\_cpserver.py", 
line 72, in start
Engine.start(self)
  File 
"c:\python24\lib\site-packages\CherryPy-2.2.1-py2.4.egg\cherrypy\_cpengine.py", 
line 91, in start
autoreload.main(self._start, freq=freq)
  File 
"c:\python24\lib\site-packages\CherryPy-2.2.1-py2.4.egg\cherrypy\lib\autoreload.py",
 
line 63, in main
sys.exit(restart_with_reloader())

SystemExit: 1

Any idea what the problem is? Thanks for your help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with small program

2006-12-24 Thread smartbei

Felix Benner wrote:
> smartbei schrieb:
> > Hello, I am a newbie with python, though I am having a lot of fun using
> > it. Here is one of the excersizes I am trying to complete:
> > the program is supposed to find the coin combination so that with 10
> > coins you can reach a certain amoung, taken as a parameter. Here is the
> > current program:
> >
> > coins = (100,10,5,1,0.5)
> > anslist = []
> > def bar(fin, hist = {100:0,10:0,5:0,1:0,0.5:0}):
> > s = sum(x*hist[x] for x in hist)
> > l = sum(hist.values())
> > if s < fin and l < 10:
> > for c in coins:
> > if (s+c) <= fin:
> > hist[c] += 1
> > bar(fin, hist)
> > hist[c] -= 1
> > elif l==10 and s==fin and not hist in anslist:
> > #p1
> > anslist.append(hist)
> >
> > bar(50)
> > print anslist
> >
> > The problem is that if I run it, anslist prints as [{0.5: 0, 1: 0, 10:
> > 0, 100: 0, 5: 0}], which doesnt even add up to 50. When I check how
> > many times the program has reached the #p1 by sticking a print there,
> > it only reaches it once, and it comes out correct. why is it that this
> > result is replaced by the incorrect final one?
> >
>
> hist is stored in anslist as a pointer only, therfore the hist[c] -= 1
> operates on the same dict as is stored in the anslist. Try the following
> in the python interpreter:
>
> a = { 'key' : 1 }
> l = [a]
> l[0]['key'] -= 1
> a
>
> instead use:
>
> anslist.append(dict(hist.items))
>
> which will copy the dict.

Thanks!
BTW - its hist.items(), after that it worked.

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


Re: problem with PIPE

2006-12-24 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Felix Benner  <[EMAIL PROTECTED]> wrote:
>Dhika Cikul schrieb:
>> Hello,
>> 
>> I'm new in Python, i don't know my subject is correct or wrong. I have
>> problem with my script. I want to change password with passwd password
>> in python without user submitted anything from keyboard. I get
.
[other issues I
don't choose to
address now]
.
.
>I guess the passwd program doesn't allow changing passwords from a pipe
>since it is a potential security hole.

This is exactly the domain Pexpect addresses http://www.unixreview.com/documents/s=9083/sam0402d/ >.
-- 
http://mail.python.org/mailman/listinfo/python-list


terminology question - "foreign function library"

2006-12-24 Thread mirandacascade
I am prompted to make these inquiries after seeing the following link
to ctypes:

http://docs.python.org/lib/module-ctypes.html

in which ctypes is described as a foreign function library.

What is the definition of "foreign function library"?
Is the concept different from a "package"?
Is the concept different from a "module"?

Thank you.

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


Re: Fall of Roman Empire

2006-12-24 Thread Dan Bishop
Dec 20, 10:36 am, Felix Benner <[EMAIL PROTECTED]> wrote:

> static int main(int argc, char **argv) {
> char *god_name;
> if (argc)
> god_name = argv[1];
> else
> god_name = "YHWH";
> metaPower God = getGodByName(god_name);
> universe *everything = makeUniverse(God);
> while (simulatePhysics(everything));
> return 0;
> }

This won't work if there are no command-line arguments.  You mean if
(argc > 1).

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


Re: consequence and life

2006-12-24 Thread marika

Lester Mosley wrote:
> I alway wondered if you are smelling a flower in a dream while on some
> crazy herbal medication. are you smelling the flower that is in the
> drug or a a flower that you once smelled when you were three years old
> on your daddy's knee ofr when you were bent over in the park looking
> for your lost keys.
>
>

that can easily be answered by viewing the movie Brainstorm.

Christopher Foof Walken was on TV today,as a matter of fact.

mk5000

"If he is, he's in the vast minority."--george w

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


Re: terminology question - "foreign function library"

2006-12-24 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|I am prompted to make these inquiries after seeing the following link
| to ctypes:
|
| http://docs.python.org/lib/module-ctypes.html
|
| in which ctypes is described as a foreign function library.
|
| What is the definition of "foreign function library"?

A library for connecting to and making use of foreign functions,
which are functions written in a foreign (to Python) language
and usually not particularly designed with Python in mind.

| Is the concept different from a "package"?
| Is the concept different from a "module"?

Ctypes is one particular module with the particular purpose given.
A module in general can be for any purpose.

Terry Jan Reedy




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


Re: Use a Thread to reload a Module?

2006-12-24 Thread Aahz
In article <[EMAIL PROTECTED]>,
=?ISO-8859-1?Q?Gregory_Pi=F1ero?= <[EMAIL PROTECTED]> wrote:
>
>That module deals with accessing data from QuickBooks, marshaling it,
>and providing methods to access the marshaled data.  Having the server
>program keep that module and all of its data in memory makes the
>server run really fast, but yeah, it does get complicated now that
>it's storing 100's of MB of data.  I guess most people go to a
>database at this point?

Very, very yes.  Try using a SQLite in-memory database, maybe?

>It's just so easy to store the data in the Python objects I already
>need them in instead of converting to tables in a DB and then
>converting back.  So maybe this threading will work for me.

You might well run into problems with the import lock.  I strongly
advise against your current approach.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"I support family values -- Addams family values" --www.nancybuttons.com
-- 
http://mail.python.org/mailman/listinfo/python-list


thread and command-line communicating

2006-12-24 Thread Siamak
Hello,
I'm a newbie to Python.
How can I have a thread (say a Tkinter window) alongside with the
command-line interpretor?
I'd like to have my thread handling events and exceptions, while I do
stuff in the command-line, possibly signaling the thread, or
terminating it, etc.
Is that possible?
Thanks,
Siamak

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


Re: terminology question - "foreign function library"

2006-12-24 Thread Gary Herron
[EMAIL PROTECTED] wrote:
> I am prompted to make these inquiries after seeing the following link
> to ctypes:
>
> http://docs.python.org/lib/module-ctypes.html
>
> in which ctypes is described as a foreign function library.
>
> What is the definition of "foreign function library"?
> Is the concept different from a "package"?
> Is the concept different from a "module"?
>   
Neither. If you have a library, completely unrelated to Python, but you 
would like to make calls into it from Python, there are several ways to 
proceed.

(A good example of such a library is the OpenGL library: 
C:/WINDOWS/SYSTEM32/opengl32.dll.)

You can craft an extension to Python, written in C perhaps and linked to 
the DLL in question, that provides functions which can be called from 
Python and which make the appropriate calls into the DLL. (Several 
products help with building of such an extension module, SWIG being the 
one I've used.)

A newer alternative to building such extensions is ctypes. If you can 
discern (from the documentation) the exact calling parameters footprint 
to a function in a DLL, then ctypes can directly call that function with 
your parameters. This is done directly in Python and ctypes without the 
need for building any extension module.

Gary Herron
> Thank you.
>
>   

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


module hierarchy snapshot

2006-12-24 Thread km

Hi,

Is there any good tool get a snapshot of module hierarchy for custom python
modules ?

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

Re: file/directory format/size help

2006-12-24 Thread Steven D'Aprano
On Sun, 24 Dec 2006 07:45:32 -0800, moishyyehuda wrote:

> Hi
> 
> I am writing a script to upload images. How do I check the format of
> the file? How can I tell if the file is an image, movie, or text file?
> I would also like to put a limit on how much a user can upload. So how
> can I check how many bits, bytes, mb, gb are in a folder.
> 
> So that sums up to
> 
> #1 What type of file is the file? Is it a movie, image, or text
> document?

In the Windows world, one simply looks at the file extension (e.g. .gif,
.avi, .txt, etc.) and hopes that it is correct.

In the Linux world, there is a command "file" that tries to guess the file
type, by looking at some combination of extension and/or signature bytes
inside the file.

Classic Macintosh OS kept file-type metadata as part of the file system; I
don't know what OS X based Macintoshes do.

Why do you care what the format of the file is? Can't you let the user
upload whatever file they like?


> #2 What particular form is the file jpeg, bmp, gif etc.?

I don't understand the question. What do you mean "form"?


> #3 The size of a directory?

Directories themselves generally are a fixed size, e.g. on my ext3 file
system my directories are typically 4K in size. But that's probably not
what you mean :-)

I assume you mean the size of all the files in a directory combined. You
have to get the size of each file, and add them all together. If you use
Google, you will find Python code to do that. Try looking on the
ActiveState Python Cookbook:

http://aspn.activestate.com/ASPN/Python/Cookbook/



-- 
Steven.

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


Re: file/directory format/size help

2006-12-24 Thread Stef Mientki

>> #1 What type of file is the file? Is it a movie, image, or text
>> document?
> 
> In the Windows world, one simply looks at the file extension (e.g. .gif,
> .avi, .txt, etc.) and hopes that it is correct.
or simply use TRID:
http://mark0.net/soft-trid-e.html

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


Re: Multi-line docstrings

2006-12-24 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Duncan Booth wrote:

> Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:
> 
>> The Python docs recommend the use of triple-quoted string literals for
>> docstrings, e.g.
>> 
>> def Meet(Alice, Bob) :
>> """arranges a meeting between Alice and Bob.
>> Returns a reference to the meeting booking object."""
>> ...
>> #end Meet
>> However, these tend to get messed up by indentation whitespace, which
>> gets spuriously included as part of the string.
> 
> Not spuriously included: included by design, but sometimes annoying.

The problem is that the treatment of indentation whitespace in triple-quoted
strings is at odds with its use for syntax purposes elsewhere in the
language.

Instead of preserving all included whitespace, a better rule for
triple-quoted strings might be to strip whitespace up to the current
indentation level from each continuation line. That is, each line _must_
begin with at least that amount of whitespace, otherwise it's an error; any
extra whitespace is preserved. E.g.

a = """two lines
  of text"""

being equivalent to

a = "two lines\n  of text"

Or, a simpler rule might be to strip _all_ whitespace at the start of each
continuation line, regardless of indentation level. So the triple-quoted
example above becomes equivalent to

a = "two lines\nof text"

If you _want_ to include some whitespace at the start of a continuation
line, simply precede it by something that isn't literal whitespace:

a = """two lines
 \x20 of text"""

becomes equivalent to

a = "two lines\n  of text"

(It might be nice if "\ " was recognized as equivalent to "\x20" for this
purpose.)
-- 
http://mail.python.org/mailman/listinfo/python-list


method names in __slots__ ??

2006-12-24 Thread John Machin
I have stumbled across some class definitions which include all/most
method names in a __slots__ "declaration". A cut-down and disguised
example appears at the end of this posting.

Never mind the __private_variables and the getter/setter approach, look
at the list of methods in the __slots__.

I note that all methods in an instance of a slotted class are read-only
irrespective of whether their names are included in __slots__ or not:
Given a = Adder(),
a.tally = 0
gets AttributeError: 'Adder' object attribute 'tally' is read-only
a.notinslots = 1
gets AttributeError: 'Adder' object attribute 'notinslots' is read-only

So is there some magic class-fu going down here, or is this just a
waste of memory space in the instances?

=== example ===
# class with method names in __slots__

class Adder(object):

__slots__ = [
# methods
'__init_',
'get_foo',
'get_value',
'set_foo',
'tally',
# private variables
'__foo',
'__value',
# public variables
'bar',
'zot',
]

def __init__(self, start=0):
self.__value = start
self.__foo = 666
self.bar = None
self.zot = 42

def tally(self, amount):
self.__value += amount

def get_value(self):
return self.__value

def set_foo(self, arg):
self.__foo = arg

def get_foo(self):
return self.__foo

def notinslots(self):
pass
=== end of example ===

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


Why does Python never add itself to the Windows path?

2006-12-24 Thread Ben Sizer
I've installed several different versions of Python across several
different versions of MS Windows, and not a single time was the Python
directory or the Scripts subdirectory added to the PATH environment
variable. Every time, I've had to go through and add this by hand, to
have something resembling a usable Python installation. No such
problems on Linux, whether it be Mandrake/Mandriva, Fedora Core, or
Kubuntu. So why is the Windows install half-crippled by default? I just
rediscovered this today when trying to run one of the Turbogears
scripts, but this has puzzled me for years now.

-- 
Ben Sizer

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


Re: Why does Python never add itself to the Windows path?

2006-12-24 Thread vbgunz

Ben Sizer wrote:
> I've installed several different versions of Python across several
> different versions of MS Windows, and not a single time was the Python
> directory or the Scripts subdirectory added to the PATH environment
> variable. Every time, I've had to go through and add this by hand, to
> have something resembling a usable Python installation. No such
> problems on Linux, whether it be Mandrake/Mandriva, Fedora Core, or
> Kubuntu. So why is the Windows install half-crippled by default? I just
> rediscovered this today when trying to run one of the Turbogears
> scripts, but this has puzzled me for years now.
> 
> -- 
> Ben Sizer

excellent question

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


Unescaping URLs in Python

2006-12-24 Thread John Nagle
Here's a URL from a link on the home page of a major company.

About Us

Yes, that "&" is in the source text of the page.

This is, in fact, correct HTML. See

http://www.htmlhelp.com/tools/validator/problems.html#amp

 What's the appropriate Python function to call to unescape a URL which 
might
contain things like that?  Will this interfere with the usual "%" type escapes
in URLs?

 What's actually needed to get this right is something that goes from
HTML escaped form to URL escaped form, because, in general, there is no
unescaped form that will work for all URLs.

There's "htmldecode" at "http://zesty.ca/python/scrape.py";, which works,
but this should be a standard library function.

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


Re: Why does Python never add itself to the Windows path?

2006-12-24 Thread [EMAIL PROTECTED]
I don't seem to have any problem running python programs regardless of
where they are.  My platform is windows xp and I have run both 2.4 and
2.5 more details about what version of windows you are running might be
helpfull

https://sourceforge.net/project/showfiles.php?group_id=156455&package_id=174569

vbgunz wrote:
> Ben Sizer wrote:
> > I've installed several different versions of Python across several
> > different versions of MS Windows, and not a single time was the Python
> > directory or the Scripts subdirectory added to the PATH environment
> > variable. Every time, I've had to go through and add this by hand, to
> > have something resembling a usable Python installation. No such
> > problems on Linux, whether it be Mandrake/Mandriva, Fedora Core, or
> > Kubuntu. So why is the Windows install half-crippled by default? I just
> > rediscovered this today when trying to run one of the Turbogears
> > scripts, but this has puzzled me for years now.
> > 
> > -- 
> > Ben Sizer
> 
> excellent question

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


Re: Help with small program

2006-12-24 Thread Paul Watson
smartbei wrote:
> Felix Benner wrote:
>> smartbei schrieb:
>>> Hello, I am a newbie with python, though I am having a lot of fun using
>>> it. Here is one of the excersizes I am trying to complete:
>>> the program is supposed to find the coin combination so that with 10
>>> coins you can reach a certain amoung, taken as a parameter. Here is the
>>> current program:
>>>
>>> coins = (100,10,5,1,0.5)
>>> anslist = []
>>> def bar(fin, hist = {100:0,10:0,5:0,1:0,0.5:0}):
>>> s = sum(x*hist[x] for x in hist)
>>> l = sum(hist.values())
>>> if s < fin and l < 10:
>>> for c in coins:
>>> if (s+c) <= fin:
>>> hist[c] += 1
>>> bar(fin, hist)
>>> hist[c] -= 1
>>> elif l==10 and s==fin and not hist in anslist:
>>> #p1
>>> anslist.append(hist)
>>>
>>> bar(50)
>>> print anslist
>>>
>>> The problem is that if I run it, anslist prints as [{0.5: 0, 1: 0, 10:
>>> 0, 100: 0, 5: 0}], which doesnt even add up to 50. When I check how
>>> many times the program has reached the #p1 by sticking a print there,
>>> it only reaches it once, and it comes out correct. why is it that this
>>> result is replaced by the incorrect final one?
>>>
>> hist is stored in anslist as a pointer only, therfore the hist[c] -= 1
>> operates on the same dict as is stored in the anslist. Try the following
>> in the python interpreter:
>>
>> a = { 'key' : 1 }
>> l = [a]
>> l[0]['key'] -= 1
>> a
>>
>> instead use:
>>
>> anslist.append(dict(hist.items))
>>
>> which will copy the dict.
> 
> Thanks!
> BTW - its hist.items(), after that it worked.

An alternative.

cointypes = (100, 10, 5, 1, 0.5)
needed = {}

def coins(fin):
cur = fin
for c in cointypes:
v = int(cur / c)
if v > 0:
needed[c] = v
cur -= v * c

if __name__ == '__main__':
coins(51)
print needed
coins(127)
print needed
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with small program

2006-12-24 Thread Paul Watson
Better alternative.

cointype = (100, 10, 5, 1, 0.5)

def coins(fin):
needed = {}
for c in cointypes:
v, r = divmod(fin, c)
if v > 0:
needed[c] = v
fin = r
return needed

if __name__ == '__main__':
print coins(51)
print coins(127)
print coins[12.5)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unescaping URLs in Python

2006-12-24 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, John Nagle
wrote:

> Here's a URL from a link on the home page of a major company.
> 
> About Us
> 
> What's the appropriate Python function to call to unescape a URL
> which might contain things like that?

Just use any HTML-parsing library. I think the standard Python HTMLParser
will do the trick, provided there aren't any errors in the HTML.

> Will this interfere with the usual "%" type escapes in URLs?

No. Just think of it as an HTML attribute value; the fact that it's a URL is
a question of later interpretation, nothing to do with the fact that it
comes from an HTML attribute.

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


Re: Why does Python never add itself to the Windows path?

2006-12-24 Thread MC
Hi!

+1

-- 
@-salutations

Michel Claveau


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


How to stop program when threads is sleeping

2006-12-24 Thread many_years_after
Hi, pythoners:

  There is a problem I couldn't dispose. I start a thread in the my
program. The thread will do something before executing time.sleep().
When the user give a signal to the main thread (such as click the 'end'
button or close the window), the thread should end it's running. But
how to end the threading when it's sleeping? I set an flag to the
thread, but it doesn't work.

  I also thought to put  'time.sleep()'   to the main thread. But I
think the main thread will not response to user's action because it is
executing sleep(). 

 Any ideas?
 Thanks.

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


Website Capture

2006-12-24 Thread yoring
Hi,

I want to capture a web site into gif image using Python.
I installed the PIL if it can help.

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


Re: textwrap.dedent replaces tabs?

2006-12-24 Thread Frederic Rentsch
Tom Plunket wrote:
> Frederic Rentsch wrote:
>
>   
>> Following a call to dedent () it shouldn't be hard to translate leading 
>> groups of so many spaces back to tabs.
>> 
>
> Sure, but the point is more that I don't think it's valid to change to
> tabs in the first place.
>
> E.g.:
>
>  input = ' ' + '\t' + 'hello\n' +
>  '\t' + 'world'
>
>  output = textwrap.dedent(input)
>
> will yield all of the leading whitespace stripped, which IMHO is a
> violation of its stated function.  In this case, nothing should be
> stripped, because the leading whitespace in these two lines does not
> /actually/ match.  Sure, it visually matches, but that's not the point
> (although I can understand that that's a point of contention in the
> interpreter anyway, I would have no problem with it not accepting "1 tab
> = 8 spaces" for indentation...  But that's another holy war.
>
>   
>> If I understand your problem, you want to restore the dedented line to 
>> its original composition if spaces and tabs are mixed and this doesn't 
>> work because the information doesn't survive dedent ().
>> 
>
> Sure, although would there be a case to be made to simply not strip the
> tabs in the first place?
>
> Like this, keeping current functionality and everything...  (although I
> would think if someone wanted tabs expanded, they'd call expandtabs on
> the input before calling the function!):
>
> def dedent(text, expand_tabs=True):
> """dedent(text : string, expand_tabs : bool) -> string
>
> Remove any whitespace than can be uniformly removed from the left
> of every line in `text`, optionally expanding tabs before altering
> the text.
>
> This can be used e.g. to make triple-quoted strings line up with
> the left edge of screen/whatever, while still presenting it in the
> source code in indented form.
>
> For example:
>
> def test():
> # end first line with \ to avoid the empty line!
> s = '''\
>  hello
> \t  world
> '''
> print repr(s) # prints ' hello\n\t  world\n'
> print repr(dedent(s))  # prints ' hello\n\t  world\n'
> """
> if expand_tabs:
> text = text.expandtabs()
> lines = text.split('\n')
> 
> margin = None
> for line in lines:
> if margin is None:
> content = line.lstrip()
> if not content:
> continue
> indent = len(line) - len(content)
> margin = line[:indent]
> elif not line.startswith(margin):
> if len(line) < len(margin):
> content = line.lstrip()
> if not content:
> continue
> while not line.startswith(margin):
> margin = margin[:-1]
>
> if margin is not None and len(margin) > 0:
> margin = len(margin)
> for i in range(len(lines)):
> lines[i] = lines[i][margin:]
>
> return '\n'.join(lines)
>
> import unittest
>
> class DedentTest(unittest.TestCase):
> def testBasicWithSpaces(self):
> input = "\n   Hello\n  World"
> expected = "\nHello\n   World"
> self.failUnlessEqual(expected, dedent(input))
>
> def testBasicWithTabLeadersSpacesInside(self):
> input = "\n\tHello\n\t   World"
> expected = "\nHello\n   World"
> self.failUnlessEqual(expected, dedent(input, False))
> 
> def testAllTabs(self):
> input = "\t\tHello\n\tWorld"
> expected = "\tHello\nWorld"
> self.failUnlessEqual(expected, dedent(input, False))
> 
> def testFirstLineNotIndented(self):
> input = "Hello\n\tWorld"
> expected = input
> self.failUnlessEqual(expected, dedent(input, False))
> 
> def testMixedTabsAndSpaces(self):
> input = "  \t Hello\n   \tWorld"
> expected = "\t Hello\n \tWorld"
> self.failUnlessEqual(expected, dedent(input, False))
> 
> if __name__ == '__main__':
> unittest.main()
> -tom!
>
>   
It this works, good for you. I can't say I understand your objective. 
(You dedent common leading tabs, except if preceded by common leading 
spaces (?)). Neither do I understand the existence of indentations made 
up of tabs mixed with spaces, but that is another topic.
 I have been wasting a lot of time with things of this nature coding 
away before forming a clear conception in my mind of what my code was 
supposed to accomplish. Sounds stupid. But many problems seem trivial 
enough at first sight to create the illusion of perfect understanding. 
The encounter with the devil in the details can be put off but not 
avoided. Best to get it over with from the start and write an exhaustive 
formal description of the problem. Follows an exhaustive formal 
description of the rules for its solution. The rules can then be morphed 
into code in a straightforward manner. In other words, coding sh

Re: Website Capture

2006-12-24 Thread Jonathan Curran
On Monday 25 December 2006 00:57, [EMAIL PROTECTED] wrote:
> Hi,
>
> I want to capture a web site into gif image using Python.
> I installed the PIL if it can help.

It can't be done with just Python & PIL, that much is for sure. First of all 
you need some sort of module/program/(whatever you want to call it) that can 
render a given webpage. Then you would proceed to capturing the graphical 
output of that module/program/...

Maybe what you should look into are graphical toolkits that possibly provide a 
HTML widget from which you can get a graphical display. WxWidgets/WxPython is 
one option, and the only other I can think of is GTK/pyGTK.

I hope this helps a little, and Merry Christmas!

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