Error handling. Python embedded into a C++ app.

2006-11-28 Thread Wolfram
I have a problem with displaying errors in an embedded situation.

The "main program" I want to embed Python into is a windows, MFC,
non-console, C++ application. My issue is that I have not been able to
"catch" error messages from python, for example syntax errors. 

PyRun_SimpleFile() crashed, probably due to incompatible FILE
structures. So I am using PyRun_SimpleString to call the python
"execute" command to execute a *.py file. As a test for stdout I can
do a "print" in the *.py and I test stderr using an on-purpose name
error.


Here is what I tried:

- Use AllocConsole and 
freopen("CON", "w", stdout);
  freopen("CON", "w", stderr);
to redirect stderr and stdout to a new console window.
The C++ stderr/stdout is successfully redirected before I start python
with  Py_Initialize(), but Python does not output into it at all. In
case it is a "not flushed yet" issue, I even added a Py_Finalize()
afetr executing the *.py file.
- I used a TKInter based solution found on the net
- I reopened stderr and stdout in C++ to a file. It always stays at 0
bytes.
- I tried to reset stderr in the python code (sorry, forgot details).

What is the best way to access Python error messages?
I prefer a C++ to a python way as I currently can debug C++ but not
python.
Is there one way I can use to "catch" exceptions, "runtime errors" and
"syntax errors" in case there is a difference between them? Sorry for
the newbie questions but neither a look into my Python-book nor onto
google helped.

Bye bye,
Wolfram Kuss.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Error handling. Python embedded into a C++ app.

2006-11-29 Thread Wolfram
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

>You would use try: and then on the next line except:  

Thanks for the idea, but it did not help. I can not wrap every pythion
line in python, so I wrote the following code on the C++ side:

-- snip -
  try
  {
  int ret = PyRun_SimpleString ( p ) ;
  if(ret==-1)
  {
  ::MessageBox(0, "Error in Python call!", "", 0);
  }
  else
  {
assert(ret == 0);
  }
  }
  catch( ...) {
  ::MessageBox(0, "exception", "", 0 );
  }
-- snip -


I call this where "p" is an "execute" of a *.py file containing an
error. I get the "Error in Python call!", but not the "exception".
Any help, including links to information, welcome.


TIA, Wolfram Kuss.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Error handling. Python embedded into a C++ app.

2006-12-02 Thread Wolfram
Maybe of interest to people loking for a solution:

I solved my issue by changing the program retroactively from a pure
MFC app to a console one using this procedure:
http://homepage3.nifty.com/ysflight/mfcconsole/mfcconsole.html

I am still not sure why all of my other attempts failed, but most
somehow changed stderr after the program started and before the python
initialisation call. Maybe by binding in the python libraries some
initialisation is done automatically before the first "user" C++ line
is called and so any change done by the C++ code ignored? 

Oh well, it works now, even if with a kludge (I always need to have a
console, even if I do not use Python).

Bye bye, Wolfram Kuss.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: copy on write

2012-02-06 Thread Wolfram Hinderer
On 3 Feb., 11:47, John O'Hagan  wrote:

> But isn't it equally true if we say that z = t[1], then t[1] += x is 
> syntactic sugar for z = z.__iadd__(x)? Why should that fail, if z can handle 
> it?

It's more like syntactic sugar for
y = t; z = y.__getitem__(1); z.__iadd__(x); y.__setitem__(1, z)

It's clear that only the last expression fails, after the mutation has
taken place.

Just in case you wonder about the y: you need it for more complicated
cases.
t[1][1] += [4] is syntactic sugar for
y = t.__getitem__(1); z = y.__getitem__(1); z.__iadd__([4]);
y.__setitem__(1, z)

That makes clear why there's no exception in this code:
>>> t = (0, [1, [2, 3]])
>>> t[1][1] += [4]
>>> t
(0, [1, [2, 3, 4]])

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


Re: Faster Recursive Fibonacci Numbers

2011-05-17 Thread Wolfram Hinderer
On 17 Mai, 20:56, geremy condra  wrote:
> On Tue, May 17, 2011 at 10:19 AM, Jussi Piitulainen
>
>  wrote:
> > geremy condra writes:
>
> >> or O(1):
>
> >> ö = (1 + sqrt(5)) / 2
> >> def fib(n):
> >>     numerator = (ö**n) - (1 - ö)**n
> >>     denominator = sqrt(5)
> >>     return round(numerator/denominator)
>
> >> Testing indicates that it's faster somewhere around 7 or so.
>
> > And increasingly inaccurate from 71 on.
>
> Yup. That's floating point for you. For larger values you could just
> add a linear search at the bottom using the 5f**2 +/- 4 rule, which
> would still be quite fast out to about 10 times that. The decimal
> module gets you a tiny bit further, and after that it's time to just
> use Dijkstra's, like rusi suggested. In any event, I still think this
> formulation is the most fun ;).

I think you can write it even more funny

def fib(n):
return round(((.5 + .5 * 5 ** .5) ** n -  (.5 - .5 * 5 ** .5) **
n) * 5 ** -.5)

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


Re: N-grams

2016-11-09 Thread Wolfram Hinderer

Am 10.11.2016 um 03:06 schrieb Paul Rubin:

This can probably be cleaned up some:

 from itertools import islice
 from collections import deque

 def ngram(n, seq):
 it = iter(seq)
 d = deque(islice(it, n))
 if len(d) != n:
 return
 for s in it:
 yield tuple(d)
 d.popleft()
 d.append(s)
 if len(d) == n:
 yield tuple(d)

 def test():
 xs = range(20)
 for a in ngram(5, xs):
 print a

 test()
That's along the lines of what I thought. Steven's version has two areas 
that might be possible to be improved:


1. The startup looks slightly ugly to me.
2. If n is large, tee has to maintain a lot of unnecessary state.

collections.deque manages all the state we need. Here are Steve's 
version (ngram) and mine (ngram_2):


from itertools import tee, islice
from collections import deque

def ngrams(iterable, n=2):
if n < 1:
raise ValueError
t = tee(iterable, n)
for i, x in enumerate(t):
for j in range(i):
next(x, None)
return zip(*t)

def ngrams_2(iterable, n=2):
if n < 1:
raise ValueError
it = iter(iterable)
d = deque(islice(it, n-1), maxlen=n)
for elem in it:
d.append(elem)
yield tuple(d)

print(list(ngrams(range(1000), 4)) == list(ngrams_2("abcdefg", 4)))


One problem my version has, is that it does the iteration over the 
iterable itself, so that's probably more python code (instead of C code 
in Steven's version). For large n the reduced number of iterators does 
pay off, though:


%timeit list(ngrams(range(1000), n=500))
10 loops, best of 3: 26.5 ms per loop

%timeit list(ngrams_2(range(1000), n=500))
100 loops, best of 3: 4.07 ms per loop

For small n, it's slower, as expected:

%timeit list(ngrams(range(1000), n=3))
1 loops, best of 3: 120 µs per loop

%timeit list(ngrams_2(range(1000), n=3))
1000 loops, best of 3: 603 µs per loop


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


Re: How to use a timer in Python?

2005-09-22 Thread Wolfram Kraus
Nico Grubert wrote:
> Hi there,
> 
> on a Linux machine running Python 2.3.5. I want to create a file 
> 'newfile' in a directory '/tmp' only if there is no file 'transfer.lock' 
> in '/temp'.
> A cronjob creates a file 'transfer.lock' in '/temp' directory every 15 
> minutes while the cronjob is doing something. This job takes around 30 
> seconds. During these 30 seconds the 'transfer.lock' file is present in 
> the '/temp' directory and I must not create 'newfile'. After the cronjob 
> has been finished, the 'transfer.lock' file is deleted from '/temp' and 
> I can create 'newfile'.
> How can I use a timer that waits e.g. 10 seconds if 'transfer.lock' is 
> present and then checks again if 'transfer.lock' is still there?
> 
> I want to do something like this:
> 
> import os
> if 'transfer.lock' in os.listdir('/temp'):
>   # ...wait 10 seconds and then check again if
>   # 'transfer.lock' is in os.listdir('/temp')
> else:
>   # create 'newfile'
> 
> 
> Nico

import time
time.sleep(10)

For more information: help(time.sleep) ;-)

HTH,
Wolfram
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to creat a file?

