Re: PIL(Py Image lib), show() not showing picture...

2008-07-03 Thread ssecorp
On Jul 3, 10:20 pm, "Méta-MCI \(MVP\)"
<[EMAIL PROTECTED]> wrote:
> Hi!
>
> Which OS?   On Vista, you MUST reconfig the "aperçu images et
> télécopies" (in french ; sorry, I don't know the english translation).
>
> @-salutations
>
> Michel Claveau


VISTA.

i will try google translate :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: PIL(Py Image lib), show() not showing picture...

2008-07-03 Thread ssecorp
On Jul 3, 10:20 pm, "Méta-MCI \(MVP\)"
<[EMAIL PROTECTED]> wrote:
> Hi!
>
> Which OS?   On Vista, you MUST reconfig the "aperçu images et
> télécopies" (in french ; sorry, I don't know the english translation).
>
> @-salutations
>
> Michel Claveau




thumbnail images and faxes? and how do i do that? i must do it in
windows or in the python library?
--
http://mail.python.org/mailman/listinfo/python-list


how are strings immutable in python?

2008-07-06 Thread ssecorp
>>> h = "aja baja"
>>> h += 'e'
>>> h
'aja bajae'
>>>

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


Re: how are strings immutable in python?

2008-07-06 Thread ssecorp
so if strings were mutable and i did
a = b = "foo"
and then did
a += "bar"
then a and b would be foobar?
--
http://mail.python.org/mailman/listinfo/python-list


Very weird bug!

2008-07-06 Thread ssecorp
I was looking into currying and

Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.


Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface.  This connection is not visible on any external
interface and no data is sent to or received from the Internet.


IDLE 1.2.2
>>> h = "aja baja"
>>> h += 'e'
>>> h
'aja bajae'
>>> h = h+'a'
>>> h
'aja bajaea'
>>> a = b = "foo"
>>> a
'foo'
>>> b
'foo'
>>> a==b
True
>>> id(a)
35018400
>>> id(b)
35018400
>>> a += "bar"
>>> id(a),a
(35110112, 'foobar')
>>> id(b),b
(35018400, 'foo')
>>> fac

Traceback (most recent call last):
  File "", line 1, in 
fac
NameError: name 'fac' is not defined
>>> factorial

Traceback (most recent call last):
  File "", line 1, in 
factorial
NameError: name 'factorial' is not defined
>>> import math
>>> math

>>> math.factorial

Traceback (most recent call last):
  File "", line 1, in 
math.factorial
AttributeError: 'module' object has no attribute 'factorial'
>>> math.fac

Traceback (most recent call last):
  File "", line 1, in 
