newbie question

2011-04-01 Thread Karl

Hello,

one beginner question:

aList = [0, 1, 2, 3, 4]
bList = [2*i for i in aList]
sum = 0
for j in bList:
sum = sum + bList[j]
   print j

0
2
4
IndexError: 'list index out of range'
Why is j in the second run 2 and not 1 in the for-loop?? I think j is a 
control variable with 0, 1, 2, 3, ...


Thanks!

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


Re: newbie question

2011-04-01 Thread Karl

Ah, all right. Thank you very much, eryksun!


On 2011-04-01 22:48:44 +0200, eryksun () said:


Regarding the format of your post, please use plain text only.

On Friday, April 1, 2011 3:52:24 PM UTC-4, Karl wrote:


aList = [0, 1, 2, 3, 4]
bList = [2*i for i in aList]
sum = 0
for j in bList:
sum = sum + bList[j]
print j

0
2
4

IndexError: list index out of range

Why is j in the second run 2 and not 1 in the for-loop?? I think
j is a control variable with 0, 1, 2, 3, ...


The for loop yields the elements of bList, not their index (it's like a 
foreach statement in other languages). Here's the full printout:


In [1]: aList = [0, 1, 2, 3, 4]
In [2]: bList = [2*i for i in aList]
In [3]: for j in bList:
   ...: print j

0
2
4
6
8

Since bList is 5 elements long, bList[6] is indeed "out of range". 
Here's a more direct way to accomplish this task:


In [4]: b_sum = sum(bList)
In [5]: b_sum
Out[5]: 20

Note that I'm not overwriting the name of the built-in function 'sum'. 
Try to avoid doing that. It's pretty simple to type the name in the 
interpreter and see if it's already bound to something you might want 
to keep around.


Here's one way to get the index in a loop:

In [6]: b_sum = 0
In [7]: for j, b in enumerate(bList):
   ...: b_sum += b
   ...: print j

0
1
2
3
4

In [9]: b_sum
Out[9]: 20

The enumerate function returns an iterable that's a tuple of the index 
and item. A for loop iterates over an iterable object such as a 
sequence.



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


[Help]UnicodeDecodeError

2007-03-18 Thread Karl
error msg:
Mod_python error: "PythonHandler mod_python.publisher"

Traceback (most recent call last):

  File "/usr/lib/python2.3/site-packages/mod_python/apache.py", line
299, in HandlerDispatch
result = object(req)

  File "/usr/lib/python2.3/site-packages/mod_python/publisher.py",
line 136, in handler
result = util.apply_fs_data(object, req.form, req=req)

  File "/usr/lib/python2.3/site-packages/mod_python/util.py", line
361, in apply_fs_data
return object(**args)

  File "/var/www/html/sky.py", line 38, in main
sresult = sresult.decode('zh-hk').encode('utf_8')

UnicodeDecodeError: 'big5hkscs' codec can't decode bytes in position
958-959: illegal multibyte sequence


Wt can I do, since there is some characters, is there any solutions to
solve it???

thx

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


Issues with `codecs.register` and `codecs.CodecInfo` objects

2012-07-06 Thread Karl Knechtel
Hello all,

While attempting to make a wrapper for opening multiple types of
UTF-encoded files (more on that later, in a separate post, I guess), I
ran into some oddities with the `codecs` module, specifically to do
with `.register` ing `CodecInfo` objects. I'd like to report a bug or
something, but there are several intertangled issues here and I'm not
really sure how to report it so I thought I'd open the discussion.
Apologies in advance if I get a bit rant-y, and a warning that this is
fairly long.

Observe what happens when you `register` the wrong function:

>>> import codecs
>>> def ham(name):
... # Very obviously wrong, just for demonstration purposes
... if name == 'spam': return 'eggs'
...
>>> codecs.register(ham)

Already there is a problem in that there is no error... there is no
realistic way to catch this, of course, but IMHO it points to an issue
with the interface. I don't want to register a codec lookup function;
I want to register *a codec*. The built-in lookup process would be
just fine if I could just somehow tell it about this one new codec I
have... I really don't see the use case for the added flexibility of
the current interface, and it means that every time I have a new
codec, I need to either create a new lookup function as well (to
register it), or hook into an existing one that's still of my own
creation.

Anyway, moving on, let's see what happens when we try to use the faulty codec:

>>> codecs.getencoder('spam')
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python32\lib\codecs.py", line 939, in getencoder
return lookup(encoding).encode
TypeError: codec search functions must return 4-tuples

Ehh?! That's odd. I thought I was supposed to return a `CodecInfo`
object, not a 4-tuple! Although as an aside, AFAICT the documentation
*doesn't actually document the CodecInfo class*, it just says what
attributes CodecInfo objects are supposed to have.

A bit of digging around with Google and existing old bugs on the
tracker suggests that this comes about due to backwards-compatibility:
in 2.4 and below, they *were* 4-tuples. But now CodecInfo objects are
expected to provide 6 functions (and a name), not 4. Clearly that
won't fit in a 4-tuple, and anyway I thought we had gotten rid of all
this deprecated stuff.

Regardless, let's see what happens if we do try to register a 4-tuple-lookup-er:

>>> def spam(name):
... # As long as we return a 4-tuple, it doesn't really matter
what the functions are;
... # errors shouldn't happen until we actually attempt to
encode/decode. Right?
... if name == 'spam': return (spam, spam, spam, spam)

Oops, we need to restart the interpreter, or otherwise reset global
state somehow, because the old lookup function has priority over this
one, and *there is no way to unregister it*. But once that's fixed:

>>> codecs.getencoder('spam')
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python32\lib\codecs.py", line 939, in getencoder
return lookup(encoding).encode
AttributeError: 'tuple' object has no attribute 'encode'

That's quite odd indeed. We can't actually trust the error message we
got before! 4-tuples don't work any more like they used to, so our
backwards-compatibility concession doesn't even work. Meanwhile, we're
left wondering how CodecInfo objects work at all. Is the error message
wrong?

Nope, well, not really. Let's grab an known good CodecInfo object and
see what we can find out...

>>> utf8 = codecs.lookup('utf-8')
>>> utf8.__class__.__bases__
(,)
>>> # not collections.namedtuple, which is understandable, since
that wasn't available until 2.6...
>>> len(utf8)
4
>>> # OK, apparently it magically actually is a tuple of length 4
despite needing 7 attributes. I wonder which ones are included:
>>> tuple(utf8)
(, , , )
>>> # Unsurprising: the ones mandated by the original PEP (100!
That long ago...)