2005-12-02 Thread Wolfram Kraus
sandorf wrote:
> I'm new to python. Have a simple question.
> 
> "open" function can only open an existing file and raise a IOerror when
> the given file does not exist. How can I creat a new file then?
> 
open the new file in write mode: open('foo', 'w')
See: help(open)

HTH,
Wolfram
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SuSE 9.1: updating to python-2.4

2005-01-10 Thread Wolfram Kraus
Heyho!
Torsten Mohr wrote:
Hi,
along with my distribution SuSE 9.1 came python 2.3.3.
I'd like to update to 2.4 now, is this an easy thing to do or will
lots of installed modules refuse to work then?
I installed Python 2.4 under SuSE 9.1 and had no problems so far. If you
install it via "./configure;make;make install", python 2.4 will be
installed in /usr/local/lib/python2.4 parallel to your existing 2.3
installation under /usr/lib/python2.3.
Is there an easy way to find out what i need to update?
Just check out, which version comes up when you call "python" from the 
shell. If this is version 2.3 you can start 2.4 with "python2.4"
All the installed packages for python2.3 (e.g. PIL, MySQLdb, wxPython,
...) need to be installed for the new version, too.
Thanks for any hints, Torsten.
HTH,
Wolfram
--
http://mail.python.org/mailman/listinfo/python-list


Associate objects with Tix.Tree

2005-01-15 Thread Wolfram Kraus
Heyho!
I want to associate objects with the nodes of a Tix.Tree. Is this 
possible, because the following example won't work:

--8<-- Cut here -
import Tix
class C:
pass
root = Tix.Tk()
top = Tix.Frame(root, relief=Tix.RAISED, bd=1)
tixtree = Tix.Tree(top)
tixtree.pack(expand=1, fill=Tix.BOTH, padx=10, pady=10, side=Tix.LEFT)
c=C()
print c
tixtree.hlist.add(c,
  itemtype=Tix.IMAGETEXT,
  text='foo',
  image=tixtree.tk.call('tix', 'getimage', 'folder'))
tixtree.setmode(c, 'open')
root.mainloop()
--8<-- Cut here -----
Can this somehow be done?
TIA,
Wolfram
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to pass attribute name via sys.argv

2005-01-27 Thread Wolfram Kraus
Felix Hebeler wrote:
Hi all, I am doing some Python scripting for a while, but I'm not too
deep into it yet. So I have a problem I can't solve.
I need to call an object attribute:
value = object.attrName[0]
the problem is, that the attribute name can only be specified at
runtime.
So what I have is something like
attrName = sys.argv[1] attrName
'cellsize'
and I need to pass it on so I can call
value = object.cellsize[0]
Use getattr:
value = getattr(object, attrName)[0]
Can this be done using Python?
Thanks for any hints
Cheers Felix
HTH,
Wolfram
--
http://mail.python.org/mailman/listinfo/python-list


Re: python-2.4.msi installation issue

2005-02-03 Thread Wolfram Kraus
[EMAIL PROTECTED] wrote:
O/S: Windows XP Home (with Service Pack 2)
Downloaded python-2.4.msi from python.org (10,632KB).  When I double
click on the file from Windows Explorer, the installation process
presents the window in which I am prompted to either install for all
users (the default) or install for just me.  I selected the defaulted
value.  Installation process presents a window in which the user may
select the directory for python 2.4 files.  I selected the default
value of the Python24 folder.  After clicking Next, the process
presents a window with the message, "Python 2.4 installer ended
prematurely.  Python 2.4 ended prematurely because of an error.  Your
system has not been modified.  To install this program at a later time,
please run the installation again."
My question is this: how do I determine what the error was that caused
the installation process to end prematurely?
I have the same problem and don't know what's happening, but 
ActivePython worked for me. Get it here:
http://activestate.com/Products/ActivePython/

HTH,
Wolfram
--
http://mail.python.org/mailman/listinfo/python-list


Re: catch argc-argv

2005-06-19 Thread Wolfram Kraus
mg wrote:
> Hello,
> 
> I am writting bindings for a FEM application. In  one of my function 
> 'initModulename', called when the module is imported, I would like to 
> get the argc and argv arguments used in the main function of Python.
> So, my question is: does the Python API containe fonctions like 
> 'get_argc()' and 'get_argv()' ?
> 
> Thanks,
> 
> 
> 
Use sys.argv:
http://python.org/doc/2.4.1/lib/module-sys.html

HTH,
Wolfram
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: need help with MySQLdb

2005-06-29 Thread Wolfram Kraus
[EMAIL PROTECTED] wrote:
> Hey there all,
> i have a question about how to point my python install to my sql
> database.
> 
> when i enter this: db = MySQLdb.connect(user="user", passwd="pass",
> db="myDB")
> 
> i get this:
> Traceback (most recent call last):
>   File "", line 1, in -toplevel-
> db = MySQLdb.connect(user="user", passwd="pass", db="MyDB")
>   File "/usr/lib/python2.4/site-packages/MySQLdb/__init__.py", line 66,
> in Connect
> return Connection(*args, **kwargs)
>   File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line
> 134, in __init__
> super(Connection, self).__init__(*args, **kwargs2)
> OperationalError: (1049, "Unknown database 'MyDB'")
> 
> i am using the all in one package from lampp (now xampp) and i have
> tested a couple of python scripts from the cgi, but nothing that
> connects to the database.
> 
> any ideas?
> 
> thanks
> 
Try the following from the shell (NOT the python shell):
mysql -u user -p
[Enter passwd]
mysql> show databases;