math.fac
AttributeError: 'module' object has no attribute 'fac'
>>> dir(math)
['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil',
'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod',
'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow',
'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
>>> pow

>>> tan

Traceback (most recent call last):
  File "", line 1, in 
tan
NameError: name 'tan' is not defined
>>> math.tan

>>> def build(a,b):
return a+b

>>> build(5,4)
(5, 4)
>>> def build(x,y):
a=x+y
return a

>>> build(5,4)
9
>>> def b(n, p):
return n + p

>>> b(1, 10)
11
>>> def b(n,p):
return n+p

>>> b(5,2)
7
>>> def build(x,y):
return a+b

>>> build(5,4)

Traceback (most recent call last):
  File "", line 1, in 
build(5,4)
  File "", line 2, in build
return a+b
TypeError: cannot concatenate 'str' and 'function' objects
>>> def build(x,y):
yreturn x+

SyntaxError: invalid syntax
>>> def build(x,y):
return x+y

>>> build(5,4)
9
>>> def build(a,b):
return a+b

>>> build(5,4)
9
>>>




wtf was this in the middle!?

>>> def build(a,b):
return a+b

>>> build(5,4)
(5, 4)
--
http://mail.python.org/mailman/listinfo/python-list


Re: how are strings immutable in python?

2008-07-06 Thread ssecorp
so why would you ever want mutability?


seems very counterintuitive and unreliable.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Very weird bug!

2008-07-07 Thread ssecorp
i know, idid try it again and it works as expected. but how the h***
did it not work that one time?
--
http://mail.python.org/mailman/listinfo/python-list


TypeError, I know why but not how!?

2008-07-09 Thread ssecorp
Im looking into PvsNP:
http://www.claymath.org/millennium/P_vs_NP/
so I thought I'd write the program just to get a feel for it.


But I run into a problem. Why does it all the sudden return None? I
mean I know why the program aborts but I dont understand why the None
is generated all the sudden. Hitting recursion depth isn't reported
with that error.
Guess I am missing something very obvious.

Traceback (most recent call last):
  File "C:\Python25\Progs\PNP\pnp.py", line 34, in 
gen(50)
  File "C:\Python25\Progs\PNP\pnp.py", line 32, in gen
return generateList([], [(1,10),(4,272),(34,442),(112,42)], [],
rooms)
  File "C:\Python25\Progs\PNP\pnp.py", line 27, in generateList
generateList(dormlist,incompatibles,placed,rooms)
  File "C:\Python25\Progs\PNP\pnp.py", line 27, in generateList
generateList(dormlist,incompatibles,placed,rooms)
  File "C:\Python25\Progs\PNP\pnp.py", line 27, in generateList
generateList(dormlist,incompatibles,placed,rooms)
  File "C:\Python25\Progs\PNP\pnp.py", line 27, in generateList
generateList(dormlist,incompatibles,placed,rooms)
  File "C:\Python25\Progs\PNP\pnp.py", line 27, in generateList
generateList(dormlist,incompatibles,placed,rooms)
  File "C:\Python25\Progs\PNP\pnp.py", line 25, in generateList
room, placed = pair(incompatibles, placed)
  File "C:\Python25\Progs\PNP\pnp.py", line 12, in pair
student1, placed = validate(placed)
TypeError: 'NoneType' object is not iterable
>>>

--
the program:



import random

def validate(placed):
student = round(random.random()*401)
if student in placed:
validate(placed)
else:
placed.append(student)
return student, placed

def pair(incompatibles, placed):
student1, placed = validate(placed)
student2, placed = validate(placed)
pair1 = (student1,student2)
pair2 = (student2,student1)
if (pair1 or pair2) in incompatibles:
placed.remove(student1)
placed.remove(student2)
pair(incompatibles, placed)
else:
return pair1, placed

def generateList(dormlist,incompatibles, placed, rooms):
if len(dormlist) < (rooms + 1):
room, placed = pair(incompatibles, placed)
dormlist.append(room)
generateList(dormlist,incompatibles,placed,rooms)
else:
return dormlist

def gen(rooms):
return generateList([], [(1,10),(4,272),(34,442),(112,42)], [],
rooms)

gen(50)


---
some tests inserted:


import random

def validate(placed):
student = round(random.random()*401)
if student in placed:
validate(placed)
else:
placed.append(student)
return student, placed

def pair(incompatibles, placed):
x = validate(placed)
print "x",x
y = validate(placed)
print "y",y
print "-"
student1, placed = x
student2, placed = y
#student1, placed = validate(placed)
#student2, placed = validate(placed)
pair1 = (student1,student2)
pair2 = (student2,student1)
if (pair1 or pair2) in incompatibles:
placed.remove(student1)
placed.remove(student2)
pair(incompatibles, placed)
else:
return pair1, placed

def generateList(dormlist,incompatibles, placed, rooms):
##print dormlist
##print placed
##print "---"
if len(dormlist) < (rooms + 1):
room, placed = pair(incompatibles, placed)
dormlist.append(room)
generateList(dormlist,incompatibles,placed,rooms)
else:
return dormlist

def gen(rooms):
return generateList([], [(1,10),(4,272),(34,442),(112,42)], [],
rooms)

gen(50)


x (283.0, [283.0])
y (8.0, [283.0, 8.0])
-
x (359.0, [283.0, 8.0, 359.0])
y (158.0, [283.0, 8.0, 359.0, 158.0])
-
x (249.0, [283.0, 8.0, 359.0, 158.0, 249.0])
y (371.0, [283.0, 8.0, 359.0, 158.0, 249.0, 371.0])
-
x (199.0, [283.0, 8.0, 359.0, 158.0, 249.0, 371.0, 199.0])
y (292.0, [283.0, 8.0, 359.0, 158.0, 249.0, 371.0, 199.0, 292.0])
-
x None
y (227.0, [283.0, 8.0, 359.0, 158.0, 249.0, 371.0, 199.0, 292.0, 47.0,
227.0])
-

Traceback (most recent call last):
  File "C:\Python25\Progs\PNP\pnp.py", line 44, in 
gen(50)
  File "C:\Python25\Progs\PNP\pnp.py", line 42, in gen
return generateList([], [(1,10),(4,272),(34,442),(112,42)], [],
rooms)
  File "C:\Python25\Progs\PNP\pnp.py", line 37, in generateList
generateList(dormlist,incompatibles,placed,rooms)
  File "C:\Python25\Progs\PNP\pnp.py", line 37, in generateList
generateList(dormlist,incompatibles,placed,rooms)
  File "C:\Python25\Progs\PNP\pnp.py", line 37, in generateList
generateList(dormli

Re: TypeError, I know why but not how!?

2008-07-10 Thread ssecorp
ty I came to the same conckusion in bed :)

now it works.


however since there are 400 students and some are incompatible I
shouldnt be able to generate a 200room list right?

but it works sometimes the other times i get an error. might be
because of recursion depth i never let the error finish.


i saw i also generate student 0 which shouldnt exist.




and the actual problem is generating all possible combinations right?
i mean i can easily generate one list that is made randomly so problem
solved.

why does one need to generate all possible lists? i guess there are
other problems where that might be needed so is this just a bad
example or am i missing something?


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


Re: TypeError, I know why but not how!?

2008-07-10 Thread ssecorp
I don't fully understand why I have to do this.


On Jul 10, 4:17 am, Robert Kern <[EMAIL PROTECTED]> wrote:
> ssecorp wrote:
> > Im looking into PvsNP:
> >http://www.claymath.org/millennium/P_vs_NP/
> > so I thought I'd write the program just to get a feel for it.
>
> > But I run into a problem. Why does it all the sudden return None? I
> > mean I know why the program aborts but I dont understand why the None
> > is generated all the sudden. Hitting recursion depth isn't reported
> > with that error.
>
> def validate(placed):
>      student = round(random.random()*401)
>      if student in placed:
>          # You need to explicitly return, here:
>          return validate(placed)
>      else:
>          placed.append(student)
>          return student, placed
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless enigma
>   that is made terrible by our own mad attempt to interpret it as though it 
> had
>   an underlying truth."
>    -- Umberto Eco

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


Weird lambda rebinding/reassignment without me doing it

2008-07-10 Thread ssecorp
I am never redefining the or reassigning the list when using validate
but since it spits the modified list back out that somehow means that
the modified list is part of the environment and not the old one.
i thought what happend inside a function stays inside a function
meaning what comes out is independent of what comes in.
Meaning if I want the list I send as a parameter to the function I
have to do x = func(x) and not just func(x) and x is magically what
comes out of func().
Doesnt Python have closure or that isnt what this is about?


def validate(placed):
student = round(random.random()*401)
if student in placed:
return validate(placed)
else:
placed.append(student)
return student, placed

def val(placed):
student = round(random.random()*401)
if student in placed:
return validate(placed)
else:
placed.append(student)
return student



>>> g = lambda x:validate(x)
>>> l=[]
>>> for x in range(1,10):
g(l)


(141.0, [141.0])
(19.0, [141.0, 19.0])
(86.0, [141.0, 19.0, 86.0])
(120.0, [141.0, 19.0, 86.0, 120.0])
(76.0, [141.0, 19.0, 86.0, 120.0, 76.0])
(262.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0])
(234.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0])
(74.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0])
(325.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0, 325.0])
>>> g = lambda x:val(x)
>>> l=[]
>>> for x in range(1,10):
g(l)