... and if we try `help` (or look at examples in the standard library
or find them with Google - but I sure don't see any in the webpage
docs), we can at least find out how to construct a CodecInfo object
properly - although, curiously, it's implemented using `__new__`
rather than `__init__`.

You *can* hack around with `collections.namedtuple` and create
something that basically works:

# restarting again...
>>> import codecs, collections
>>> my_codecinfo = collections.namedtuple('my_codecinfo', 'encode
decode streamreader streamwriter')
>>> def spam(name):
... if name == 'spam': return my_codecinfo(spam, spam, spam, spam)

And now the error correctly doesn't occur until we actually attempt to
encode or decode something. Except we still don't have an incremental
decoder/encoder, and in fact those are missing attributes rather than
`None` as they're defaulted to by the `CodecInfo` class. (Of course,
we can subclass `collections.namedtup

[Windows] drag-and-drop onto .py file in modern versions?

2012-04-11 Thread Karl Knechtel
Hello all,

Back when I had 2.6.x installed, I used to be able to drag a file onto a
.py file in order to open it with that script (rather, pass the name of the
file as `sys.argv[1]`). I did nothing special to make this work, as far as
I can recall; it was something that the installer set up automatically. I
am running Windows Vista.

Now that I have uninstalled 2.6.x, and have 2.7.2 and 3.2.2 installed, this
behaviour no longer works. The .py file is apparently not recognized by
Vista as a valid drop target; it does not highlight, and when I release the
mouse, the dragged file is simply moved to / reordered within the
containing folder.

I was able to find a registry hack that is supposed to re-enable this
behaviour:

http://mindlesstechnology.wordpress.com/2008/03/29/make-python-scripts-droppable-in-windows/

However, I tried this and it had no effect whatsoever.

Is there any way I can get the drag-and-drop behaviour back? Was it
deliberately disabled for some reason? It was exceptionally convenient for
several of my scripts, and now I have to make .bat wrappers for each one to
get the same convenience.

Aside: when I double-click a .py file, what determines which Python will
run it? Is it a matter of which appears first in the PATH, or do I have to
set something else in the registry? Will a shebang line override the
default on Windows? If so, how do I write a shebang line for a Windows path
- just "#!C:/Windows/Python32"?

-- 
~Zahlman {:>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is this foolish?

2012-04-12 Thread Karl Knechtel
On Thu, Apr 12, 2012 at 7:15 AM, Tim Golden  wrote:

> On 12/04/2012 10:35, Cameron Simpson wrote:
> > I've found myself using a Python gotcha as a feature.
>
> Have a look at Peter Inglesby's lightning talk from a
> recent London Python Dojo:
>
>  http://inglesp.github.com/2012/03/24/mutable-default-arguments.html
>
>
That's interesting, but you can get the same effect with a function
attribute, if you really don't want to write a class... that way also
protects you against accidentally passing something in to override the
default. (Incidentally: I feel that the "lambda x = x: ..." idiom to avoid
multiple closures sharing state is an ugly hack, for the same reason.)


-- 
~Zahlman {:>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File traversing

2012-04-16 Thread Karl Knechtel
On Sun, Apr 15, 2012 at 5:51 AM, Chris Angelico  wrote:

>
> (You may also want to consider using the 'with' statement to guarantee
> a timely closing of the file. Outside the scope of this mail though.)
>
> I think this list is just to collect unique entries, yes? If so, a set
> may be more to your liking. Check out:
> http://docs.python.org/py3k/library/stdtypes.html#set
>
>  


In cases like this I like to just show the final code after making all the
changes, and let the student ask questions :)

with open('/bah') as res_own_file:
all_res = set(line.strip().replace(' ', '').split(':')[1] for line in
res_own_file if ':' in line)

-- 
~Zahlman {:>
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: Python one-liner?

2012-04-16 Thread Karl Knechtel
On Sat, Apr 14, 2012 at 7:26 AM, Tim Chase
 wrote:
>
> On 04/13/12 22:54, Chris Angelico wrote:
>>
>> Yes, that would be the right method to use. I'd not bother with the
>> function and map() though, and simply iterate:
>>
>> d = {}
>> for val in l:
>>  d.setdefault(f(val), []).append(val)
>
>
> Or make d a defaultdict:
>
>  from collections import defaultdict
>  d = defaultdict(list)
>  for val in l:
>    d[f(val)].append(val)


For those insisting on getting something functional-ish:

d = {k: list(v) for k, v in itertools.groupby(sorted(l, key=f), f)}

(and one of these days I will send to the list instead of directly
replying, the first time...)

--
~Zahlman {:>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can I overload operators like "=>", "->" or something like that?

2012-04-19 Thread Karl Knechtel
On Thu, Apr 19, 2012 at 3:28 PM, dmitrey  wrote:
> hi all,
> can I somehow overload operators like "=>", "->" or something like
> that? (I'm searching for appropriate overload for logical implication
> "if a then b")
> Thank you in advance, D.
> --
> http://mail.python.org/mailman/listinfo/python-list


There is no "logical implication" operator in Python, and indeed
Python doesn't really work that way; you can use a condition to
trigger an action, and you can have a conditionally-valued expression,
but you don't tell Python a bunch of facts and then expect it to
reason from those - that's Prolog.

You cannot invent your own operators for Python, either. Again, this
isn't something that programming languages commonly support.

Could you please tell us more about what you're **really** trying to do?

-- 
~Zahlman {:>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can I overload operators like "=>", "->" or something like that?

2012-04-19 Thread Karl Knechtel
On Fri, Apr 20, 2012 at 12:43 AM, Chris Angelico  wrote:
> On Fri, Apr 20, 2012 at 2:38 PM, alex23  wrote:
>> On Apr 20, 5:54 am, Jacob MacDonald  wrote:
>>
>>> On Thursday, April 19, 2012 12:28:50 PM UTC-7, dmitrey wrote:
>>> > can I somehow overload operators like "=>", "->" or something like
>>> > that?
>>
>>> I don't believe that you could overload those particular operators,
>>> since to my knowledge they do not exist in Python to begin with.
>>
>> It all depends on if the operators use special methods on objects:
>> http://docs.python.org/reference/datamodel.html#special-method-names
>>
>> You can overload => via object.__le__, for example.
>
> Yes, but it will be a comparison operator, and to an extent, will be
> assumed to function as one. I don't recommend abusing comparisons for
> other operations - you'll confuse people no end.
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list

Actually, the >= operator can't be spelled => anyway:

>>> 3=>4
  File "", line 1
3=>4
  ^
SyntaxError: invalid syntax

-- 
~Zahlman {:>
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: Newbie naive question ... int() throws ValueError

2012-05-12 Thread Karl Knechtel
I really wish gmail picked up the mailing list as a default reply-to address...


-- Forwarded message --
From: Karl Knechtel 
Date: Sat, May 12, 2012 at 8:25 AM
Subject: Re: Newbie naive question ... int() throws ValueError
To: Devin Jeanpierre 


On Sat, May 12, 2012 at 12:11 AM, Devin Jeanpierre
 wrote:
> I'm not talking about unexpected exceptions. I'm saying, if I expect
> invalid input for int, where should I go to find out how to deal with
> said invalid input properly? How do I know that int raises ValueError
> on failure, and not, for example, something like ArgumentError
> (something that Python doesn't have) or (like chr) TypeError?
>
> Apparently the answer is to read the documentation for ValueError.

The easiest way is to try it. In fact, in most cases, this will be
easier than looking it up in the documentation could ever be, because
looking something up in documentation requires you to read through a
bunch of documentation until you find key info like 'raises FooError
in bar circumstance', and then interpret it; by trial and error, you
see exactly what happens right away, and you can do it by just banging
out a couple of lines on the REPL.

You should have already read the documentation for things like
ValueError as a part of learning the language (i.e. the first time
something raised a ValueError and you wanted to know what that meant);
or at the very least you should have a good idea of what the
"standard" exceptions are all named, and *develop an intuition* for
which apply to what circumstances. As noted by others, you should not
expect `int` to throw a `TypeError` when fed a bad string, because a
`TypeError` means "something is wrong with the type of some object",
and the problem with the bad string isn't that it's a string (its
type), but that the string contents are not interpretable as int (its
value, hence ValueError).

--
~Zahlman {:>


-- 
~Zahlman {:>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good data structure for finding date intervals including a given date

2012-05-12 Thread Karl Knechtel
On Sat, May 12, 2012 at 8:17 AM, Jean-Daniel
 wrote:
> I am looking for a fast way to find the intervals
> containing a given date, without having to check all intervals (less
> than O(n)).

Since you say "intervals" in plural here, I assume that they can overlap?

-- 
~Zahlman {:>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dealing with the __str__ method in classes with lots of attributes

2012-05-12 Thread Karl Knechtel
On Thu, May 10, 2012 at 9:33 AM, Andreas Tawn  wrote:
> And there's also something like...
>
> return "\n".join((": ".join((str(k), str(self.__dict__[k]))) for k in 
> self.__dict__))
>
> which is a nice length, but I lose control of the order of the attributes and 
> the formatting is fixed. It also looks a bit too much like Lisp ;o)
>
> Is there a better way?

If you don't care about being able to change the attributes
dynamically, define the `__slots__` of your class, and then you can
use

return '\n'.join('%s: %s' % (name, getattr(self, name)) for name in
self.__slots__)

Calling `getattr` is probably more Pythonic than looking things up in
`__dict__`, string formatting can take care of "casting" (converting,
really) for you, and the nested `join` is really overkill :) Anyway
the main point is that `__slots__` is a list, and thus has a defined
order.

>
> p.s. I may want to substitute __repr__ for __str__ perhaps?

Depending. Sometimes you want them to behave the same way. Since
functions are objects, this is as simple as `__repr__ = __str__`. :)

p.s. Is Python seeing a lot of use at Ubisoft or is this just for
personal interest (or perhaps both)?

-- 
~Zahlman {:>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dealing with the __str__ method in classes with lots of attributes

2012-05-14 Thread Karl Knechtel
On Sat, May 12, 2012 at 9:10 AM, Ethan Furman  wrote:
>
> Firstly, __slots__ is a tuple.

I object: conceptually, the "slots" of a class are set in stone, but
the `__slots__` attribute of a class object is just an attribute, and
any iterable (as long as it yields valid identifier names) can be used
when the `__slots__` magic is invoked in the class definition. FWIW,
all the ordinary examples I've seen use a list, although a tuple
arguably makes more sense.

Observe:

>>> class Evil(object):
...   __slots__ = ('a%s' % a for a in range(10))
...
>>> Evil().__slots__
 at 0x01EDFAA8>
>>> list(Evil().__slots__)
[] # the generator was consumed by the metaclass during class creation
>>> dir(Evil())
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__has
h__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__rep
r__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '
a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9'] # yep, the
expected attributes are there, and can be set.
>>> Evil.__slots__ = 42
# no exception

>
> Secondly, this is bad advice.  __slots__ is there as a memory optimization
> for classes that will have thousands of instances and do not need the
> ability to have arbitrary attributes added after creation.

I did explicitly indicate the latter part.

>  __slots__ is an
> advanced feature, and as such is easier to get wrong.  It is *not* there to
> make __str__ nor __repr__ easier to write.

Of course not, but it seems to me that it serves well in this particular case.

 class Test1(object):
> ...     __slots__ = ('item', 'size')
> ...     desc = 'class-only attribute'
> ...
>
 t1 = Test1()
 t1.desc = 'read-only attribute'      # fails because 'desc' is
>                                         # not in __slots__

Well, sure; expecting to modify a class attribute via an instance is a
bit naughty anyway.

 print t1.item                        # fails because 'item' was
>                                         # not set

Well, yes, that's what `__init__` is for; the same line would fail
without `__slots__` and for the same reason. Arguably, this is a
gotcha for people coming from C-like languages who are expecting
`__slots__` to make the class behave as if it had a defined layout,
but there isn't actually any more work involved here.

 class Test2(Test1):
> ...     def __init__(self, price):
> ...         self.price = price
> ...
 t2 = Test2(7.99)          # __slots__ not defined in
>                              # subclass, optimizations lost

Well, yes, but we aren't using it for the optimizations here!

But I see your point; explicit is better than implicit, and our
explicit purpose here is to have an explicit list of the attributes
we're interested in for __str__/__repr__ - which could be any other
named class attribute, without magic associated with it. That said,
`__slots__` is as close to a canonical listing of instance-specific
attributes as we have (`dir()` clearly won't cut it, as we don't want
methods or other class-specific stuff).

--
~Zahlman {:>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good data structure for finding date intervals including a given date

2012-05-14 Thread Karl Knechtel
On Sat, May 12, 2012 at 10:18 AM, Jean-Daniel
 wrote:
>> Since you say "intervals" in plural here, I assume that they can overlap?
>
> Yes,
>
> For instance, there are the following intervals :
> [[1, 10],
> [4, 7],
> [6, 15],
> [11, 17]]
>
> asking for the intervals including  5, the returned value should be
>
> [[1, 10],
> [4, 7]]
>
> The idea here to make it fast is to have done some preprocessing at
> insertion time, so that not all intervals are processed at query time.
>

How about this:

Set up a list of lists of intervals. Insert the intervals one at a
time thus: for each existing list, check if the new interval overlaps
any existing intervals - you can use the `bisect` module to check for
where the new interval would "fit". If there is no overlap, insert it
into that list at the discovered "insertion point"; otherwise move on
to the next list. If no lists are found that can hold the new
interval, append a new list for it.

Then at query time, you just iterate over the lists, using `bisect`
again to find the unique interval (if any) in each list that spans the
specified point in time.

-- 
~Zahlman {:>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dynamically selecting a class to instantiate based on the object attributes.

2012-05-14 Thread Karl Knechtel
On Wed, May 9, 2012 at 7:02 AM, J. Mwebaze  wrote:
>
> During object instantiaton, i would like to use  the specific class, that
> corresponds to the version of the class that was used to create the object.

I don't understand; "the version of the class that was used to create"
**what** object? We're still in the middle of object instantiation!
Where is the version information coming from?

Are you perhaps trying to do something with (un)serialization? Could
you show any relevant code at all?

-- 
~Zahlman {:>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print XML

2012-05-19 Thread Karl Knechtel
What do you want the contents of the file to look like? Why are you
parsing the XML in the first place? (What do you want to happen if the
data on `sys.stdin` isn't actually valid XML?)

On Thu, May 17, 2012 at 9:52 AM, Nibin V M  wrote:
> Hello,
>
> I have the following code, which will assign  XML data to a variable! What
> is the best method to write the contents of the variable to a file?
>
> ===
> doc = minidom.parse(sys.stdin)
> ===
>
> Any help will be highly appreciated!
>
> Thank you,
> --
> Regards
>
> Nibin.
>
> http://TechsWare.in
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
~Zahlman {:>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: append method

2012-05-23 Thread Karl Knechtel
On Wed, May 23, 2012 at 8:23 AM, 水静流深 <[email protected]> wrote:
 s=[1,2,3]
 s.append(5)
 s
> [1, 2, 3, 5]
 s=s.append(5)
 s
 print s
> None
>
> why can't  s=s.append(5)  ,what is the reason?

For the same reason that you don't see `[1, 2, 3, 5]` immediately
after doing `s.append(5)` the first time around, but must instead
check `s`: because the value is not returned from the function. `s` is
modified in-place, and nothing is returned.

This was a deliberate design decision made a long time ago that is
very well documented; try Googling for `python why doesn't list.append
return the value` for example.


-- 
~Zahlman {:>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda closure question

2005-02-22 Thread Karl Anderson
"Ted Lilley" <[EMAIL PROTECTED]> writes:

> What I want to do is pre-load functions with arguments by iterating
> through a list like so:
> 
> >>>class myclass:
> ...pass
> >>>def func(self, arg):
> ...print arg
> >>>mylist = ["my", "sample", "list"]
> >>>for item in mylist:
> ...setattr(myclass, item, lamdba self: func(self, item))

I just found myself doing something similar to deal with unittest.py's
test loaders/runners, which have to be able to find attributes on a
class before the class is instantiated.

def addItemStateTransTest(klass):
"""
For each item generator and transition test, add a method to klass
to test that combo.
"""
for ig_name in klass.item_generators:
   for tt_name in klass.transition_tests.keys():
   test_name = "test" + ig_name + tt_name
   test_fun = (lambda self,
   ig_name=ig_name, tt_name=tt_name:
   self.doTestItemStateTrans(ig_name, tt_name))
   setattr(klass, test_name, test_fun)

-- 
Karl Anderson  [EMAIL PROTECTED]   http://monkey.org/~kra/
-- 
http://mail.python.org/mailman/listinfo/python-list


__delitem__ affecting performance

2006-10-19 Thread Karl H.
Hi,

I was performing some timing tests on a class that inherits from the 
built-in list, and got some curious results:

import timeit

class MyList(list):
 def __init__(self):
 list.__init__(self)
 self[:] = [0,0,0]

 def __delitem__(self,index):
 print 'deleting'

ml = MyList()

def test():
 global ml
 ml[0] += 0
 ml[1] += 0
 ml[2] += 0

t = timeit.Timer("test()","from __main__ import test")
print t.timeit()

 >> 4.11651382676

import timeit

class MyList(list):
 def __init__(self):
 list.__init__(self)
 self[:] = [0,0,0]

ml = MyList()

def test():
 global ml
 ml[0] += 0
 ml[1] += 0
 ml[2] += 0

t = timeit.Timer("test()","from __main__ import test")
print t.timeit()

 >> 2.23268591383

Does anybody know why defining __delitem__ is causing the code to run 
slower? It is not being called, so I don't see why it would affect 
performance. Overriding other sequence operators like __delslice__ does 
not exhibit this behavior.

The speed difference doesn't really bother me, but I am curious.

I used Python 2.4 for this test.

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


Backup Mailman?

2006-10-30 Thread Karl Groves
Does anyone out there know of a utility that will allow you to backup 
Mailman (including the subscribers and all messages)?

TIA

-- 
Karl Groves
www.karlcore.com
-- 
http://mail.python.org/mailman/listinfo/python-list


What are python closures realy like?

2006-12-01 Thread Karl Kofnarson
Hi,
while writing my last program I came upon the problem
of accessing a common local variable by a bunch of 
functions.
I wanted to have a function which would, depending on
some argument, return other functions all having access to
the same variable. An OO approach would do but why not
try out closures...
So here is a simplified example of the idea:
def fun_basket(f):
common_var = [0]
def f1():
print common_var[0]
common_var[0]=1
def f2():
print common_var[0]
common_var[0]=2
if f == 1:
return f1
if f == 2:
return f2
If you call f1 and f2 from the inside of fun_basket, they
behave as expected, so common_var[0] is modified by
whatever function operates on it.
However, calling f1=fun_basket(1); f2 = fun_basket(2) and
then f1(); f2() returns 0 and 0. It is not the way one would
expect closures to work, knowing e.g. Lisp make-counter.
Any ideas what's going on behind the scene?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What are python closures realy like?

2006-12-02 Thread Karl Kofnarson
> Karl,
> 
> Usually when using this idiom, fun_basket would return a tuple of all of the 
> defined functions, rather than one vs. the other.  So in place of:
>>if f == 1:
>>return f1
>>if f == 2:
>>return f2
> Just do
>>return f1, f2
> (For that matter, the argument f is no longer needed either.)
> 
> Then your caller will get 2 functions, who share a common var.  You don't 
> call fun_basket any more, you've already created your two "closures".  Call 
> fun_basket using something like:
> 
> z1,z2 = fun_basket(None)
> 
> And then call z1() and z2() at your leisure - they should have the desired 
> behavior.
> 
> -- Paul

Thanks a lot Paul and for the other answers. The things are now
clear to me. In fact, in the Lisp example that I mentioned, you
get a list (or let it be association list) of the internal
functions. Then you can call them separately and they work as
you expect but it's due to the fact only that you got them created
at the same time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyThreadState_SetAsyncExc (nThreadId ??????, exc);

2006-12-14 Thread Karl H.
iwl wrote:
> what is the nThreadId-Parameter of PyThreadState_SetAsyncExc?
> 
> I try to implement a Terminate-Button in my C-Prog for my
> embedded Python, but its hard to find an example how to
> stop an interpreter running in an thread.
> 
> I found no other Python C-App-Func returning such a parameter.
> 

Use the "thread_id" member of the PyThreadState object:

PyThreadState *tstate;

PyThreadState_SetAsyncExc(tstate->thread_id,exc);

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


2D vector graphics Problem

2005-05-29 Thread Karl Max
Hi all,

I'm new here. Name's Max from tuscany, and I don't speak english very well 
:-) I am not veteran at coding, I am most like an "artisan coder" since 
commodore 64 times.

Now the problem:
I would like to have a little 2d engine to calculate and trace segments and 
poly's and their collisions, rotations and trasformations. I didn't 
understand too much in tutorials (you're all high school coders, well 
informed in maths and programming theory!!! :-))) so I took my old school 
books on Cartesian space and had a refresh. Proceeding in this not too 
optimized way of coding my needs, I took down some generic classes to 
describe primitive objects in space (vertexes, segments, poly's etc...).

Now I try to make a point rotate around another point.
Here's my piece of code:

def rotate(self, w):
 # This method belongs to the class Vertex
 # w = angle expressed in radiants
 x, y = self.coords
 xRel, yRel = self.relPoint # The rotation should be relative to this
 sin, cos = math.sin(w), math.cos(w)
 x = x * cos - y * sin - xRel * cos + yRel * sin + xRel
 y = x * sin + y * cos - xRel * sin - yRel * cos + yRel
 self.coords = (x,y)

I know the style isn't professional, and if you should have some piece of 
advice, you're welcome... but that's not the question.
When I render it graphically, using pygame 1.6, the point tends to fall 
towards the center of rotation round after round. I mean if I have a loop 
rotating the point by a fixed angle, the point is like "attracted" by the 
center every round it does, like in a vortex.
I think it depends from float representation inside python, but I have no 
clear idea about how to resolve it. Maybe should I use Decimal module? Or is 
there any trick on this subject (2D vector graphics?) that I can't even 
imagine?
Thanks you all,
 Max 


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


Re: 2D vector graphics Problem

2005-05-29 Thread Karl Max

"Scott David Daniels" <[EMAIL PROTECTED]> ha scritto nel messaggio 
news:[EMAIL PROTECTED]
>>  x = x * cos - y * sin - xRel * cos + yRel * sin + xRel
>>  y = x * sin + y * cos - xRel * sin - yRel * cos + yRel
>>  self.coords = (x,y)
>
> Your equation for y uses the new x, not the old x.

De hi hi ho. I must sleep some more hours at night... ;-)
>Be more free with names.

Well, I often report book formulas, and forget renaming variables to more 
comprehensive language. Thank you for your help.

Max 


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


socket.getaddrinfo: flags |= AI_ADDRCONFIG

2008-11-05 Thread Karl Chen

I've discovered that since glibc 2.3.2, getaddrinfo(3) supports a
useful flag called AI_ADDRCONFIG.  It turns off  lookups if
the machine isn't configured for IPv6 (and similarly for IPv4,
theoretically).  This is especially important when behind gateways
whose DNS forwarder silently filter  requests.  Without
AI_ADDRCONFIG, every DNS request has to wait for 4  request
timeouts before it even attempts an A request.

Passing hints=NULL to getaddrinfo (the C function) means
hints->flags = AI_V4MAPPED | AI_ADDRCONFIG.  I.e., not the same as
hints->hints->flags = 0.  (Don't ask me why the default isn't 0, I
don't like this API either.  It means if you wish to specify only
some hint parameters you have to carefully get the flags right.)

Python's socketmodule.c, especially socket_getaddrinfo, uses 0 as
the default flags.  So AI_ADDRCONFIG is turned off by default.

I propose:
1) mimic glibc default behavior, i.e. if flags is unspecified or
   None, treat it as the default value of AI_V4MAPPED |
   AI_ADDRCONFIG).

Alternatively:
2) add these flags to callers of socket.getaddrinfo in various
   standard libs, e.g. httplib.


(AI_V4MAPPED isn't as important since it only applies if you
explicitly choose AF_INET6, a conscious decision.)

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


RE: ka-ping yee tokenizer.py

2008-09-16 Thread Karl Kobata
Hi Fredrik,

This is exactly what I need.  Thank you.
I would like to do one additional function.  I am not using the tokenizer to
parse python code.  It happens to work very well for my application.
However, I would like either or both of the following variance:
1) I would like to add 2 other characters as comment designation
2) write a module that can readline, modify the line as required, and
finally, this module can be used as the argument for the tokenizer.

Def modifyLine( fileHandle ):
  # readline and modify this string if required
...

For token in tokenize.generate_tokens( modifyLine( myFileHandle ) ):
Print token

Anxiously looking forward to your thoughts.
karl

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
Fredrik Lundh
Sent: Monday, September 15, 2008 2:04 PM
To: [email protected]
Subject: Re: ka-ping yee tokenizer.py

Karl Kobata wrote:

> I have enjoyed using ka-ping yee's tokenizer.py.  I would like to 
> replace the readline parameter input with my own and pass a list of 
> strings to the tokenizer.  I understand it must be a callable object and 
> iteratable but it is obvious with errors I am getting, that this is not 
> the only functions required.

not sure I can decipher your detailed requirements, but to use Python's 
standard "tokenize" module (written by ping) on a list, you can simple 
do as follows:

 import tokenize

 program = [ ... program given as list ... ]

 for token in tokenize.generate_tokens(iter(program).next):
 print token

another approach is to turn the list back into a string, and wrap that 
in a StringIO object:

 import tokenize
 import StringIO

 program = [ ... program given as list ... ]

 program_buffer = StringIO.StringIO("".join(program))

 for token in tokenize.generate_tokens(program_buffer.readline):
 print token



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

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


Re: ka-ping yee tokenizer.py

2008-09-17 Thread Karl Kobata
Aaran,
 
Thanks for your input.  Your examples gave me other alternatives for what I
wanted to do and it seems to work.
 
Thanks all for your help.
 
 
On Sep 16, 2:48 pm, "Karl Kobata" http://mail.python.org/mailman/listinfo/python-list> > wrote:
> Hi Fredrik,
> 
> This is exactly what I need.  Thank you.
> I would like to do one additional function.  I am not using the tokenizer
to
> parse python code.  It happens to work very well for my application.
> However, I would like either or both of the following variance:
> 1) I would like to add 2 other characters as comment designation
> 2) write a module that can readline, modify the line as required, and
> finally, this module can be used as the argument for the tokenizer.
> 
> Def modifyLine( fileHandle ):
>   # readline and modify this string if required
> ...
> 
> For token in tokenize.generate_tokens( modifyLine( myFileHandle ) ):
> Print token
> 
> Anxiously looking forward to your thoughts.
> karl
> 
> -Original Message-
> From: python-list-bounces+kkobata=syncira at python.org
<http://mail.python.org/mailman/listinfo/python-list> 
> 
> [mailto:python-list-bounces+kkobata=syncira at python.org
<http://mail.python.org/mailman/listinfo/python-list> ] On Behalf Of
> Fredrik Lundh
> Sent: Monday, September 15, 2008 2:04 PM
> To: python-l... at python.org
<http://mail.python.org/mailman/listinfo/python-list> 
> Subject: Re: ka-ping yee tokenizer.py
> 
> Karl Kobata wrote:
> 
> > I have enjoyed using ka-ping yee's tokenizer.py.  I would like to
> > replace the readline parameter input with my own and pass a list of
> > strings to the tokenizer.  I understand it must be a callable object and
> > iteratable but it is obvious with errors I am getting, that this is not
> > the only functions required.
> 
> not sure I can decipher your detailed requirements, but to use Python's
> standard "tokenize" module (written by ping) on a list, you can simple
> do as follows:
> 
>  import tokenize
> 
>  program = [ ... program given as list ... ]
> 
>  for token in tokenize.generate_tokens(iter(program).next):
>  print token
> 
> another approach is to turn the list back into a string, and wrap that
> in a StringIO object:
> 
>  import tokenize
>  import StringIO
> 
>  program = [ ... program given as list ... ]
> 
>  program_buffer = StringIO.StringIO("".join(program))
> 
>  for token in tokenize.generate_tokens(program_buffer.readline):
>  print token
> 
> 
> 
> --http://mail.python.org/mailman/listinfo/python-list
> 
> 
 
This is an interesting construction:
 
>>> a= [ 'a', 'b', 'c' ]
>>> def moditer( mod, nextfun ):
... while 1:
... yield mod( nextfun( ) )
...
>>> list( moditer( ord, iter( a ).next ) )
[97, 98, 99]
 
Here's my point:
 
>>> a= [ 'print a', 'print b', 'print c' ]
>>> tokenize.generate_tokens( iter( a ).next )

>>> tokenize.generate_tokens( moditer( lambda s: s+ '#', iter( a ).next
).next )
 
It adds a '#' to the end of every line, then tokenizes.

 

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

member functions in a class

2008-09-17 Thread Karl Kobata
I am new to python and am wondering.  When I create a class, with 'def'
functions and if this class is instantiated say 50 times.  Does this mean
that all the 'def' functions code within the class is duplicated for each
instance?

Can someone give me a short and simple answer as to what happens in python?

 

Thanks

 

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

fwd: member functions in a class

2008-09-18 Thread Karl Kobata
Gary,

 

No the answer is not too short, thank you for your reply, I am learning
rapidly.

 

Terry,

 

The expanded answer is also useful.  Now I am getting a better insight on
how python resolves object attributes.

This also gives me more insight on the difference between import 
vs from  from *.

 

Thanks

karl

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

deleting an object

2008-09-25 Thread Karl Kobata
Please help.  Questions based on snippet of code below.

1)   when myTestCase is deleted, is just the pointer deleted or the
entire instance with all of its data and data structure deleted?

2)   What is the practice for deleted the object and recovering the
memory it occupies?

3)   If delete is the way, what happens to 'testUtils.utilFunction1()'
if it were instantiated in other classes that have not been deleted yet?

 

Thanks for your help.

 

 

 

Example:

import testUtils

 

class testClass:

def __init__(self):

self.testList = list()

self.testDict1 = dict()

self.utils1 = testUtils.utilFunction1()

...





...in the main code body.

myTestCase = testClass()



delete myTestCase

...

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

installation in mac os x

2009-06-10 Thread Karl Jansson

Hi,

I was doing the tutorial at http://www.python.org/doc/current/ 
tutorial/, and I came across some code that did not work,  and I got  
the following error:  	AttributeError: 'str' object has no attribute  
'format'.


So I downloaded a .dmg of python 2.6.2 and then I installed it.  But  
it's not working.  Running the Python launcher, the "new" command in  
the file menu is grey, and won't work, so I can't make any scripts.


Does anyone know how to make python 2.6.2 work in mac os x?

Thanks,
Stefan



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


timeit and __future__

2009-06-19 Thread Karl Chen

I wanted to time something that uses with_statement, in python2.5.
Importing __future__ in the statement or the setup doesn't work
since it's not the beginning of the code being compiled.  Other
than using a separate module, I could only come up with this:

timeit.template = 'from __future__ import with_statement\n' + 
timeit.template

timeit should directly support importing __future__ stuff...

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


Re: installation in mac os x

2009-06-24 Thread Karl Jansson


What happens if you work on the commandline (Terminal)?

Python2.6 should be available from (out of my head)

/Library/Frameworks/Python.framework/Versions/2.6/bin/python

If that's working, it is successfully installed.

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


If I work on the commandline, I have version 2.3, which works. But  
some of the commands in the tutorial don't work with that version, so  
I had to upgrade in order to do the tutorial.  But I still can't do  
it, obviously.


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


Re: Regular Expressions - Python vs Perl

2005-04-21 Thread Karl A. Krueger
Terry Reedy <[EMAIL PROTECTED]> wrote:
> Depending upon you particular application, 'completeness' may be a
> more relevant concern than 'performance'.  I believe the original
> Python regex engine did not have all the Perl extensions, some of them
> decidedly 'non regular'.  It was replace by the 'perl-compatible regex
> engine' (pcre or pre), written in C by a non-pythonista so that other
> languages/applications, like Python, could drop it in and have what
> the title claimed -- perl-like re capability.

By way of comparison, there do exist at least some Perl-compatible regex
libraries in other non-Perl languages, which don't use libpcre.

An example is CL-PPCRE (http://www.weitz.de/cl-ppcre/), which claims to
be "more compatible with the regex semantics of Perl 5.8.0 than, say,
Perl 5.6.1 is."

-- 
Karl A. Krueger <[EMAIL PROTECTED]> { s/example/whoi/ }
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling GPL code from a Python application

2006-01-03 Thread Karl A. Krueger
Mike Meyer <[EMAIL PROTECTED]> wrote:
> 1) Executing software involves several copy operations. Each of those
>   potentially violate the copyright, and hence the copyright holder
>   can restrict execution of a program.

#include 

In the U.S. at least, there's a specific statute *exempting* the running
of software (and the making of backups) from copyright protection.  That
is, copyright does *not* grant the holder the right to restrain users
from executing a copy of software that they have legally obtained.

http://www.copyright.gov/title17/92chap1.html#117

-- 
Karl A. Krueger <[EMAIL PROTECTED]> { s/example/whoi/ }
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling GPL code from a Python application

2006-01-04 Thread Karl A. Krueger
Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> As far as I know, US copyright law does not give an exemption for
> temporary copies in working memory (although I could be wrong about that).
> Here in Australia, our government (for once getting it right!)
> *explicitly* gives such an exemption to our copyright law.

Actually, the U.S. does as well:

http://www.copyright.gov/title17/92chap1.html#117


> (We also have the explicit right to make backup copies of legal software,
> although Australian copyright law is firm that this is for backup ONLY,
> and not a "backup *nudge nudge wink wink*".

An analogous provision exists in U.S. law, indeed in the same chapter
cited above.  It also covers copies made in the course of repairing a
computer.

-- 
Karl A. Krueger <[EMAIL PROTECTED]> { s/example/whoi/ }
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Software licenses and releasing Python programs for review

2005-06-02 Thread Karl A. Krueger
Andreas Kostyrka <[EMAIL PROTECTED]> wrote:
> *) GPL is not acceptable for "library" stuff, because as a software
>   developer I'm sometimes forced to do "closed" stuff.
>   (Yep, even nowadays there are place where it's basically a legal
>requirement.)

I'm curious about this last one.

The GPL does not require that derivative works be published, or that
they be donated back to the original author.  All it requires is that
you pass on the rights that you received to the recipient of your
derivative work -- in this case, your customer alone.

Of course, if your customer is a proprietary software firm looking to
own and sell the software restrictively, then they don't want those
terms.  But if they're just looking to use it privately and internally,
I'm curious how the GPL would get in the way of that.

-- 
Karl A. Krueger <[EMAIL PROTECTED]> { s/example/whoi/ }
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing HTML

2007-02-11 Thread Samuel Karl Peterson
"mtuller" <[EMAIL PROTECTED]> on 10 Feb 2007 15:03:36 -0800 didst
step forth and proclaim thus:

> Alright. I have tried everything I can find, but am not getting
> anywhere. I have a web page that has data like this:

[snip]

> What is show is only a small section.
> 
> I want to extract the 33,699 (which is dynamic) and set the value to a
> variable so that I can insert it into a database.

[snip]

> I have also tried Beautiful Soup, but had trouble understanding the
> documentation.


from BeautifulSoup import BeautifulSoup as parser

soup = parser("""

LETTER

33,699

1.0

""")

value = \
   int(soup.find('td', headers='col2_1').span.contents[0].replace(',', ''))


> Thanks,

> Mike

Hope that helped.  This code assumes there aren't any td tags with
header=col2_1 that come before the value you are trying to extract.
There's several ways to do things in BeautifulSoup.  You should play
around with BeautifulSoup in the interactive prompt.  It's simply
awesome if you don't need speed on your side.

-- 
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find all the same words in a text?

2007-02-11 Thread Samuel Karl Peterson
"Johny" <[EMAIL PROTECTED]> on 10 Feb 2007 05:29:23 -0800 didst step
forth and proclaim thus:

> I need to find all the same words in a text .
> What would be the best idea  to do that?

I make no claims of this being the best approach:


def findOccurances(a_string, word):
"""
Given a string and a word, returns a double:
[0] = count [1] = list of indexes where word occurs
"""
import re
count = 0
indexes = []
start = 0 # offset for successive passes
pattern = re.compile(r'\b%s\b' % word, re.I)

while True:
match = pattern.search(a_string)
if not match: break
count += 1;
indexes.append(match.start() + start)
start += match.end()
a_string = a_string[match.end():]

return (count, indexes)


Seems to work for me.  No guarantees.

-- 
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find all the same words in a text?

2007-02-11 Thread Samuel Karl Peterson
[EMAIL PROTECTED] on 11 Feb 2007 08:16:11 -0800 didst step
forth and proclaim thus:

> More concisely:
> 
> import re
> 
> pattern = re.compile(r'\b324\b')
> indices = [ match.start() for match in
> pattern.finditer(target_string) ]
> print "Indices", indices
> print "Count: ", len(indices)
> 

Thank you, this is educational.  I didn't realize that finditer
returned match objects instead of tuples.

> Cheers,
> Steven
> 

-- 
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No module named pyExcelerator Error

2007-02-11 Thread Samuel Karl Peterson
"susan" <[EMAIL PROTECTED]> on 11 Feb 2007 16:55:35 -0800 didst
step forth and proclaim thus:

> Hi,
> I'm new of Python, and this problem stucked me whole day but can't be
> solved.

[snip]

> anybody can tell me where's wrong please? Thanks in advance!

What are the contents of sys.path from an interactive prompt?  Have
you tried the official windows Python?  Is there a reason you need to
use the cygwin Python?

-- 
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


string.replace non-ascii characters

2007-02-11 Thread Samuel Karl Peterson
Greetings Pythonistas.  I have recently discovered a strange anomoly
with string.replace.  It seemingly, randomly does not deal with
characters of ordinal value > 127.  I ran into this problem while
downloading auction web pages from ebay and trying to replace the
"\xa0" (dec 160, nbsp char in iso-8859-1) in the string I got from
urllib2.  Yet today, all is fine, no problems whatsoever.  Sadly, I
did not save the exact error message, but I believe it was a
ValueError thrown on string.replace and the message was something to
the effect "character value not within range(128).

Some googling seemed to indicate other people have reported similar
troubles:

http://mail.python.org/pipermail/python-list/2006-July/391617.html

Anyone have any enlightening advice for me?

-- 
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About getattr()

2007-02-11 Thread Samuel Karl Peterson
"Jm lists" <[EMAIL PROTECTED]> on Mon, 12 Feb 2007 12:36:10
+0800 didst step forth and proclaim thus:

> Hello,
> 
> Since I can write the statement like:
> 
> >>> print os.path.isdir.__doc__
> Test whether a path is a directory
> 
> Why do I still need the getattr() func as below?
> 
> >>> print getattr(os.path,"isdir").__doc__
> Test whether a path is a directory

getattr lets you lookup an attribute given a string, so the attribute
wouldn't have to be hardcoded in your program, it could come from a
file, or from user input.

-- 
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: searching a list of lists as a two-dimensional array?

2007-02-11 Thread Samuel Karl Peterson
James Stroud <[EMAIL PROTECTED]> on Sun, 11 Feb 2007 16:53:16 -0800
didst step forth and proclaim thus:

> agent-s wrote:
> > Basically I'm programming a board game and I have to use a list of
> > lists to represent the board (a list of 8 lists with 8 elements each).
> > I have to search the adjacent cells for existing pieces and I was
> > wondering how I would go about doing this efficiently. Thanks
> >
> 
> This isn't very clear. What do you mean by "I have to search the
> adjacent cells for existing pieces"?
> 
> If piece is 1 and empty is 0 and piece is at ary[row][col]:
> 
> import operator
> srch = [(i,j) for i in [-1,0,1] for j in [-1,0,1] if (i,j) != (0,0)]
> is_adj = reduce(operator.or_, [ary[row+i][col+j] for (i,j) in srch]])

Wow, maybe it's just me (I'm a pretty bad programmer) but this is
where list comprehensions begin to look unreadable to me.  Here's a
C-like way to do it, (warning, untested in python):

for i in range(8):
for j in range(8):
for offset_i in range(-1,2):
for offset_j in range(-1, 2):
row = i + offset_i
col = j + offset_j
if (row < 0 or row > 7) or (col < 0 or col > 8) \
   or ((row,col) == (i,j)):
continue
# else do something with board[row][col]

I realize this is gross and un-Pythonic and does the same thing the
above code does, but it's probably the way I'd choose to do it :).
Then again, I've been negatively influenced by doing a game of life in
C a few months back.

-- 
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string.replace non-ascii characters

2007-02-11 Thread Samuel Karl Peterson
Steven Bethard <[EMAIL PROTECTED]> on Sun, 11 Feb 2007 22:23:59
-0700 didst step forth and proclaim thus:

> Samuel Karl Peterson wrote:
> > Greetings Pythonistas.  I have recently discovered a strange anomoly
> > with string.replace.  It seemingly, randomly does not deal with
> > characters of ordinal value > 127.  I ran into this problem while
> > downloading auction web pages from ebay and trying to replace the
> > "\xa0" (dec 160, nbsp char in iso-8859-1) in the string I got from
> > urllib2.  Yet today, all is fine, no problems whatsoever.  Sadly, I
> > did not save the exact error message, but I believe it was a
> > ValueError thrown on string.replace and the message was something to
> > the effect "character value not within range(128).
> 
> Was it something like this?
> 
>  >>> u'\xa0'.replace('\xa0', '')
> Traceback (most recent call last):
>File "", line 1, in 
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position
> 0: ordinal not in range(128)

Yeah that looks like exactly what was happening, thank you.  I wonder
why I had a unicode string though.  I thought urllib2 always spat out
a plain string.  Oh well.

u'\xa0'.encode('latin-1').replace('\xa0', " ")

Horray.
-- 
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why I don't like range/xrange

2007-02-16 Thread Samuel Karl Peterson
Roel Schroeven <[EMAIL PROTECTED]> on Sat, 17 Feb 2007
01:31:13 GMT didst step forth and proclaim thus:

...
> So, the point is that in C you can influence the loop's behavior by
> modifying the loop variable, while you cannot do that in Python (at
> least not in a for-loop).

What's wrong with...

for i in range(10):
if condition: break

...?
-- 
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python setup.py install on Vista?

2008-04-18 Thread Karl-Heinz Ruskowski
hi
> well using windows vista, where the h*** am i supposed to type this?
you have to include the path to the python interpreter like this 
c:\programs\python\python.exe pythonfile.py 
(replace this with your path) 
or you set an alias called python - i don't know how to that under windows, 
especially visa :D 

good luck 

-- 
GPG key: 0x04B3BB96


pgpQLpoZyTTGB.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Another MySQL Images Question

2008-04-18 Thread Karl-Heinz Ruskowski
Hi, 

>   cursor.execute('update products set pic1="%s" where id="%s", ;',
> (pic1, id))

Shouldn't it be something like 
cursor.execute('update products set pic1="%s" where id="%s", ;' % (pic1, id))

-- 
GPG key: 0x04B3BB96


pgpiL4LACYHv7.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Issue with inspect module

2008-04-19 Thread Karl-Heinz Ruskowski
> Why does the inspect module cause the output
> to be printed twice?

I also tested it, no problem here either. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: manipulating class attributes from a decorator while the class is being defined

2008-04-19 Thread Karl-Heinz Ruskowski
> How can I reach the class attribute `regexps' from within a decorator?
Now, the first way that comes to my mind is simply overloading the class and 
set your regexps variable in your new class. 

The other way is to create an object and set it more manually (obj.regexps = 
['.*']). Which for me is an ugly this to do because the first way is far more 
elegant :) 

-- 
GPG key: 0x04B3BB96


pgpqg8hSnWlWX.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list