If MyDB isn't in the list either something went wrong with the xampp 
installation or the database for xampp got a different name. (I am no 
xampp expert, so I can't help you any further)

HTH,
Wolfram
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: need help with MySQLdb

2005-06-30 Thread Wolfram Kraus
nephish wrote:
[...]

>> Try the following from the shell (NOT the python shell):
>> mysql -u user -p
>> [Enter passwd]
>> mysql> show databases;
>>
>> If MyDB isn't in the list either something went wrong with the xampp 
>> installation or the database for xampp got a different name. (I am no 
>> xampp expert, so I can't help you any further)
>>
>> HTH,
>> Wolfram
>>
>>
> after i entered the password it told me it cannot connect to mysql through
> socket /tmp/mysql.sock
> 
> hmmmm.
> hope this helps

Please keep the discussion on the list

Try
mysql -u user -p -h 127.0.0.1

HTH,
Wolfram
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing last comma in 'C1, C2, C3' with 'and' so that it reads 'C1, C2 and C3'

2005-07-11 Thread Wolfram Kraus
Ric Da Force wrote:
> Hi,
> 
> I have a string such as 'C1, C2, C3'.   Without assuming that each bit of 
> text is of fixed size, what is the easiest way to change this list so that 
> it reads:
> 'C1, C2 and C3' regardless of the length of the string.
> 
> Regards and sorry for the newbie question,
> 
> Ric 
> 
> 
Use rfind and slicing:

 >>> x = "C1, C2, C3"
 >>> x[:x.rfind(',')]+' and'+x[x.rfind(',')+1:]
'C1, C2 and C3'

HTH,
Wolfram
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Retrieving and saving images from internet address

2005-07-25 Thread Wolfram Kraus
rock69 wrote:
> Hi all :)
> 
> I got this address:
> 
> http://www.infomedia.it/immagini/riviste/covers/cp/cp137.jpg
> 
> and I would like to download that image and save it to a local file.
> How do you do that in Python?
> 
Use urllib2:

http://docs.python.org/lib/module-urllib2.html
http://docs.python.org/lib/urllib2-examples.html

HTH,
Wolfram
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: display VARCHAR(mysql) and special chars in html

2005-02-23 Thread Wolfram Kraus
Jonas Meurer wrote:
hello,
my script selects a comment saved as VARCHAR in MySQL and displays it
inside an html page.
the problem is, that the comment contains several special characters, as
mysterious utf-8 hyphens, german umlauts, etc.
i could write a function to parse the comment and substitute special
chars with the relevant html code, but maybe this already exists in some
module?
if not, it'll be hard work, as i've to consider many special chars, and
at least iso-8859-1* and utf-8 as charmaps.
bye
 jonas
If I understand you correctly, just put

somewhere in the -section of you HTML-Page.
HTH,
Wolfram
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing to stdout and a log file

2005-04-20 Thread Wolfram Kraus
Mike wrote:
I would like my 'print' statements to send its output to the user's
screen and a log file.
This is my initial attempt:
class StdoutLog(file):
def __init__(self, stdout, name='/tmp/stdout.log',
mode='w',bufsize=-1):
super(StdoutLog, self).__init__(name,mode,bufsize)
self.stdout = stdout
def write(self, data):
self.stdout.write(data)
What happens when you do a self.stdout.flush() here?
self.write(data)
import sys
sys.stdout = StdoutLog(sys.stdout)
print 'STDOUT', sys.stdout
When the program is run the string is written to the log file but
nothing appears on my screen. Where's the screen output?
It looks like the superclass's write() method is getting called instead
of the StdoutLog instance's write() method.
The python documentation says 'print' should write to
sys.stdout.write() but that doesn't seem to be happening.
Any idea what's going one? 
Or ideas on how to debug this?

Thanks, Mike
I had the same problem (writing to file and stdout with print) and my 
solution was *not* to subclass file and instead add a 
self.outfile=file(...) to the constructor.

HTH,
Wolfram
--
http://mail.python.org/mailman/listinfo/python-list


Re: find all multiplicands and multipliers for a number

2015-04-11 Thread wolfram . hinderer
Am Samstag, 11. April 2015 09:14:50 UTC+2 schrieb Marko Rauhamaa:
> Paul Rubin :
> 
> > This takes about 4 seconds on a Intel(R) Core(TM) i5-3230M CPU @ 2.60GHz
> > laptop (64 bit linux):
> 
> Converted to Python3:
> 
> #!/usr/bin/env python3
> 
> import itertools, time
> 
> def candidates():
> yield 2
> yield 3
> for i in itertools.count(5,6):
> yield i
> yield i+2
> 
> def fac(n):
> for c in candidates():
> if c*c > n:
> yield n
> break
> while n%c == 0:
> yield c
> n //= c
> 
> t0 = time.time()
> print(list(fac(2**111+1)))
> print(time.time() - t0)
> 
> 
> This is slightly faster:
> 
> 
> #!/usr/bin/env python3
> 
> import time
> 
> def fac(n):
> for c in range(n):
> if c*c > n:
> yield n
> break
> while n%c == 0:
> yield c
> n //= c
> 
> t0 = time.time()
> print(list(fac(2**111+1)))
> print(time.time() - t0)
> 
> 

I get other results on 3.2.3:

n % 0 raises ZeroDivisionError.
After fixing that by using range(2, n) it takes about three times as long as 
the original version, which is what I'd expect.
-- 
https://mail.python.org/mailman/listinfo/python-list


ipython -wthread vs. ipython -pylab

2011-09-12 Thread Wolfram Brenig

Hi,

I have a problem with the ipython shell: frequently, within one session 
I would like to do 2D plotting, using  matplotlib, as well as 3D 
visualization using mayavi


The man page for ipython, matplotlib, and mayavi tell me, that I must 
invoke ipython with

ipython -wthread for mayavi and
ipython -pylab for matplotlib
in order to avoid blocking (which indeed happens if I don't
use those options).
However, ipython's manpage also states, that only one of -wthread or 
-pylab can be given?


Does that imply I have to get out of the shell each time I want to 
switch from matplotlib to mayavi usage? Most likely no. But what should 
I do?


Thanks for your help

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


Re: Sorted list - how to change it

2006-11-09 Thread Wolfram Kraus
On 09.11.2006 10:52, Lad wrote:
> I have a sorted list for example [1,2,3,4,5] and I would like to change
> it in a random way
> e.g [2,5,3,1,4] or [3,4,1,5,2]  or in any other way except being
> ordered.
> What is the best/easiest
>  way how to do it?
> 
> Thank you for help
> L.
> 
use random.shuffel:

>>> import random
>>> x = [1,2,3,4,5]
>>> random.shuffle(x)
>>> x
[1, 4, 2, 3, 5]
>>> random.shuffle(x)
>>> x
[4, 2, 1, 3, 5]

see: http://docs.python.org/lib/module-random.html

HTH,
Wolfram
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to measure execution time of a program

2006-06-28 Thread Wolfram Kraus
On 28.06.2006 10:01, Girish Sahani wrote:
> Sorry for spamming again, but please also enlighten me with some way to
> time a function i.e. to find out how much time each function takes for
> execution in a big program.
>> Hi all,
>>
>>   Can anyone tell me the simplest way to do it (some code snippet that
>> could be included in the program's main function) ??
>>
>> Thanks,
>> girish
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
> 

Use the Python profiler:

http://docs.python.org/lib/profile.html

HTH,
Wolfram
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looping question 4 NEWB

2006-07-06 Thread Wolfram Kraus
On 06.07.2006 12:43, manstey wrote:
> Hi,
> 
> I often have code like this:
> 
> data='asdfbasdf'
> find = (('a','f')('s','g'),('x','y'))
> for i in find:
>if i[0] in data:
>data = data.replace(i[0],i[1])
> 
> is there a faster way of implementing this? Also, does the if clause
> increase the speed?
> 
> Thanks,
> Matthew
> 

>>> import string
>>> data='asdfbasdf'
>>> data.translate(string.maketrans('asx', 'fgy'))
'fgdfbfgdf'

HTH,
Wolfram
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-08 Thread Wolfram Fenske
David Lees <[EMAIL PROTECTED]> writes:

> [EMAIL PROTECTED] wrote:
>> Okay, since everyone ignored the FAQ, I guess I can too...
>> Mark Tarver wrote:
>>> How do you compare Python to Lisp?  What specific advantages do you
>>> think that one has over the other?
>> (Common) Lisp is the only industrial strength language with both pure
>> compositionality and a real compiler. What Python has is stupid slogans
>> ("It fits your brain." "Only one way to do things.") and an infinite
>> community of flies that, for some inexplicable reason, believe these
>> stupid slogns. These flies are, however, quite useful because they
>> produce infinite numbers of random libraries, some of which end up
>> being useful. But consider: Tcl replaced Csh, Perl replaced Tcl, Python
>> is rapidly replacing Perl, and Ruby is simultaneously and even more
>> rapidly replacing Python. Each is closer to Lisp than the last; the
>> world is returning to Lisp and is dragging the flies with it.
>> Eventually the flies will descend upon Lisp itself and will bring with
>> them their infinite number of random libraries, and then things will be
>> where they should have been 20 years ago, but got sidetracked by Tcl
>> and other line noise.
>>
>
> Hmmm.  The last time I fooled around with Lisp was 1966 from the Lisp
> 1.5 Manual Published by MIT in cloth.  It was interesting and
> different from the other languages I was using, Algol 60, Basic and
> Macro assembler for the GE-235 and GE-635.  When I read some of the
> over the top type hype by Lisp enthusiasts (like the stuff above) it
> feels like a flash back to the mid 60's.  Personally, I never like
> Lisp syntax; Clearly some people, some fanatic judging by this thread
> :) think easily in prefix.  I am not one of them.

Doesn't matter.  We are Borg.  You will be assimilated.  Resistance is
futile. :-)

But seriously, look at how features from Lisp are constantly finding
their way into mainstream programming languages and have done so for
decades (garbage colection, closures, ...).  Maybe one day prefix
notation and Lisp style macros will also find their way into other
languages and then Lisp will finally take over. :-) And here's another
thing: All the interesting features that haven't originated from Lisp
(e. g. OO from Smalltalk) could in turn easily be implemented in Lisp
with a couple of macros.  I. e. if Common Lisp didn't have CLOS, its
object system, I could write my own as a library and it would be just
as powerful and just as easy to use as the system Common Lisp already
provides.  Stuff like this is impossible in other languages.

To summarize: Lispers are not fanatics.  And if we appear to be then
it is simply because we recognize that Lisp truly is The Chosen
Language. [1]


Footnotes:
[1]  Kidding! :-)  ... or am I?

--
Wolfram Fenske

A: Yes.
>Q: Are you sure?
>>A: Because it reverses the logical flow of conversation.
>>>Q: Why is top posting frowned upon?

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


Re: merits of Lisp vs Python

2006-12-09 Thread Wolfram Fenske
Steven D'Aprano <[EMAIL PROTECTED]> schreibt:

> On Sat, 09 Dec 2006 14:00:10 +, Timofei Shatrov wrote:
>
>> On Sat, 09 Dec 2006 20:36:02 +1100, Steven D'Aprano
>> <[EMAIL PROTECTED]> tried to confuse everyone with this
>> message:
>>
>>>On Fri, 08 Dec 2006 23:38:02 -0800, Wolfram Fenske wrote:
>>>
>>>> if Common Lisp didn't have CLOS, its object system, I could write my own
>>>> as a library and it would be just as powerful and just as easy to use as
>>>> the system Common Lisp already provides.  Stuff like this is impossible
>>>> in other languages.
>>>
>>>Dude. Turing Complete. Don't you Lisp developers know anything about
>>>computer science?
>>
>> Here, you've basically shot yourself in the ass. Appealing to
>> Turing completeness when talking about programming language
>> features is about the dumbest thing you can make. In Turing sense,
>> a program is simply a function that takes an argument and returns a
>> value. It doesn't say anything about how this function was
>> implemented. It could be Turing machine, lambda calculus, Markov
>> chains or whatever else. All these methods produce the same set of
>> programs, but that doesn't mean you could implement lambda in
>> Turing machine for example.

[...]

> If you're talking about practicality, then of course you're correct,
> not all languages are equally expressive. Some languages are not
> expressive enough.

I agree.

> Some languages are too expressive.

I disagree.  "Too expressive"--what a thing to say.

[...]

> Look, all snarkiness aside, it just isn't true that "stuff like this
> is impossible in other languages". If Wolfram Fenske had said "stuff
> like this isn't easy in many other languages" he would have been
> right.

I said that it's impossible to write you own object system in other
languages *and* have it behave like it was part of the language.  OK,
you could always write your own pre-processor, i. e., your own
Foo+Objects to Foo compiler.  But that's almost like saying it's
impossible.  Now, object systems aside, how about that one: One of the
new features of Python 2.5 is a syntax for

--8<---cut here---start->8---
if condition:
x = true_value
else:
x = false_value
--8<---cut here---end--->8---

which becomes

--8<---cut here---start->8---
x = true_value if condition else false_value
--8<---cut here---end--->8---

(see [1]).  IMO that's a nice addition because this pattern is
something that has bothered me for some time.

Here's another one, the "with" statement [2]:

--8<---cut here---start->8---
Some standard Python objects now support the context management
protocol and can be used with the 'with' statement. File objects are
one example:

with open('/etc/passwd', 'r') as f:
for line in f:
print line
... more processing code ...

After this statement has executed, the file object in f will have been
automatically closed, even if the 'for' loop raised an exception
part-way through the block.
--8<---cut here---end--->8---

My point is that in Python--and AFAIK any other language except maybe
OCaml and maybe maybe Haskell--, you have to wait for these changes
until the language designers decide to make the for you.  And if they
don't, you're out of luck.  In Lisp, you can just add this yourself.

> And if he had said "and stuff like this carries risks as well as
> benefits" he would have come across as less of a language fanatic.

Sure, you can shoot yourself in the foot with macros.  But you can do
that in any language of any degree of expressiveness [3].  Come to
think of it, the whole reason why we use high level languages is
because of their expressiveness: We get stuff done faster and
introduce less errors.  So "the more expressive, the better," right?
But according to you, there's a point when a language gets "too
expressive".  I don't see why.

> One of the risks with Python is the ease with which you can modify the
> built-ins. An expression like list(2, 3, 4) doesn't necessarily create a
> list from 2, 3, and 4, because the built-in list could be redefined.
> (In practice, that's not often a real problem, because experienced
> Python developers simply learn not to needlessly or confusingly shadow
> built-ins. It's not the best system, but it works well enough in
> practice.)

So

Re: MySQL

2006-02-16 Thread Wolfram Kraus
rodmc wrote:
> I need to write a Python application which connects to a MySQL 5.0
> database. Can anyone point me in the right direction or a compatible
> library?
> 
> Best,
> 
> rod
> 

See http://sourceforge.net/projects/mysql-python


HTH,
Wolfram
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's this error then?

2005-05-02 Thread Wolfram Kraus
Sara Khalatbari wrote:
> You remember me asking about running a program in my
> code...I got a problem here
> 
[...]

> & my code is:
> #! /usr/bin/env python
 ^
Remove this space, the line should be:
#!/usr/bin/env python


> 
> import os
> from os import execl
> 
> os.execl ('/home/sara/PYTHON/HEADER/msgfmt.py',
> 'file-roller.HEAD.fa.po')
> 
> 
> But when I run it, this Error raises:
> [EMAIL PROTECTED] HEADER]$ python run.py
> /usr/bin/env: python2.2: No such file or directory
> 
> Do you have any solutions?


HTH,
Wolfram
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function with variable arguments

2005-05-13 Thread Wolfram Kriesing
using default args does actually solve it
what about

def Range(n, m=None, step=None)
  if step==None:
if m==None:
  range(n)
else:
  range(n,m)
  else:
if m==None:
   raise Exception, "missing parameter m"
else:
  range(n,m,step)

can be optimized i am sure :-)

-- 
cu

Wolfram


On 13 May 2005 02:52:34 -0700, Xah Lee <[EMAIL PROTECTED]> wrote:
> i wanted to define a function where the number of argument matters.
> Example:
> 
> def Range(n):
> return range(n+1)
> 
> def Range(n,m):
> return range(n,m+1)
> 
> def Range(n,m,step):
> return range(n,m+1,step)
> 
> this obvious doesn't work. The default argument like
> Range(n=1,m,step=1) obviously isn't a solution.
> 
> can this be done in Python?
> 
> or, must the args be changed to a list?
> 
>  Xah
>  [EMAIL PROTECTED]
> ∑ http://xahlee.org/
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: function with variable arguments

2005-05-13 Thread Wolfram Kriesing
> def Range(n,m=None,step=1):
>   if m is None:
> n,m = 0,n+1
>   else:
> n,m = n,m+1
>   return range(n,m,step)

i like this one. 

coming from php (just a couple weeks ago) its always again interesting
to see how i have to start thinking to program differently, it can be
so much easier with python. i dont want to go back to php!

-- 
cu

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


doc tags?

2005-05-13 Thread Wolfram Kriesing
i was already searching and remember i had seen something like "its not needed".

Anyway, are there any doc tags, like in Java/PHPDoc etc, where you can
describe parameters (@param[eter]), return values (@ret[urn]),
attributes (@var), references (@see), etc?

I guess I have just not found the link to the last flameware about it :-))

-- 
cu

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


Re: doc tags?

2005-05-13 Thread Wolfram Kraus
Wolfram Kriesing wrote:
> i was already searching and remember i had seen something like "its not 
> needed".
> 
> Anyway, are there any doc tags, like in Java/PHPDoc etc, where you can
> describe parameters (@param[eter]), return values (@ret[urn]),
> attributes (@var), references (@see), etc?
> 
> I guess I have just not found the link to the last flameware about it :-))
> 

I'm not sure if there is something like that builtin, but you can use 
epydoc: http://epydoc.sourceforge.net/

HTH,
Wolfram :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: doc tags?

2005-05-13 Thread Wolfram Kriesing
i am really looking for documenting my code, actually i expect the ide
to interpret them too and show me the doc etc., since i am missing
that a lot. esp. attributes' doc i was missing which made me write
this post
if there is not standard tool (or even a PEP) is there any pythonic
syntax? (which might make it into the standard lib, to be available
like the doc-string also inside the code -  i really like the __doc__)

-- 
cu

Wolfram

On 5/13/05, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Wolfram Kriesing wrote:
> 
> > i was already searching and remember i had seen something like "its not 
> > needed".
> >
> > Anyway, are there any doc tags, like in Java/PHPDoc etc, where you can
> > describe parameters (@param[eter]), return values (@ret[urn]),
> > attributes (@var), references (@see), etc?
> 
> do you want to use javadoc-style comments for your documentation?
> 
> http://effbot.org/zone/pythondoc.htm
> 
> or are you just looking for some syntactic construct that uses an at-
> sign?
> 
> http://www.python.org/peps/pep-0318.html
> http://docs.python.org/ref/function.html
> 
> 
> 
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strings for a newbie

2005-05-27 Thread Wolfram Kraus
Malcolm Wooden wrote:
> I'm trying to get my head around Python but seem to be failing miserably. I 
> use RealBasic on a Mac and find it an absolute dream! But PythonUGH!
> 
> I want to put a sentence of words into an array, eg "This is a sentence of 
> words"
> 
> In RB it would be simple:
> 
> Dim s as string
> Dim a(-1) as string
> Dim i as integer
> 
> s = "This is a sentence of words"
> For i = 1 to CountFields(s," ")
>   a.append NthField(s," ",i)
> next
> 
> That's it an array a() containing the words of the sentence.
> 
> Now can I see how this is done in Python? - nope!
> 
> UGH!
> 
> Malcolm
> (a disillusioned Python newbie) 
> 
> 
Use split:

 >>> s = "This is a sentence of words"
 >>> s.split()