183.0
33.0
315.0
244.0
308.0
168.0
146.0
378.0
297.0
>>>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Weird lambda rebinding/reassignment without me doing it

2008-07-10 Thread ssecorp
ty very good answer. i know i shouldn't use lambda like that, i never
do i was just playing around there and then this happened which i
thought was weird.






On Jul 10, 8:09 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> David C. Ullrich wrote:
> > In article
> > <[EMAIL PROTECTED]>,
> >  ssecorp <[EMAIL PROTECTED]> wrote:
>
> >> I am never redefining the or reassigning the list when using validate
> >> but since it spits the modified list back out that somehow means that
> >> the modified list is part of the environment and not the old one.
> >> i thought what happend inside a function stays inside a function
> >> meaning what comes out is independent of what comes in.
> >> Meaning if I want the list I send as a parameter to the function I
> >> have to do x = func(x) and not just func(x) and x is magically what
> >> comes out of func().
>
> > A function cannot modify the value of a global variable
>
> Yes it can.
>  >>> a=[]
>  >>> def f():
>         a.append('yes I can')
>
>  >>> f()
>  >>> a
> ['yes I can']
>
> > (unless it specifies "global"). It doesn't reassign anything.
>
> The statement 'global a' would allow f to *rebind* the global *name*
> 'a'.  The word 'variable' should almost not be used in discussing Python
> since it is often unclear whether it refers to a name (or collection
> slot) or an object bound thereto.
>
> > But in the functions below you're not reassigning a variable,
> > you're _modifiying_ an object. A function _can_ modify an
> > object you pass to it:
>
> It can modify any mutable object it can access.
>
> >> Doesnt Python have closure or that isnt what this is about?
>
> Python does have closures.  This is not about that.
>
> >> def validate(placed):
> >>     student = round(random.random()*401)
> >>     if student in placed:
> >>         return validate(placed)
> >>     else:
> >>         placed.append(student)
> >>         return student, placed
>
> Delete this. It is redundant with the below.
>
> >> def val(placed):
> >>     student = round(random.random()*401)
> >>     if student in placed:
> >>         return validate(placed)
> >>     else:
> >>         placed.append(student)
> >>         return student
>
> I believe this is equivalent to
>
> def addval(placed):
>    while True:
>      student = round(random.random()*401)
>      if student not in placed:
>        break
>    placed.append(student)
>    return student
>
> While this avoids the indefinite recursion depth problem, it does not
> avoid the indefinite time problem.  Use random.shuffle, or write your
> own version if doing this for practice.  Also consider removing the
> return statement unless you actually directly use the added value.  It
> is easier to remember that addval mutates 'placed' without the return.
>
> >>>>> g = lambda x:validate(x)
>
> This is doubly diseased.
>
> First, never write a 'name = lambda...' statement since it is equivalent
> to a def statement except that the resulting function object lacks a
> proper .funcname attribute.  The above only trivially abbreviates
>    def g(x): return validate(x)
> by 3 characters.  Another reason is that the lambda form somehow more
> often tricks people into the next mistake .
>
> Second, never write a function (with either def or lambda) that simply
> returns a function of the argument(s).  The wrapping does nothing!  This
> is a waste of time and space for both you and the interpreter.  The
> above is functionally equivalent to
>    g = validate
> and if you want that, you could name the function 'g' when you define it.
>
> >>>>> l=[]
>
> In some fonts, 'l' and '1' are nearly identical; please use something
> else for public code, which you made this to be by posting it;-)
>
> >>>>> for x in range(1,10):
> >>        g(l)
>
> As said, the 'g' wrapper is useless.
>         addval(l)
>
> Hope this helps.
>
> Terry Jan Reedy

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


Re: Weird lambda rebinding/reassignment without me doing it

2008-07-10 Thread ssecorp
>>> def mod(x,y):
return x.append(y)

>>> mod([1,2],3)
>>> k=[1,2,3]
>>> k
[1, 2, 3]
>>> l = mod(k,4)
>>> l
>>> k
[1, 2, 3, 4]
>>> l
>>> k==l
False
>>> mod(k,5)
>>> k
[1, 2, 3, 4, 5]
>>> mod(l,4)

Traceback (most recent call last):
  File "", line 1, in 
mod(l,4)
  File "", line 2, in mod