['This', 'is', 'a', 'sentence', 'of', 'words']

See:
http://www.python.org/doc/2.4.1/lib/string-methods.html#l2h-202

HTH,
Wolfram
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Incrementing letters

2005-05-27 Thread Wolfram Kraus
Heiko Wundram wrote:
> Am Freitag, 27. Mai 2005 13:31 schrieb Michael:
> 
>>if(C == 'z') C='a';
>>else C++;
> 
> 
> if C == "z":
>   C = "a"
> else:
>   C = chr(ord(C)+1)
> 
According to the OP's problem (with the assumption that only characters 
  from a-z are given) he might even try a lil LC:
 >>> s = "shiftthis"
 >>> ''.join([chr(((ord(x)-ord('a')+1)%26)+ord('a')) for x in s])
'tijguuijt'


HTH,
Wolfram
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strings for a newbie

2005-05-27 Thread Wolfram Kraus
Malcolm Wooden wrote:
> my actual code is:
> 
>   for x in range(len(l)):
> h = string.split(l[x])
> 
> where the sentence string is in an array of one element 'l'
> Error is:
> 
> Traceback (most recent call last):
>   File "", line 34, in ?
>   File "", line 27, in SentenceText
>   File "C:\PYTHON22\lib\string.py", line 122, in split
> return s.split(sep, maxsplit)
> AttributeError: 'list' object has no attribute 'split'
> 

What is l[x]? Are you sure that l[x] is a string? Do a print before the 
split to see what l[x] is. Oh, and no need for range here, if l is a list:

for x in l:
  print x
  h = x.split()

HTH,
Wolfram
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Incrementing letters

2005-05-27 Thread Wolfram Kraus
Duncan Booth wrote:
> Michael wrote:
> 
> 
>>Hi,
>>I've got a string s, and i want to shift all the letters up by one, eg
>>a->b, b->c  z->a
>>In c++ i can do this quite simply with
>>
>>if(C == 'z') C='a';
>>else C++;
>>
>>but i can't work out how to do this this in python??
> 
> 
>>>>import string
>>>>upone = string.maketrans(
> 
> 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
> 'bcdefghijklmnopqrstuvwxyzaBCDEFGHIJKLMNOPQRSTUVWXYZA')
> 
>>>>string.translate("I've got a string s", upone)
> 
> "J'wf hpu b tusjoh t"
> 
> 
> Note the difference though: the Python code does what you said you wanted, 
> whereas your sample code corrupts punctuation.

Wow, that's quite nice. You really learn something new every day :-)
A minor improvement: Use string.ascii_letters as the first parameter for 
string.maketrans

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


Re: What's wrong with Zope 3 ?

2005-05-31 Thread Wolfram Kraus
Kay Schluehr wrote:
> The last downloadable release is from november 2004. The Windows
> installer is configured for Python 2.3(!). The Zope.org main page
> announces Zope 2.8 beta 2. Is it stillborn? 
> 
> Kay
> 
What you see is not Zope 3, it is Zope X 3. To quote from the X3 
information page: "Zope X3 3.0 is for developers. If you are expecting 
an end-user application, this is not for you."
The current stable brance is Zope2.X If you want to incorporate some 
functionalty from X3 in Zope 2.X, do a search for "Five"

HTH,
Wolfram
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's wrong with Zope 3 ?

2005-06-02 Thread Wolfram Kraus
Kay Schluehr wrote:
> 
> Wolfram Kraus wrote:
> 
>> Kay Schluehr wrote:
>> 
>>> The last downloadable release is from november 2004. The Windows 
>>> installer is configured for Python 2.3(!). The Zope.org main page
>>>  announces Zope 2.8 beta 2. Is it stillborn?
>>> 
>>> Kay
>>> 
>> 
>> What you see is not Zope 3, it is Zope X 3. To quote from the X3 
>> information page: "Zope X3 3.0 is for developers. If you are
>> expecting an end-user application, this is not for you."
> 
> 
> Yes I noticed this almost 8 months ago, read a bit of the
> documentation and articles published that time, regarded it as
> interesting and considered it for future development. But since then
> absolutely nothing happened. No project plan, no time-schedule, no
> subsequent releases.
You can always scan the zope3-mailinglist at zope.org (or via
news.gmane.org) to see whats happening. Migth be a better place for 
questions, too.

>> The current stable brance is Zope2.X If you want to incorporate
>> some functionalty from X3 in Zope 2.X, do a search for "Five"
> 
> 
> No, I do not want to migrate components from a new major release 
> backwards, as well as I do not want to migrate applications from
> WinXP to Win98. This seems to be the wrong development process
> direction.
Well, the problem is that it is not a "new major release" but a "new 
mayor experimental release". And X3 is not backward compatible, so a lot 
of Z2 products, e.g. Plone, don't work with X3.

> Regards, Kay
> 

HTH,
Wolfram (still using Z2 ;-))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Just for fun: Countdown numbers game solver

2008-02-17 Thread wolfram . hinderer
On 22 Jan., 23:56, [EMAIL PROTECTED] wrote:
> So anyone got an answer to which set of numbers gives the most targets
> from 100 onwards say (or from 0 onwards)? IsPythonupto the task?

It's (5, 8, 9, 50, 75, 100): 47561 targets altogether (including
negative ones), 25814 targets >= 100.
(BTW, 1226 sets of numbers give all 900 3-digit targets, but the above
one doesn't; 954 and 981 are missing.)

The following (mostly) straightforward program needed about 30 min for
the calculation. I tried to keep all (intermediate) results in a dict
(which turned out later to need too much memory). I wanted to use the
same dict for memoization. So I let the dict fill itself on access.
The disadvantage of this method is that the function needs to know
that it's being memoized. The advantage is that it's easier (I think)
to manipulate/control the dict.


class AutoFillDict(dict):
""" Values for missing keys are computed on-the-fly """

def __init__(self, func, *args, **kwargs):
self.func = func
super(AutoFillDict, self).__init__(*args, **kwargs)

def __missing__(self, key):
self[key] = self.func(self, key)
return self[key]


def subs_k(dic, (nums, k)):
""" Return k-subsets of tuple nums, using dic as cache """
if k == 1:
return [(i,) for i in nums]
if k == len(nums):
return [nums]
a = nums[:1]
b = nums[1:]
return [a + i for i in dic[b, k-1]] + dic[b, k]


def subs_and_complements(dic, nums):
""" Return subsets and complements of tuple nums, using dic as
cache """
if not nums:
return set([((), ())])
a = nums[:1]
b = nums[1:]
res = set([(s, a + c) for s, c in dic[b]])
res.update([(a + s, c) for s, c in dic[b]])
return res


subs_and_comps = AutoFillDict(subs_and_complements)


def countdown(dic, nums, sac_dict=subs_and_comps):
"""Return all possible goals for input nums, using dic as cache

All numbers in nums must be used.

"""
if len(nums) == 1:
return nums
ret = set()
for s, c in sac_dict[nums]:
if s and c:
xs = dic[s]
ys = dic[c]
ret.update([x + y for x in xs for y in ys])
ret.update([x - y for x in xs for y in ys])
ret.update([x * y for x in xs for y in ys])
ret.update([x // y for x in xs for y in ys if y != 0 and x
% y == 0])
return ret


def print_max(results):
max_goals = max(results.values())
max_nums = [n for (n, g) in results.items() if g == max_goals]
max_nums.sort()
print "Maximal number of reachable goals: %d" % max_goals
print "Number of tuples: %d" % len(max_nums)
for n in max_nums:
print n


if __name__ == "__main__":

all_nums = range(1, 11)*2 + [25, 50, 75, 100]
all_nums = tuple(sorted(all_nums))

subsets_k = AutoFillDict(subs_k)
d = AutoFillDict(countdown)

results = {}
results100 = {}
for i, nums in enumerate(sorted(set(subsets_k[all_nums, 6]))):
# result is the union of reachable goals for all subsets
result = set()
for s, c in subs_and_comps[nums]:
result.update(d[s])
results[nums] = len(result)
results100[nums] = len([x for x in result if x >= 100])
# Prevent MemoryError
    if i % 200 == 0:
d.clear()

print "Goals: all integers"
print_max(results)
print
print "Goals: integers >= 100"
print_max(results100)

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


Re: Indentation and optional delimiters

2008-02-26 Thread wolfram . hinderer
On 26 Feb., 14:36, [EMAIL PROTECTED] wrote:
> A possible solution to this problem is "optional delimiters". What's
> the path of less resistance to implement such "optional delimiters"?
> Is to use comments. For example: #} or #: or something similar.
> If you use such pairs of symbols in a systematic way, you have cheap
> "optional delimiters", for example:
>
> def insort_right(a, x, lo=0, hi=None):
> if hi is None:
> hi = len(a)
> #}
> while lo < hi:
> mid = (lo + hi) // 2
> if x < a[mid]:
> hi = mid
> #}
> else:
> lo = mid+1
> #}
> #}
> a.insert(lo, x)
> #}
>
> It looks a bit ugly, but a script is able to take such code even
> flattened:
>
> def insort_right(a, x, lo=0, hi=None):
> if hi is None:
> hi = len(a)
> #}
> while lo < hi:
> mid = (lo + hi) // 2
> if x < a[mid]:
> hi = mid
> #}
> else:
> lo = mid+1
> #}
> #}
> a.insert(lo, x)
> #}
>
> And build the original Python code (it's possible to do the opposite
> too, but it requires a bit more complex script).

Have a look at Tools/Scripts/pindent.py

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


Re: Functional schmunctional...

2009-02-11 Thread wolfram . hinderer
On 10 Feb., 21:28, r0g  wrote:

> def inet2ip(n, l=[], c=4):
>   if c==0: return ".".join(l)
>   p = 256**( c-1 )
>   l.append( str(n/p) )
>   return inet2ip( n-(n/p)*p, l, c-1 )

> The results for 1
> iterations of each were as follows...
>
> 0.113744974136 seconds for old INET->IP method
> 27.744112 seconds for new INET->IP method
>
> :-/

That's probably because your new function is broken:

>>> def inet2ip(n, l=[], c=4):
  if c==0: return ".".join(l)
  p = 256**( c-1 )
  l.append( str(n/p) )
  return inet2ip( n-(n/p)*p, l, c-1 )

>>> inet2ip(0)
'0.0.0.0'
>>> inet2ip(0)
'0.0.0.0.0.0.0.0'
>>> inet2ip(0)
'0.0.0.0.0.0.0.0.0.0.0.0'

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


Re: Self function

2009-05-05 Thread wolfram . hinderer
On 5 Mai, 08:08, Steven D'Aprano
 wrote:

> Self-reflective functions like these are (almost?) unique in Python in
> that they require a known name to work correctly. You can rename a class,
> instance or module and expect it to continue to work, but not so for such
> functions. When editing source code, it is very easy to forget to change
> all the references to the function name within the body of itself
> function, even for small functions, and refactoring tools are overkill.

It is easy to change all references of the function name, except for
those in the function body itself? That needs some explantation.

> It is often useful to create two similar functions, or a variant of a
> function, without duplicating the source code. E.g. you might want a
> function that uses a cache, while still keeping around the version
> without a cache:
>
> cached_function = memoize(function)
>
> Currently, this does not give the expected results for recursive
> functions, nor does it give an error. It simply fails to behave as
> expected. Re-writing function() to use __this__ for the recursive call
> will solve that problem.

Won't __this__ (inside function) still refer to function, not
cached_function?

> Here is a proof-of-concept pure Python implementation, using a decorator,
> and abusing a global variable. This is NOT to imply that `__this__`
> should be a global if this proposal goes ahead.
>
> from functools import wraps
> def make_this(func):
>     global __this__
>     __this__ = func
>     @wraps(func)
>     def f(*args, **kwargs):
>         return func(*args, **kwargs)
>     return f

This still has the memoizing problem.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can this program be shortened? Measuring program-length?

2008-07-10 Thread wolfram . hinderer
On 10 Jul., 21:57, "r.e.s." <[EMAIL PROTECTED]> wrote:
> Can the following program be shortened? ...
>
> def h(n,m):
>  E=n,
>  while (E!=())*m>0:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n
>  return n
> h(9,9)
>

Some ideas...

# h is your version
def h(n,m):
 E=n,
 while (E!=())*m>0:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n
 return n

def g(n,m):
 E=n,
 while E*m:n=h(n+1,m-1);E=E[:-1]+(E[-1]>0)*(E[-1]-1,)*n
 return n

def f(n,m):
 E=n,
 while E*m:n=h(n+1,m-1);E=(E[0]>0)*(E[0]-1,)*n+E[1:]
 return n

def e(n,m):
 E=[n]
 while E*m:n=h(n+1,m-1);E[:1]=(E[0]>0)*[E[0]-1]*n
 return n

# some tests
print h(1,1), h(2,1), h(0,2)
print g(1,1), g(2,1), g(0,2)
print f(1,1), f(2,1), f(0,2)
print e(1,1), e(2,1), e(0,2)

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


Re: substitution of list elements

2008-07-18 Thread Wolfram Kraus

Am 18.07.2008 14:33, antar2 schrieb:

I want to replace each first element in list 5 that is equal to the
first element of the list of lists4 by the fourth element. I wrote
following code that does not work:

list4 = [['1', 'a', 'b', 'c'], ['2', 'd', 't', 'e'], ['8', 'g', 'q',
'f']]
list5 = ['1', '2', '3']

for j in list4:
  for k in list5:

  for i,k in enumerate(list5):


if j[0] == k:
    k = j[3]

  list5[i] = j[3]


print list5
Wanted result: ['c', 'e', '3']

thanks!


You didn't replace the list element itself.

HTH,
Wolfram
--
http://mail.python.org/mailman/listinfo/python-list


Re: seemingly simple list indexing problem

2008-07-30 Thread wolfram . hinderer
On 29 Jul., 01:05, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
> [Ervan Ensis]
>
> > I have a list like [108, 58, 68].  I want to return
> > the sorted indices of these items in the same order
> > as the original list.  So I should return [2, 0, 1]
>
> One solution is to think of the list indexes
> being sorted according the their corresponding
> values in the input array:
>
> >>> s = [ 108, 58, 68 ]
> >>> sorted(range(len(s)), key=s.__getitem__)
>
> [1, 2, 0]
>

To get the desired output you have to apply it twice:
>>> sorted(range(len(s)), key=sorted(range(len(s)), 
>>> key=s.__getitem__).__getitem__)
[2, 0, 1]

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


Re: Dangerous behavior of list(generator)

2010-01-01 Thread Wolfram Hinderer
On 1 Jan., 02:47, Steven D'Aprano  wrote:
> On Thu, 31 Dec 2009 11:34:39 -0800, Tom Machinski wrote:


> > On Wed, Dec 30, 2009 at 4:01 PM, Steven D'Aprano
> >  wrote:
> >> On Wed, 30 Dec 2009 15:18:11 -0800, Tom Machinski wrote:
> >>> Bottom line, I'm going to have to remove this pattern from my code:
>
> >>>   foo = (foo for foo in foos if foo.bar).next()
>
> >> I don't see why. What's wrong with it? Unless you embed it in a call to
> >> list, or similar, it will explicitly raise StopIteration as expected.
>
> > Exactly; this seems innocuous, but if some caller of this code uses it
> > in a list() constructor, a very subtle and dangerous bug is introduced -
> > see OP. This is the entire point of this post.
>
> Then don't use it in a list() constructor.
>
> That's a glib answer, of course. A better answer is to point out that the
> problem is not with the above expression, but with letting StopIteration
> bubble up as an error exception instead of dealing with it immediately.
> That's not what it's for, and you can't trust it not to be captured by
> something. If StopIteration represents an error condition, you need to
> deal with it immediately and convert it to an exception which isn't
> likely to disappear.
>
> > In a large, non-trivial application, you simply cannot afford the
> > assumption that no caller will ever do that. Even if you have perfect
> > memory, some of your other developers or library users may not.
>
> You shouldn't put the responsibility of dealing with the StopIteration on
> the caller, because StopIteraction is a signal not an error condition,
> and you can't tell when that signal will disappear. The responsibility
> lies on the writer of the function containing the line (that is, the
> Original Poster of this thread).
>
> So you need something like this:
>
> def my_function():
>     try:
>         foo = (foo for foo in foos if foo.bar).next()
>     except StopIteration:
>         handle_empty_foos()
>     else:
>         handle_at_least_one_foo()
>
> handle_empty_foos may be as simple as raising a new exception and letting
> that bubble up to whatever layer of the application is expected to deal
> with it.
>

> > As for what's wrong with the "if not any" solution, Benjamin Kaplan's
> > post hits the nail on its head. This is a bioinformatics application, so
> > the iterable "foos" tends to be very large, so saving half the runtime
> > makes a big difference.
>
> Possibly you haven't seen my reply to Benjamin, so I'll paraphrase:
> that's incorrect, because any() is lazy and will return as soon as it
> hits a non-false item.

Tom's point is that
if not any(foo for foo in foos if foo.bar):
foo = (foo for foo in foos if foo.bar).next()
iterates twice over (the same first few elements of) foos, which
should take about twice as long as iterating once. The lazyness of
"any" does not seem to matter here.
Of course, you're right that the iteration might or might not be the
bottleneck. On the other hand, foos might not even be reiterable.

> If the foo items are arbitrary objects which have an equal chance of
> being considered true or false, then on average it will have to look at
> half the list,

By which definition of chance? :-)

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