return x.append(y)
AttributeError: 'NoneType' object has no attribute 'append'
>>> l
>>> l=k
>>> l
[1, 2, 3, 4, 5]
>>> i=mod(k,1)
>>> i
>>>

same stuff but i dont find this intuitive.
--
http://mail.python.org/mailman/listinfo/python-list


Why is this blowing the stack, thought it was tail-recursive...

2008-07-12 Thread ssecorp
def fib(n):
def fibt(a, b, n):
if n <= 1:
return b
else:
return fibt(b, a + b, n - 1)
if n == 0:
return 0
else:
return fibt(0, 1, n);


and can memoization speed up this even more? tesintg with memoization
doesnt really say anything because it is so fast it is instant anyway.


(the classic easy-redable exponential fib-function can obv be helped
enormously with memoization though.)
--
http://mail.python.org/mailman/listinfo/python-list


why is "self" used in OO-Python?

2008-07-12 Thread ssecorp
I first learned about OO from Java.

I much prefer to program in Python though.

However I am consufed about 2 things.

1. Why do I have to pass self into every method in a class? Since I am
always doing why cant this be automated or abstracted away?
Are the instances where I won't pass self?
I imagine there is some tradeoff involved otherwise it would have been
done away with.

2. self.item instead of getters and setters. I thought one of the main
purposes of OO was encapsulation. Doesn't messing with internal object-
representations break this?
I see how the getters and setters could be just visual clutter and you
have to add them to every class so it is annoying a bit in the same
way as self described above.
However I feel like I want getters and setters when I write classes,
not sure of the advantages/disadvantages though.
Only looking at the documentation of a Python-class, will internal
representations be provided?

If I have a class:

class Stack(object):
def __init__(self, *items):
self.stack = list(items)

def append(self, item):
self.stack.append(item)

def pop(self):
return self.stack.pop()

I can get to see the stack with var.stack but then why even implement
append when I could do self.stack.append(x) etc.
That way you could do away with OO completely. So why let people
access the main attribute but not let them manipulate it?
Makes more sense to draw the line to not access any attributes at all
no?
--
http://mail.python.org/mailman/listinfo/python-list


Re: why is "self" used in OO-Python?