Re: Writing a string.ishex function

2010-01-14 Thread Wolfram Hinderer
On 14 Jan., 19:48, MRAB  wrote:
> Arnaud Delobelle wrote:
> > "D'Arcy J.M. Cain"  writes:
>
> >> On Thu, 14 Jan 2010 09:07:47 -0800
> >> Chris Rebert  wrote:
> >>> Even more succinctly:
>
> >>> def ishex(s):
> >>>     return all(c in string.hexdigits for c in s)
> >> I'll see your two-liner and raise you.  :-)
>
> >> ishex = lambda s: all(c in string.hexdigits for c in s)
>
> > I'see your one-liner and raise you by four characters :o)
>
> > ishex1 = lambda s: all(c in string.hexdigits for c in s) # Yours
> > ishex2 = lambda s: not(set(s)-set(string.hexdigits))     # Mine
>
> I raise you one character:
>
> ishex2 = lambda s: not(set(s)-set(string.hexdigits))     # Yours
> ishex3 = lambda s: not set(s)-set(string.hexdigits)      # Mine
>
> I could actually go three better:
>
> ishex3=lambda s:not set(s)-set(string.hexdigits)
>
> :-)
>

ishex4=lambda s:not s.strip(string.hexdigits)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Performance of lists vs. list comprehensions

2010-01-19 Thread Wolfram Hinderer
On 19 Jan., 16:30, Gerald Britton  wrote:
> >>> Timer("' '.join([x for x in l])", 'l = map(str,range(10))').timeit()
>
> 2.9967339038848877
>
> >>> Timer("' '.join(x for x in l)", 'l = map(str,range(10))').timeit()
>
> 7.2045478820800781

[...]

> 2. Why should the "pure" list comprehension be slower than the same
> comprehension enclosed in '[...]' ?

Others have already commented on "generator expression" vs. "list
comprehension". I'll try to shed some light on the cause of the
slowness.

For me it's
>>> Timer("' '.join([x for x in l])", 'l = map(str,range(10))').timeit()
0.813948839866498
>>> Timer("' '.join(x for x in l)", 'l = map(str,range(10))').timeit()
2.226825476422391

But wait! I'm on Python 3.1 and the setup statement has to be changed
to make this test meaningful.
>>> Timer("' '.join([x for x in l])", 'l = list(map(str,range(10)))').timeit()
2.5788493369966545
>>> Timer("' '.join(x for x in l)", 'l = list(map(str,range(10)))').timeit()
3.7431774848480472

Much smaller factor now.
But wait! If we want to test list comprehension against generator
comprehension, we should try a function that just consumes the
iterable.

>>> setup = """l = list(map(str,range(10)))
... def f(a):
... for i in a: pass
... """
>>> Timer("f([x for x in l])", setup).timeit()
3.288511528699928
>>> Timer("f(x for x in l)", setup).timeit()
2.410873798206012

Oops! Iteration over generator expressions is not inherently more
expension than iteration over list comprehensions. But certainly
building a list from a generator expression is more expensive than a
list comprehension?

>>> Timer("[x for x in l]", 'l = list(map(str,range(10)))').timeit()
2.088602950933364
>>> Timer("list(x for x in l)", 'l = list(map(str,range(10)))').timeit()
3.691566805277944

Yes, list building from a generator expression *is* expensive. And
join has to do it, because it has to iterate twice over the iterable
passed in: once for calculating the memory needed for the joined
string, and once more to actually do the join (this is implementation
dependent, of course). If the iterable is a list already, the list
building is not needed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Performance of lists vs. list comprehensions

2010-01-19 Thread Wolfram Hinderer
On 19 Jan., 21:06, Gerald Britton  wrote:
> [snip]
>
>
>
> > Yes, list building from a generator expression *is* expensive. And
> > join has to do it, because it has to iterate twice over the iterable
> > passed in: once for calculating the memory needed for the joined
> > string, and once more to actually do the join (this is implementation
> > dependent, of course). If the iterable is a list already, the list
> > building is not needed.
>
> if join has to iterate twice over the iterable, how does this work?
>
> $ python3.1
> Python 3.1.1+ (r311:74480, Nov  2 2009, 14:49:22)
> [GCC 4.4.1] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>
> >>> l = map(str, (x for x in range(10) if int(x)%2))
> >>> '.'.join(l)
> '1.3.5.7.9'
>
> If join had to iterate twice over l, it would be consumed on the first
> pass.

Yes. (Coincidentally, l is consumed in the first execution of the Timer
()-statement, which is why I had to add the call to list. Not to
mention the xrange example of Stephen. But all this is not linked to
what join does internally.)

> If it works as you say then join would have to copy the
> iterable on the first pass, effectively turning it into a list.

Yes, that's what I'm saying above in the first two lines of what you
quoted.
I should have added somehting like "AFAIK CPython does it that way".

> Though I didn't read through it, I would suppose that join could use a
> dynamic-table approach to hold the result, starting with some
> guesstimate then expanding the result buffer if and when needed.

Probably. But that's not what happens. Try
"".join("" for x in range(10**10)
and watch join eating memory.


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


Re: Traversing through variable-sized lists

2010-02-17 Thread Wolfram Hinderer
On 17 Feb., 19:10, Andrej Mitrovic  wrote:
> Hi,
>
> I couldn't figure out a better description for the Subject line, but
> anyway, I have the following:
>
> _num_frames = 32
> _frames = range(0, _num_frames) # This is a list of actual objects,
> I'm just pseudocoding here.
> _values = [0, 1, 2, 3, 4]
>
> I want to call a function of _frames for each frame with a _values
> argument, but in a way to "spread out" the actual values.
>
> I would want something similar to the following to be called:
>
> _frames[0].func(_values[0])
> _frames[1].func(_values[0])
> _frames[2].func(_values[0])
> _frames[3].func(_values[0])
> _frames[4].func(_values[1])
> _frames[5].func(_values[1])
> _frames[6].func(_values[1])
> _frames[7].func(_values[1])
> _frames[8].func(_values[2])
> ...etc...
>
> Both the _values list and _frames list can be of variable and uneven
> size, which is what is giving me the problems. I'm using Python 2.6.
>
> I've tried the following workaround, but it often gives me inaccurate
> results (due to integer division), so I had to add a safety check:
>
> num_frames = 32
> values = [0, 1, 2, 3, 4]
> offset_step = num_frames / len(values)
>     for index in xrange(0, num_frames):
>         offset = index / offset_step
>         if offset > offset_values[-1]:
>             offset = offset_values[-1]
>         frames[index].func(values[offset])
>
> There has to be a better way to do this. I'd appreciate any help.
> Cheers!

Python 3.1:
>>> def apply_spreaded(funcs, values):
... num_funcs = len(funcs)
... num_values = len(values)
... for i, func in enumerate(funcs):
... func(values[(i * num_values) // num_funcs])

>>> apply_spreaded([print] * 8, range(5))
0
0
1
1
2
3
3
4

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


Re: Fastest way to calculate leading whitespace

2010-05-08 Thread Wolfram Hinderer
On 8 Mai, 20:46, Steven D'Aprano  wrote:

> def get_leading_whitespace(s):
>     t = s.lstrip()
>     return s[:len(s)-len(t)]
>
> >>> c = get_leading_whitespace(a)
> >>> assert c == leading_whitespace
>
> Unless your strings are very large, this is likely to be faster than any
> other pure-Python solution you can come up with.

Returning s[:-1 - len(t)] is faster.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fastest way to calculate leading whitespace

2010-05-09 Thread Wolfram Hinderer
On 8 Mai, 21:46, Steven D'Aprano  wrote:
> On Sat, 08 May 2010 12:15:22 -0700, Wolfram Hinderer wrote:
> > Returning s[:-1 - len(t)] is faster.
>
> I'm sure it is. Unfortunately, it's also incorrect.

> However, s[:-len(t)] should be both faster and correct.

Ouch. Thanks for correcting me.

No, I'll never tell how that -1 crept in...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Composition of functions

2010-07-01 Thread Wolfram Hinderer
On 1 Jul., 06:04, Stephen Hansen  wrote:
> The 'reversed' and 'sorted' functions are generators that lazilly
> convert an iterable as needed.

'sorted' returns a new list (and is not lazy).



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


Re: Python -- floating point arithmetic

2010-07-07 Thread Wolfram Hinderer
On 7 Jul., 19:32, Ethan Furman  wrote:
> Nobody wrote:
> > On Wed, 07 Jul 2010 15:08:07 +0200, Thomas Jollans wrote:
>
> >> you should never rely on a floating-point number to have exactly a
> >> certain value.
>
> > "Never" is an overstatement. There are situations where you can rely
> > upon a floating-point number having exactly a certain value.
>
> It's not much of an overstatement.  How many areas are there where you
> need the number
> 0.155511151231257827021181583404541015625000?
>
> If I'm looking for 0.1, I will *never* (except by accident ;) say
>
> if var == 0.1:
>
> it'll either be <= or >=.

The following is an implementation of a well-known algorithm.
Why would you want to replace the floating point comparisons? With
what?

(This is toy-code.)

#
from random import random

def min_cost_path(cost_right, cost_up):
""" return minimal cost and its path in a rectangle - going up and
right only """
cost = dict()
size_x, size_y = max(cost_right)

#compute minimal cost
cost[0, 0] = 0.0
for x in range(size_x):
cost[x + 1, 0] = cost[x, 0] + cost_right[x, 0]
for y in range(size_y):
cost[0, y + 1] = cost[0, y] + cost_up[0, y]
for x in range(size_x):
cost[x + 1, y + 1] = min(cost[x, y + 1] + cost_right[x, y
+ 1],
 cost[x + 1, y] + cost_up[x + 1,
y])

#compute path (reversed)
x = size_x
y = size_y
path = []
while x != 0 and y != 0:
if x == 0:
y -= 1
path.append("u")
elif y == 0:
x -= 1
path.append("r")
elif cost[x - 1, y] + cost_right[x - 1, y] == cost[x, y]: # fp
compare
x -= 1
path.append("r")
elif cost[x, y - 1] + cost_up[x, y - 1] == cost[x, y]: # fp
compare
y -= 1
path.append("u")
else:
raise ValueError

return cost[size_x, size_y], "".join(reversed(path))


if __name__ == "__main__":
size = 100
cost_right = dict(((x, y), random()) for x in range(size) for y in
range(size))
cost_up = dict(((x, y), random()) for x in range(size) for y in
range(size))
print min_cost_path(cost_right, cost_up)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python -- floating point arithmetic

2010-07-08 Thread Wolfram Hinderer
On 8 Jul., 15:10, Ethan Furman  wrote:

> Interesting.  I knew when I posted my above comment that I was ignoring
> such situations.  I cannot comment on the code itself as I am unaware of
> the algorithm, and haven't studied numbers extensively (although I do
> find them very interesting).
>
> So while you've made your point, I believe mine still stands --
> comparing floats using == to absolute numbers is almost always a mistake.

JFTR, it works because a+b == a+b (while I don't think that a+b == b+a
holds for all a and b).

In general, I totally agree with you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default behavior

2010-08-06 Thread Wolfram Hinderer
On 6 Aug., 22:07, John Posner  wrote:
> On 8/2/2010 11:00 PM, John Posner wrote:
>
> > On 7/31/2010 1:31 PM, John Posner wrote:
>
> >> Caveat -- there's another description of defaultdict here:
>
> >>http://docs.python.org/library/collections.html#collections.defaultdict
>
> >> ... and it's bogus. This other description claims that __missing__ is a
> >> method of defaultdict, not of dict.
>
> > Following is a possible replacement for the bogus description. Comments
> > welcome. I intend to submit a Python doc bug, and I'd like to have a
> > clean alternative to propose.
>
> After some off-list discussion with Ethan Furman (many thanks!), the
> Python Doc bug is submitted: #9536 at bugs.python.org.
>
> -John

This is probably nitpicking, but the patch calls __missing__ a special
method. However, unlike special methods, it is not invoked by "special
syntax" but by the dict's __getitem__ method. (len() invokes __len__
on any object - you can't do something similar with __missing__.)

__missing__ is also not listed as a special method on
http://docs.python.org/py3k/reference/datamodel.html#special-method-names

However, "normal" special method lookup seems to be used.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Turtle Graphics are incompatible with gmpy

2009-08-05 Thread Wolfram Hinderer
On 5 Aug., 21:31, Mensanator  wrote:
>
> >>> import turtle
> >>> tooter = turtle.Turtle()
> >>> tooter.tracer
>
> Traceback (most recent call last):
>   File "", line 1, in 
>     tooter.tracer
> AttributeError: 'Turtle' object has no attribute 'tracer'>>> 
> tooter.hideturtle()
> >>> tooter.speed('fast')
> >>> turtle.update()
> >>> turtle.tracer
>
> 
>
> How did the tracer attribute appear out of thin air?

You seem to confuse the "tooter" Turtle object and the "turtle" module
when talking about "the tracer attribute".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unpacking vars from list of tuples

2009-09-15 Thread Wolfram Hinderer
On 15 Sep., 23:51, Ross  wrote:

> If I have a list of tuples:
>
>    k=[("a", "bob", "c"), ("p", "joe", "d"), ("x", "mary", "z")]
>
> and I want to pull the middle element out of each tuple to make a new
> list:
>
> myList = ["bob", "joe", "mary"]

if a tuple is OK: zip(*k)[1]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How on Factorial

2010-10-30 Thread Wolfram Hinderer
On 27 Okt., 10:27, Arnaud Delobelle  wrote:
> True.  It's far too verbose.  I'd go for something like:
>
>     f=lambda n:n<=0 or n*f(~-n)
>
> I've saved a few precious keystrokes and used the very handy ~- idiom!

You can replace "n<=0" with "n<1". Then you can leave out the space
before "or" ("0or" wouldn't work with newer python versions).

f=lambda n:n<1or n*f(~-n)

Much better, isn't it? ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: count consecutive elements

2021-01-14 Thread Wolfram Hinderer via Python-list



Am 13.01.2021 um 22:20 schrieb Bischoop:

I want to  to display a number or an alphabet which appears mostly
consecutive in a given string or numbers or both
Examples
s= ' aabskaaabad'
output: c
# c appears 4 consecutive times
  8bbakebaoa
output: b
#b appears 2 consecutive times



You can let itertools.groupy find the groups.

max((len(tuple(group)), key) for key, group in itertools.groupby(s))
# (4, 'c')
--
https://mail.python.org/mailman/listinfo/python-list


Re: some problems for an introductory python test

2021-08-11 Thread Wolfram Hinderer via Python-list



Am 11.08.2021 um 05:22 schrieb Terry Reedy:
Python is a little looser about whitespace than one might expect from 
reading 'normal' code when the result is unambiguous in that it cannot 
really mean anything other than what it does.  Two other examples:


>>> if3: print('yes!')
yes!
>>> [0]  [0]
0


Not sure what you mean here - is it a joke? The first looks like an if 
statement, but isn't. The missing space *does* make a difference. (Try 
"if0" instead.)


The second is normal indexing, which allows white space. I wouldn't 
consider that surprising, but maybe I should? (Honest question, I really 
don't know.)


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


Re: best way to remove leading zeros from a tuple like string

2018-05-21 Thread Wolfram Hinderer via Python-list

Am 21.05.2018 um 01:16 schrieb [email protected]:

If I decide I need the parentheses, this works.


"(" + ",".join([str(int(i)) for i in s[1:-1].split(",")]) + ")"

'(128,20,8,255,-1203,1,0,-123)'

Thanks,
Bruce


Creating the tuple seems to be even simpler.

>>> str(tuple(map(int, s[1:-1].split(","
'(128, 20, 8, 255, -1203, 1, 0, -123)'

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