2008-07-12 Thread ssecorp
On Jul 12, 8:44 pm, castironpi <[EMAIL PROTECTED]> wrote:
> On Jul 12, 1:01 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
>
>
>
> > ssecorp <[EMAIL PROTECTED]> wrote:
> > > 1. Why do I have to pass self into every method in a class? Since I am
> > > always doing why cant this be automated or abstracted away?
> > > Are the instances where I won't pass self?
> > > I imagine there is some tradeoff involved otherwise it would have been
> > > done away with.
>
> > When you define a method in Java there is an implicit 'this' passed to the
> > method. Python cannot tell when you define a function whether the function
> > is going to be used as a function, an instance method, a class method, a
> > static method or something else (or all of the above). Consider this:
>
> > The dynamic nature of Python means you can lift a method out of a class and
> > re-use it in a different context or inject a function into a class as a
> > method. There are two ways to handle this sort of code: javascript has an
> > implied 'this' for everything whether a function or what passes for a
> > method, Python makes it explicit.
>
> > > 2. self.item instead of getters and setters. I thought one of the main
> > > purposes of OO was encapsulation. Doesn't messing with internal object-
> > > representations break this?
>
> > That is correct. Some languages (e.g. Java) don't allow you to encapsulate
> > attributes so you have to write getter and setter methods. If you expose an
> > attribute in Java then you cannot later insert some code into the lookup or
> > override the set without getting all users of your code to change the way
> > they access the value. This is bad.
>
> > Other languages (e.g. Python, C#) allow you to intercept the attribute
> > lookup so you can change a plain attribute into a property without
> > requiring the users of your class alter their source code. With C# I
> > think they would still need to recompile their code so it may be more
> > appropriate to avoid using public attributes if you are producing a class
> > library for widespread reuse, but with Python there is no difference to the
> > user of your class whether they are accessing an attribute or a property.
>
> > Sadly a lot of Java programmers mistake the limitations of their language
> > for rules of OO programming, and worse this has spread from Java into other
> > languages where these restrictions no longer need apply.
>
> > Your Stack class is a bad example: the stack attribute is purely internal
> > so you wouldn't want to expose it as part of the public interface. Consider
> > instead something like:
>
> > class AddressBookEntry(object):
> >     def __init__(self, name, phone):
> >         self.name = name
> >         self.phone = phone
>
> >     @property
> >     def phone(self):
> >         return self._phone
>
> >     @property.setter
> >     def phone(self, number)
> >         validatephonenumber(number) # may throw an exception
> >           self._phone = number
>
> > If later you want to add some processing to the name attribute it is easy,
> > but putting in dummy property getter/setter methods before you need them
> > would be pointless.
>
> Part of the value of accessor methods appears when you're changing
> class definitions, or changing classes, after you've already started
> to use them-- the same interface with a different implementation.
>
> In the AddressBookEntry example, if you changed a pickled dictionary
> to a shelf, you could reimplement the class and reprocess stored data
> files, all without changing the code that uses the class-- especially
> if there's a lot of it, or you don't know where it all is.
>
> Nothing stops you from using accessor methods to offer encapsulation,
> and permit back-end changes later.  But, nothing in Java stops you
> from declaring class members public.
>
> Depending on your development process, data hiding may enforce
> distribution of labor a little better, resulting in errors in Java
> where Python relies only on discipline.  If you're checking for value
> validation, you can write a custom setter, regardless of language.
>
> Python doesn't break encapsulation; you do.
>
> In the Stack example, you have more options than you've mentioned.
> Can you inherit from list directly?  Can you delegate using
> reflection?  Are you studying this example specifically, or the class
> model generally?  If you're choosing a language, be careful that
> stricter enforcement doesn't cause harder-to-find bugs.
>
> Useful link: Section 9.4 in the docs:http://docs.python.org/tut/node11.html




ty for all the answers. Im not saying either is better Im just trying
to fiugre out the philosophies behind each language and their
respective pros and cons.


and self is apparently not a reserved word so I could replace it with
"blahaba".
But basically Python trusts the programmer and relies on conventions
rather than enforcements like Java does.
--
http://mail.python.org/mailman/listinfo/python-list


Correct use of try,except and raise?

2008-07-12 Thread ssecorp
Is this correct use of exceptions? to raise an indexerror and add my
own string insetad of just letting it raise a IndexError by itself and
"blaming" it on list.pop?

class Stack(object):
def __init__(self, *items):
self.stack = list(items)

def push(self, item):
self.stack.append(item)

def pop(self):
try:
return self.stack.pop()
except:
raise IndexError, "pop from empty stack"

class Queue(object):
def __init__(self, *items):
self.queue = list(items)

def append(self, item):
self.queue.append(item)

def pop(self):
try:
return self.queue.pop(0)
except:
raise IndexError, "pop from empty queue"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Correct use of try,except and raise?

2008-07-12 Thread ssecorp
On Jul 13, 2:32 am, Roy Smith <[EMAIL PROTECTED]> wrote:
> In article
> <[EMAIL PROTECTED]>,
>
>
>
>  ssecorp <[EMAIL PROTECTED]> wrote:
> > Is this correct use of exceptions? to raise an indexerror and add my
> > own string insetad of just letting it raise a IndexError by itself and
> > "blaming" it on list.pop?
>
> > class Stack(object):
> >     def __init__(self, *items):
> >         self.stack = list(items)
>
> >     def push(self, item):
> >         self.stack.append(item)
>
> >     def pop(self):
> >         try:
> >             return self.stack.pop()
> >         except:
> >             raise IndexError, "pop from empty stack"
>
> > class Queue(object):
> >     def __init__(self, *items):
> >         self.queue = list(items)
>
> >     def append(self, item):
> >         self.queue.append(item)
>
> >     def pop(self):
> >         try:
> >             return self.queue.pop(0)
> >         except:
> >             raise IndexError, "pop from empty queue"
>
> I think you would do better defining a new exception, PopError, or
> something like that.  Then you can write code which specifically catches
> that and do something with it.
>
> It's also not a good idea to catch all exceptions.  Catch the most specific
> thing you can.  Consider something like:
>
> try:
>     kew.pop(0)
> except:
>    raise IndexError, "pop from empty kew"
>
> When I run it, it prints, "IndexError: pop from empty kew".  The problem
> is, the *real* error is "NameError: name 'kew' is not defined".  By
> catching all exceptions, I've masked a programming error by turning the
> NameError into an IndexError.



i dont get what you mean, if i dont do anything python will raise an
indexerror so it is an indexerror.
--
http://mail.python.org/mailman/listinfo/python-list


tail-rec decorator, well still blows the stack...

2008-07-21 Thread ssecorp
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691

so I try it and when I run:
@Decorators.tail_recursion
def fibtr(n):
def fibt(a, b, n):
if n <= 1:
return b
else:
return fibt(b, a + b, n - 1)
if n == 0:
return 0
else:
return fibt(0, 1, n);

it still blows the stack. so what is the point? is it impossible to
get "real" tail-recursion in Python?
--
http://mail.python.org/mailman/listinfo/python-list


Re: tail-rec decorator, well still blows the stack...

2008-07-21 Thread ssecorp
I my function not proper tail-recursion?


because this doesn't blow the stack:


#!/usr/bin/env python2.4
# This program shows off a python decorator(
# which implements tail call optimization. It
# does this by throwing an exception if it is
# it's own grandparent, and catching such
# exceptions to recall the stack.

import sys

class TailRecurseException:
  def __init__(self, args, kwargs):
self.args = args
self.kwargs = kwargs

def tail_call_optimized(g):
  """
  This function decorates a function with tail call
  optimization. It does this by throwing an exception
  if it is it's own grandparent, and catching such
  exceptions to fake the tail call optimization.

  This function fails if the decorated
  function recurses in a non-tail context.
  """
  def func(*args, **kwargs):
f = sys._getframe()
if f.f_back and f.f_back.f_back \
and f.f_back.f_back.f_code == f.f_code:
  raise TailRecurseException(args, kwargs)
else:
  while 1:
try:
  return g(*args, **kwargs)
except TailRecurseException, e:
  args = e.args
  kwargs = e.kwargs
  func.__doc__ = g.__doc__
  return func

@tail_call_optimized
def factorial(n, acc=1):
  "calculate a factorial"
  if n == 0:
return acc
  return factorial(n-1, n*acc)

print factorial(1)
# prints a big, big number,
# but doesn't hit the recursion limit.

@tail_call_optimized
def fib(i, current = 0, next = 1):
  if i == 0:
return current
  else:
return fib(i - 1, next, current + next)

print fib(1)
# also prints a big number,
# but doesn't hit the recursion limit.
--
http://mail.python.org/mailman/listinfo/python-list


Re: tail-rec decorator, well still blows the stack...

2008-07-21 Thread ssecorp
thanks i already have perfect iterative versions of fibonacci.
def fib(n):
a, b = 1, 0
while n:
a, b, n = b, a+b, n-1
return b


I know the example is not the way to write pythonic code, I was just
learning about decorators and then I saw this example and tried it
out.

but thanks now i understand why it didn't work.
--
http://mail.python.org/mailman/listinfo/python-list


x*x if x>10

2008-07-27 Thread ssecorp
I have seen somewhere that you can write something like:

x*x if x>10

but exactly that doesn't work and I can't get any variation to work.

it is possible to nest with an else too.


how do you write it?


and also, is it idiomatic? doesn't seem to add functionality, just
another way of doing the same thing which is quite unpythonic but I
remember reading it was added because it helped simplify the
expression of a certain type of operation.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rant (was Re: x*x if x>10

2008-07-27 Thread ssecorp
I might be misunderstanding OP but:

a+b+c+d+e is simple way of concatenating 5 lists...

as a function that takes any amount of lists and concatenates them:
def concat(*args):
c = []
for elem in args:
c += elem
return c

don't know if extend is faster or slower or the same as + :

def concat(*args):
c = []
for elem in args:
c.extend(elem)
return c

I don't know of a built-in.
--
http://mail.python.org/mailman/listinfo/python-list


How smart is the Python interpreter?

2008-07-31 Thread ssecorp
def str_sort(string):
s = ""
for a in sorted(string):
s+=a
return s


if i instead do:

def str_sort(string):
s = ""
so = sorted(string)
for a in so:
s+=a
return s


will that be faster or the interpreter can figure out that it only has
to do sorted(string) once? or that kind of cleverness is usually
reserved for compilers and not interpreters?
--
http://mail.python.org/mailman/listinfo/python-list


Profiling weirdness: Timer.timeit(), fibonacci and memoization

2008-08-02 Thread ssecorp
I am not clear about the results here.


from timeit import Timer
import Decorators

def fib(n):
a, b = 1, 0
while n:
a, b, n = b, a+b, n-1
return b

@Decorators.memoize
def fibmem(nbr):
if nbr > 1:
return fibmem(nbr-1) + fibmem(nbr-2)
if nbr == 1:
return 1
if nbr == 0:
return 0

s = 100

t1 = Timer('fib(s)', 'from __main__ import fib, s')
t2 = Timer('fibmem(s)', 'from __main__ import fibmem, s')
t1.repeat(number=1)
t2.repeat(number=1)
print t1.timeit()
print t2.timeit()


>>>
35.3092010297
1.6516613145
>>>


So memoization is 20+ times faster than the idiomatic way?
Or am I missing something here?


Ok for fun I added memoization to the idiomatic one:

from timeit import Timer
import Decorators

@Decorators.memoize
def fib(n):
a, b = 1, 0
while n:
a, b, n = b, a+b, n-1
return b

@Decorators.memoize
def fibmem(nbr):
if nbr > 1:
return fibmem(nbr-1) + fibmem(nbr-2)
if nbr == 1:
return 1
if nbr == 0:
return 0

s = 100

t1 = Timer('fib(s)', 'from __main__ import fib, s')
t2 = Timer('fibmem(s)', 'from __main__ import fibmem, s')
t1.repeat(number=1)
t2.repeat(number=1)
print t1.timeit()
print t2.timeit()


didn't think it would make a difference there but it certainly did.


>>>
1.59592657726
1.60179436213
>>>  RESTART 
>>>
2.66468922726
3.0870236301
>>>  RESTART 
>>>
1.62921684181
1.51585159566
>>>  RESTART 
>>>
1.49457319296
1.60948472501
>>>  RESTART 
>>>
1.48718203012
1.6645559701
>>>
--
http://mail.python.org/mailman/listinfo/python-list


I donä't get while-loops

2008-08-02 Thread ssecorp
in read2 it never quits when I write quit, why?

def read():
expr = raw_input("Lisp> ")
if expr != "quit":
print parse(expr)
read()
else:
print "Good session!"

def read2():
expr = ""
while expr != "quit":
expr = raw_input("Lisp> ")
print parse(expr)
read2()
print "Good session!"
--
http://mail.python.org/mailman/listinfo/python-list


Re: I donä't get while-loops

2008-08-02 Thread ssecorp
oops, embarrassing, I created the while loop not to use recursion then
I still did...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Profiling weirdness: Timer.timeit(), fibonacci and memoization

2008-08-03 Thread ssecorp
I think you are confusing 2 people in this thread but that doesn't
really matter.
What surprised me was that I didn't think fib would benefit from
memoization because it didn't repeat the same calculations. fibmem
without memoization is the classic naive implementation that grows
exponentially and obv that would benefit from memoization.


from timeit import Timer
import Decorators

@Decorators.memoize
def fib(n):
a, b = 1, 0
while n:
a, b, n = b, a+b, n-1
return b

@Decorators.memoize
def fibmem(nbr):
if nbr > 1:
return fibmem(nbr-1) + fibmem(nbr-2)
if nbr == 1:
return 1
if nbr == 0:
return 0

s = 100
t1 = Timer('fib(s)', 'from __main__ import fib, s')
t2 = Timer('fibmem(s)', 'from __main__ import fibmem, s')
print t1.repeat(number=1)
print t2.repeat(number=1)
print t1.timeit()
print t2.timeit()


>>>
[4.895097002557e-005, 3.6317464929201785e-006,
3.0730162632401604e-006]
[0.0014432001832635141, 5.5873022968000452e-006,
3.0730162632417596e-006]
1.4421612244
1.34121264015
>>>
--
http://mail.python.org/mailman/listinfo/python-list


Why doesn't import work?

2008-08-04 Thread ssecorp
I have in Lib/site-packages a module named pdfminer. when I do import
pdfminer it complains:

>>> import pdfminer

Traceback (most recent call last):
  File "", line 1, in 
import pdfminer
ImportError: No module named pdfminer


I created a file pdfminer.py and put it in site-packages and that
works.

so I apparently can't import a directory pdfminer. In the directory
pdfminer there are 3 other directoriees and inside them python-files.

how would I import them?
--
http://mail.python.org/mailman/listinfo/python-list


Wildcards for regexps?

2008-08-10 Thread ssecorp
If I have an expression like "bob marley" and I want to match
everything with one letter wrong, how would I do?
so "bob narely" and "vob marley" should match etc.
--
http://mail.python.org/mailman/listinfo/python-list


for x,y in word1, word2 ?

2008-08-10 Thread ssecorp
Is there a syntax for looping through 2 iterables at the same time?

for x in y:
for a in b:


is not what I want.

I want:
for x in y and for a in b:
--
http://mail.python.org/mailman/listinfo/python-list


Re: for x,y in word1, word2 ?

2008-08-10 Thread ssecorp
On Aug 11, 6:40 am, Mensanator <[EMAIL PROTECTED]> wrote:
> On Aug 10, 11:18 pm, ssecorp <[EMAIL PROTECTED]> wrote:
>
> > Is there a syntax for looping through 2 iterables at the same time?
>
> > for x in y:
> > for a in b:
>
> > is not what I want.
>
> > I want:
> > for x in y and for a in b:
>
> Something like this?
>
> >>> a = ['a','b','c']
> >>> b = [1,2,3]
> >>> zip(a,b)
>
> [('a', 1), ('b', 2), ('c', 3)]

I know zip but lets say I have a word "painter" and I want to compare
it to a customer's spelling, he might have written "paintor" and I
want to check how many letters are the same.

Now I know how I could do this, it is not hard.
I am just wondering if these is any specific simple syntax for it.
--
http://mail.python.org/mailman/listinfo/python-list


Python GUI interpreter slower than DOS-version?

2008-08-12 Thread ssecorp
Sometimes when running very intensive computations the Python-
interpreter kind of overheats and stops responding.

I have gotten the impression that the dos-version is less likely to
crash. Can that be true and if so, why?

Is there anyway to get around this? Pretty annoying that it stops
responding, would be nice to be able to control-c out of it like in
DOS when you want to terminate a program.
--
http://mail.python.org/mailman/listinfo/python-list


super, object and type?

2008-08-12 Thread ssecorp
>>> super(object, type)
, >
>>> super(type, object)
, >
>>>

how can both work?

they can't both be the superclass of each other right? or is it some
sort of mutually recursive definition?




>>> help(object)
Help on class object in module __builtin__:

class object
 |  The most base type

>>> help(type)
Help on class type in module __builtin__:

class type(object)
 |  type(object) -> the object's type
 |  type(name, bases, dict) -> a new type
--
http://mail.python.org/mailman/listinfo/python-list


How to stop iteration with __iter__() ?

2008-08-19 Thread ssecorp
I want a parse a file of the format:
movieId
customerid, grade, date
customerid, grade, date
customerid, grade, date
etc.

so I could do with open file as reviews and then for line in reviews.

but first I want to take out the movie id so I use an iterator.

then i want to iterate through all the rows, but how can I do:
while movie_iter != None:

because that doesn't work, itraises an exception, StopItreation, which
according to the documentation it should. But catching an exception
can't be the standard way to stop iterating right?
--
http://mail.python.org/mailman/listinfo/python-list


Generate alphabet?

2008-08-22 Thread ssecorp
In Haskell I can do [1..10] for range(1,11) and ['a'..'z'] for a list
of the alphabet.

Is there a way in Python to generate chars?
--
http://mail.python.org/mailman/listinfo/python-list


Replace reduce with listcomprehension?

2008-08-25 Thread ssecorp
GvR wants to eliminate all the functional stuff (lambda map reduce
filter) which kind of makes sense for Python, listcomprehensions are
more efficient(at least as implemented inpython) from what i have
gathered and they can express everything map/reduce/filter with
crippled lambdas can.

but what about this:
reduce(lambda x,y:x*y+x,[1,2,3,4,5,6])

how would I express that in a listcomprehension?
--
http://mail.python.org/mailman/listinfo/python-list


How to update value in dictionary?

2008-08-27 Thread ssecorp
dict.update({"a":1}) SETS the dict item "a" 's value to 1.

i want to increase it by 1. isnt that possible in an easy way? I
should use a tuple for this?
--
http://mail.python.org/mailman/listinfo/python-list


no string.downer() ?

2008-08-27 Thread ssecorp
if i want to make a string downcase, is upper().swapcase() the onyl
choice? there is no downer() ?
--
http://mail.python.org/mailman/listinfo/python-list


List of modules available for import inside Python?

2008-08-27 Thread ssecorp
Is there a way to view all the modules I have available for import
from within Python?
Like writing in the interpreter:
import.modules


Also, is there anything like Cpan for Python?
--
http://mail.python.org/mailman/listinfo/python-list


Is this a closure?

2008-08-31 Thread ssecorp
A method on a class:

def printSelf(self):
def printReviews():
for review in self.reviews:
review.printSelf()
print "Idnbr: ", self.idnumber, "Reviews: ", printReviews()

I don't have to pass an argument to printReviews because everything
defined inside printSelf is aware of outer variables? Or is that
wrong? If it is right, is this what a closure means?

Because Python is lexically scoped right? Is lexical scope+closures =
organized dynamic scope kind of if you get my point?

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


Some problems with classes

2008-08-31 Thread ssecorp
Why/how is it possible to add variables like this? I don't understand
this mechanism:
http://docs.python.org/tut/node11.html#SECTION001133

class Employee:
pass

john = Employee() # Create an empty employee record

# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000

---

Also, I can't get multiple inheritance to work.

Don't mind that the a vegan obviously don't inherit from an animal and
a vegetable. I didn't come up with anything better, it is just to
learn about inheritance.


class Animal(object):
def __init__(self, name, weight):
self.name = name
self.weight = weight

def speak(self):
print "speak"

class Vegetable(object):
def __init__(self, name, volume):
self.name = name
self.volume = volume

def split(self):
print "tjoff"

class Vegan(Animal, Vegetable):
#pass
def __init__(self, name, attacks):
self.name = name
self.attacks = attacks

>>>

Traceback (most recent call last):
  File "C:/Python25/Progs//Movie.py", line 42, in 
class ActionComedy(Movie, ActionMovie):
TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution
order (MRO) for bases Movie, ActionMovie
>>>


also, when inheriting, can I inherit __init__() somehow? If I want the
same attributes but perhaps some additional methods for example.

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


Re: Some problems with classes

2008-08-31 Thread ssecorp
class Animal(object):
def __init__(self, name, weight):
self.name = name
self.weight = weight

def speak(self):
print "speak"

class Vegetable(object):
def __init__(self, name, volume):
self.name = name
self.volume = volume

def split(self):
print "tjoff"

class Vegan(Animal, Vegetable):
def __init__(self, name, attacks):
self.name = name
self.attacks = attacks
--
http://mail.python.org/mailman/listinfo/python-list


Re: Some problems with classes

2008-08-31 Thread ssecorp
also, how does super() work more exactly? I can't get it quite to
work.


class Movie(object):
def __init__(self, movieId, grades, date):
self.movieId = movieId
self.grades = grades
self.date = date

def newGrade(self, grade):
self.grades.append(grade)

def spam(self):
print "inherits all the way down?"

def averageGrade(self):
 return sum(grade for grade in self.grades) / \
len(self.grades)

class ActionMovie(Movie):
super(Movie)
##def __init__(self, movieId, grades, date, kills):
##self.movieId = movieId
##self.grades = grades
##self.date = date
##self.kills = kills

def newGrade(self, grade, date):
self.grades.append(grade)
self.date = date

def prd(self):
print self.date

class Comedy(ActionMovie):
def __init__(self, movieId, grades, date):
self.movieId = movieId
self.grades = grades
self.date = date

def donk(self):
print "im a donkey!"


subclasses has to be indented?
class C(B):
def meth(self, arg):
super(C, self).meth(arg)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Some problems with classes

2008-08-31 Thread ssecorp
It works when I inherit from 2 classes but not when I inherit from 2
subclasses.


-

from __future__ import division

class Movie(object):
def __init__(self, movieId, grades, date):
self.movieId = movieId
self.grades = grades
self.date = date

def newGrade(self, grade):
self.grades.append(grade)

def spam(self):
print "inherits all the way down?"

def averageGrade(self):
 return sum(grade for grade in self.grades) / \
len(self.grades)

class ActionMovie(Movie):
#super(Movie, self)
def __init__(self, movieId, grades, date, kills):
self.movieId = movieId
self.grades = grades
self.date = date
self.kills = kills

def newGrade(self, grade, date):
self.grades.append(grade)
self.date = date

def prd(self):
print self.date

class Comedy(ActionMovie):
def __init__(self, movieId, grades, date):
self.movieId = movieId
self.grades = grades
self.date = date

def donk(self):
print "im a donkey!"

##class ActionComedy(Movie, ActionMovie):
##def __init__(self, movieId, grades, date):
##self.movieId = movieId
##self.grades = grades
##self.date = date



class Animal(object):
def __init__(self, name, weight):
self.name = name
self.weight = weight

def speak(self):
print "speak"

class Vegetable(object):
def __init__(self, name, volume):
self.name = name
self.volume = volume

def split(self):
print "tjoff"

class Vegan(Animal, Vegetable):
#pass
#super()
def __init__(self, name, attacks):
self.name = name
self.attacks = attacks

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


Getting an objetcs dict?

2008-09-01 Thread ssecorp
I did nce(I think).

class X

X.__dict__() and ngot a dict of its variables.

Now i get errors doing this. what am i doing wrong?
--
http://mail.python.org/mailman/listinfo/python-list


Is try-except slow?

2008-09-02 Thread ssecorp
or why does this take so god damn long time?
and if I run into an IndexError it break out of the inner loop right?
so having range up to 1000 or 1000 wouldn't matter if biggest
working x is 800?

def getPixels(fileName):
im = PIL.Image.open(fileName)
colors = []
for y in range(1, 1000):
row = []
for x in range(1, 1000):
try:
color = im.getpixel((x,y))
row.append(color)
except IndexError:
break
colors.append(row)
return numpy.array(colors)

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