Re: [Tutor] why do i get None as output

2010-09-06 Thread Andre Engels
On Mon, Sep 6, 2010 at 8:34 AM, Roelof Wobben  wrote:
> Hello,
>
> I have this programm:
>
> def encapsulate(val, seq):
>     if type(seq) == type(""):
>     return str(val)
>     if type(seq) == type([]):
>     return [val]
>     return (val,)
>
> def insert_in_middle(val, seq):
>     middle = len(seq)/2
>     return seq[:middle] + encapsulate(val, seq) + seq[middle:]
>
> def make_empty(seq):
>     """
>   >>> make_empty([1, 2, 3, 4])
>   []
>   >>> make_empty(('a', 'b', 'c'))
>   ()
>   >>> make_empty("No, not me!")
>   ''
>     """
>     word2=""
>     teller=0
>     if type(seq) == type([]):
>     teller=0
>     while teller < len(seq):
>     seq[teller]=""
>     teller = teller + 1
>     elif type(seq) == type(()):
>     tup2 = list (seq)
>     while teller > tup2.len():
>     tup2[teller]=""
>     teller = teller + 1
>     seq = tuple(tup2)
>     else:
>     seq = ""
>
> test = make_empty([1, 2, 3, 4])
> print test
>
> But now I get None as output instead of []
>
> Can anyone explain why that happens ?

test = make_empty([1, 2, 3, 4]) makes test equal to the return value
of make_empty. But make_empty does not return anything, and in that
case its return value is made equal to empty. Compare:

def f(x):
x = x + 1

def g(x):
x = x + 1
return x

def h(x):
return x +1

print f(1)
>> None

print g(1)
>> 2

print h(1)
>> 2


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] why do i get None as output

2010-09-06 Thread Alan Gauld


"Roelof Wobben"  wrote 


def make_empty(seq):
   word2=""
   teller=0
   if type(seq) == type([]):
   teller=0 
   while teller < len(seq):

   seq[teller]=""
   teller = teller + 1 
   elif type(seq) == type(()):

   tup2 = list (seq)
   while teller > tup2.len():
   tup2[teller]=""
   teller = teller + 1
   seq = tuple(tup2)
   else:
   seq = ""
  
test = make_empty([1, 2, 3, 4])


But now I get None as output instead of []


Because None is the default return value from a function.
If you do not return a value (which you don;t in this case) then 
Python automatically returns None.


You need to return something from your make_empty function.

Also, if all you want to do is return an empty version of 
whatever has been passed in there are much easier 
ways of doing it! And in fact, a list of empty strings is 
not the same as an empty list...



HTH

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] setattr vs __setattr__

2010-09-06 Thread Rasjid Wilcox
Hi all,

Suppose we have

class A(object):
pass

a = A()

Is there any difference between

setattr(a, 'foo', 'bar)

and

a.__setattr__['foo'] = 'bar'

other than syntax?

And which is considered 'better' form in Python?

Cheers,

Rasjid.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] why do i get None as output

2010-09-06 Thread Roelof Wobben


 

> To: tutor@python.org
> From: alan.ga...@btinternet.com
> Date: Mon, 6 Sep 2010 08:27:31 +0100
> Subject: Re: [Tutor] why do i get None as output
> 
> 
> "Roelof Wobben"  wrote 
> 
> def make_empty(seq):
> word2=""
> teller=0
> if type(seq) == type([]):
> teller=0 
> while teller < len(seq):
> seq[teller]=""
> teller = teller + 1 
> elif type(seq) == type(()):
> tup2 = list (seq)
> while teller > tup2.len():
> tup2[teller]=""
> teller = teller + 1
> seq = tuple(tup2)
> else:
> seq = ""
> 
> test = make_empty([1, 2, 3, 4])
> 
> But now I get None as output instead of []
> 
> 
> Because None is the default return value from a function.
> If you do not return a value (which you don;t in this case) then 
> Python automatically returns None.
> 
> You need to return something from your make_empty function.
> 
> Also, if all you want to do is return an empty version of 
> whatever has been passed in there are much easier 
> ways of doing it! And in fact, a list of empty strings is 
> not the same as an empty list...
> 
> 
> HTH
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> 
> 
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

 

Oke, 

 

I put a return seq in the programm and it looks now like this :

 

def encapsulate(val, seq):
if type(seq) == type(""):
return str(val)
if type(seq) == type([]):
return [val]
return (val,)

 

def insert_in_middle(val, seq):
middle = len(seq)/2
return seq[:middle] + encapsulate(val, seq) + seq[middle:]

 

def make_empty(seq):
"""
  >>> make_empty([1, 2, 3, 4])
  []
  >>> make_empty(('a', 'b', 'c'))
  ()
  >>> make_empty("No, not me!")
  ''
"""
if type(seq) == type([]):
seq = []
elif type(seq) == type(()):
seq=()
else:
seq = ""
return seq

 

if __name__ == "__main__":
import doctest
doctest.testmod()

 

This works but I don't think its what the exercise means :

 



Create a module named seqtools.py. Add the functions encapsulate and 
insert_in_middle from the chapter. Add doctests which test that these two 
functions work as intended with all three sequence types.

Add each of the following functions to seqtools.py:

def make_empty(seq):
"""
  >>> make_empty([1, 2, 3, 4])
  []
  >>> make_empty(('a', 'b', 'c'))
  ()
  >>> make_empty("No, not me!")
  ''
"""

So i think I have to use encapsulate and insert_in_middle. And I don't use it.

 

Roelof


 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] why do i get None as output

2010-09-06 Thread Andre Engels
On Mon, Sep 6, 2010 at 9:41 AM, Roelof Wobben  wrote:
>
>
>> To: tutor@python.org
>> From: alan.ga...@btinternet.com
>> Date: Mon, 6 Sep 2010 08:27:31 +0100
>> Subject: Re: [Tutor] why do i get None as output
>>
>>
>> "Roelof Wobben"  wrote
>>
>> def make_empty(seq):
>> word2=""
>> teller=0
>> if type(seq) == type([]):
>> teller=0
>> while teller < len(seq):
>> seq[teller]=""
>> teller = teller + 1
>> elif type(seq) == type(()):
>> tup2 = list (seq)
>> while teller > tup2.len():
>> tup2[teller]=""
>> teller = teller + 1
>> seq = tuple(tup2)
>> else:
>> seq = ""
>>
>> test = make_empty([1, 2, 3, 4])
>>
>> But now I get None as output instead of []
>>
>>
>> Because None is the default return value from a function.
>> If you do not return a value (which you don;t in this case) then
>> Python automatically returns None.
>>
>> You need to return something from your make_empty function.
>>
>> Also, if all you want to do is return an empty version of
>> whatever has been passed in there are much easier
>> ways of doing it! And in fact, a list of empty strings is
>> not the same as an empty list...
>>
>>
>> HTH
>>
>> --
>> Alan Gauld
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/
>>
>>
>> ___
>> Tutor maillist - Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> Oke,
>
> I put a return seq in the programm and it looks now like this :
>
> def encapsulate(val, seq):
>     if type(seq) == type(""):
>     return str(val)
>     if type(seq) == type([]):
>     return [val]
>     return (val,)
>
> def insert_in_middle(val, seq):
>     middle = len(seq)/2
>     return seq[:middle] + encapsulate(val, seq) + seq[middle:]
>
> def make_empty(seq):
>     """
>   >>> make_empty([1, 2, 3, 4])
>   []
>   >>> make_empty(('a', 'b', 'c'))
>   ()
>   >>> make_empty("No, not me!")
>   ''
>     """
>     if type(seq) == type([]):
>     seq = []
>     elif type(seq) == type(()):
>     seq=()
>     else:
>     seq = ""
>     return seq
>
> if __name__ == "__main__":
>     import doctest
>     doctest.testmod()
>
> This works but I don't think its what the exercise means :
>
>
> Create a module named seqtools.py. Add the functions encapsulate and
> insert_in_middle from the chapter. Add doctests which test that these two
> functions work as intended with all three sequence types.
>
> Add each of the following functions to seqtools.py:
>
> def make_empty(seq):
> """
>   >>> make_empty([1, 2, 3, 4])
>   []
>   >>> make_empty(('a', 'b', 'c'))
>   ()
>   >>> make_empty("No, not me!")
>   ''
> """
>
> So i think I have to use encapsulate and insert_in_middle. And I don't use
> it.

I don't think so. They don't look like the kind of thing that would be
useful for this function. In your example seqtools.py is supposed to
be a (toy example of a) library, a collection of functions to do
things with sequence-like objects to be used by other programs. These
functions in general need not have much to do with eachother, except
that they work on the same type of objects.


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] setattr vs __setattr__

2010-09-06 Thread Hugo Arts
On Mon, Sep 6, 2010 at 9:27 AM, Rasjid Wilcox  wrote:
> Hi all,
>
> Suppose we have
>
> class A(object):
>    pass
>
> a = A()
>
> Is there any difference between
>
> setattr(a, 'foo', 'bar)
>
> and
>
> a.__setattr__['foo'] = 'bar'
>

Did you mean a.__setattr__('foo', 'bar')? That's the same thing,
though you'd generally use a.foo = 'bar' or setattr(a, 'foo', 'bar'),
in that order of preference.

If you meant a.__dict__['foo'] = 'bar', that may or may not be the
same thing depending on the class. It works for instances of object,
but fails for any class that defines __slots__, for example.  I'd
generally recommend you don't do it. Use setattr instead.

Hugo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] setattr vs __setattr__

2010-09-06 Thread Rasjid Wilcox
On 6 September 2010 19:55, Hugo Arts  wrote:
> On Mon, Sep 6, 2010 at 9:27 AM, Rasjid Wilcox  wrote:
>> Hi all,
>>
>> Suppose we have
>>
>> class A(object):
>>    pass
>>
>> a = A()
>>
>> Is there any difference between
>>
>> setattr(a, 'foo', 'bar)
>>
>> and
>>
>> a.__setattr__['foo'] = 'bar'
>>
>
> Did you mean a.__setattr__('foo', 'bar')? That's the same thing,
> though you'd generally use a.foo = 'bar' or setattr(a, 'foo', 'bar'),
> in that order of preference.

Sorry, yes, a.__setattr__('foo', 'bar') is what I meant.  I'm actually
iterating over a number of attributes, so AFASK the first form is not
an option.  I've been using

for attr_name in name_list:
setattr(a, attr_name, getattr(b, attr_name))

to copy the attributes from one type of class to another, and it is
not quite as readable as I would like.  Actually, I've just thought
that the best option would be to make both classes dictionary like
objects with automatic translation between a['foo'] and a.foo.
Sqlalchemy uses that for its query result objects with good effect.

Cheers,

Rasjid.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Arguments from the command line

2010-09-06 Thread aug dawg
I've seen Python programs that can be activated from the command line. For
example:

hg

This displays a list of commands for the Mercurial revision control system.
But another command is this:

hg commit "This is a commit name"

Mercurial is written in Python. I know that commit is a function that
commits to a repo, but what command does the program use in order to get the
commit name, like "This is a commit name" (This would make a commit with
"This is a commit name" as the commit name)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Arguments from the command line

2010-09-06 Thread Hugo Arts
On Mon, Sep 6, 2010 at 5:48 PM, aug dawg  wrote:
> I've seen Python programs that can be activated from the command line. For
> example:
> hg
>
> This displays a list of commands for the Mercurial revision control system.
> But another command is this:
> hg commit "This is a commit name"
> Mercurial is written in Python. I know that commit is a function that
> commits to a repo, but what command does the program use in order to get the
> commit name, like "This is a commit name" (This would make a commit with
> "This is a commit name" as the commit name)
>

sys.argv is a list of all arguments from the command line. However,
you'll rarely deal with it directly, there's various modules that deal
with handling arguments. I believe the current one is argparse:
http://docs.python.org/library/argparse.html#module-argparse

Hugo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Arguments from the command line

2010-09-06 Thread Mark Weil
I think you're looking for this:

http://docs.python.org/library/argparse.html

you'll also want to read up on sys.argv

http://docs.python.org/library/sys.html#sys.argv



On Mon, Sep 6, 2010 at 8:48 AM, aug dawg  wrote:

> I've seen Python programs that can be activated from the command line. For
> example:
>
> hg
>
> This displays a list of commands for the Mercurial revision control system.
> But another command is this:
>
> hg commit "This is a commit name"
>
> Mercurial is written in Python. I know that commit is a function that
> commits to a repo, but what command does the program use in order to get the
> commit name, like "This is a commit name" (This would make a commit with
> "This is a commit name" as the commit name)
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Arguments from the command line

2010-09-06 Thread bob gailer

 On 9/6/2010 11:48 AM, aug dawg wrote:
I've seen Python programs that can be activated from the command line. 
For example:


hg

This displays a list of commands for the Mercurial revision control 
system. But another command is this:


hg commit "This is a commit name"

Mercurial is written in Python. I know that commit is a function that 
commits to a repo, but what command does the program use in order to 
get the commit name, like "This is a commit name" (This would make a 
commit with "This is a commit name" as the commit name)

hg.py:
import sys
print sys.argv

$hg commit "This is a commit name"
['C:\\hg.py', 'commit', 'This is a commit name']

--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] exercise correct ??

2010-09-06 Thread Roelof Wobben

Hello, 

 

I have this programm :

 

def index_of(val, seq, start=0):
"""
  >>> index_of(9, [1, 7, 11, 9, 10])
  3
  >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5))
  3
  >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
  6
  >>> index_of('y', 'happy birthday')
  4
  >>> index_of('banana', ['apple', 'banana', 'cherry', 'date'])
  1
  >>> index_of(5, [2, 3, 4])
  -1
  >>> index_of('b', ['apple', 'banana', 'cherry', 'date'])
  -1
"""
plek = 0 
if type(seq) == type([]):
plek = seq.index(val)
elif type(seq) == type(()):
seq = list (seq)
plek = seq.index(val)
else :
plek = seq.find(val)
return plek 


 

But I get this message :

 

File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 70, in 
__main__.index_of
Failed example:
index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
Expected:
6
Got:
3

 

But in that tuple 5 is on position 3.

 

Is the exercise here wrong ?

 

Roelof

 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Simple Python Problem

2010-09-06 Thread Keith Lucas
What is wrong with the following, apparently almost straight out of Python 
Programming
by Michael Dawson?



# Declare variable and initialise (overkill!).
name = "ABCDEFG"

# Get value.
name = input("What is your name? ")

# Echo value
print(name)

# Issue greeting
print("Hi ", name)


Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on 
win32 Type
"copyright", "credits" or "license()" for more information.
>>>  RESTART 
What is your name? Keith

Traceback (most recent call last):
  File "C:\Documents and Settings\User\My Documents\My Files\Staff\Keith
Lucas\Education\Python\Learn_Input_01.py", line 5, in 
name = input("What is your name? ")
  File "", line 1, in 
NameError: name 'Keith' is not defined




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Multiple versions of python and paths problems

2010-09-06 Thread Dominique
Hello,

I usually use python 2.6 and several packages. Everything's fine.

At present, I'm trying to run a package which is only available with python 2.5.
So, i installed 2.5 and the various dependencies needed to run this package:
PIL, numpy... which were already installed in my 2.6 site-packages.

Unfortunately, when I try to run it under Idle 2.5, python goes in the 2.6
site-packages to get these dependencies (PIL,...) and throws me a traceback (due
to incompatibilities).

I understand it is a paths problem.

So, I added the path of python 2.5 and that of my application to the path and
Pythonpath in the windows environ variables.
But the same problems arise.

So, I tried to load the normal 2.5 Idle and unload ('remove') everything related
to 2.6 from sys.path, but it's strangely not working completely.

Finally, I managed to run the program :
- by launching D:\python25\python.exe -E -S in a console (which seems to prevent
python from loading the paths)
- then appending the application path to sys.path
but it's really not fun working with this bloody windows console where cut and
paste is impossible...

So, here is my question:
How can I force py2.5 to go and find the dependencies only in the 2.5
site-packages ?

Thanks in advance for your help.

Dominique

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple Python Problem

2010-09-06 Thread Alan Gauld


"Keith Lucas"  wrote

What is wrong with the following, apparently almost straight out of 
Python Programming

by Michael Dawson?



You are using Python v2, the tutorial seems to be written for v3.
There are big diffeernces in syntax between them, v3 is NOT
backwards compatible with v2.


# Get value.
name = input("What is your name? ")


In v2 that would be

name = raw_input("What is your name")

Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit 
(Intel)] on win32 Type

"copyright", "credits" or "license()" for more information.
 RESTART 


What is your name? Keith


I think there is a trick in V2.7 to make it act more like v3 but 
someone

else will need to tell you what it is... :-)

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] why do i get None as output

2010-09-06 Thread Francesco Loffredo

On 06/09/2010 8.34, Roelof Wobben wrote:

Hello,

I have this programm:
...
def make_empty(seq):
"""
 >>> make_empty([1, 2, 3, 4])
[]
 >>> make_empty(('a', 'b', 'c'))
()
 >>> make_empty("No, not me!")
''
"""
word2=""
teller=0
if type(seq) == type([]):
teller=0
while teller < len(seq):
seq[teller]=""
teller = teller + 1
elif type(seq) == type(()):
tup2 = list (seq)
while teller > tup2.len():
tup2[teller]=""
teller = teller + 1
seq = tuple(tup2)
else:
seq = ""

test = make_empty([1, 2, 3, 4])
print test

But now I get None as output instead of []


I would add a line like:

return seq

at the end of the  make_empty  function.



Can anyone explain why that happens ?
I think Python doesn't know what exactly is the value you need to 
receive from the  make_empty  function. That's why I'd make it clear. 
Otherwise, you know what happens...


I quote the following from
http://diveintopython.org/getting_to_know_python/declaring_functions.html
"In fact, every Python function returns a value; if the function ever 
executes a return statement, it will return that value, otherwise it 
will return None, the Python null value."



Roelof

Francesco
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.851 / Database dei virus: 271.1.1/3115 -  Data di rilascio: 
09/05/10 08:34:00
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple Python Problem

2010-09-06 Thread Bill Allen
>
>
>  Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)]
>> on win32 Type
>> "copyright", "credits" or "license()" for more information.
>>
>>>  RESTART 
>
 What is your name? Keith
>>
>
> I think there is a trick in V2.7 to make it act more like v3 but someone
> else will need to tell you what it is... :-)
>
>
Other than changing the input() to raw_input() for Python 2 compatibility,
the following statement could be added to the beginning of the program to
allow your Python 2 program to use the Python 3 style print function.

from __future__ import print_function


-Bill
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multiple versions of python and paths problems

2010-09-06 Thread David Hutto
On Mon, Sep 6, 2010 at 1:46 PM, Dominique  wrote:
> Hello,
>
> I usually use python 2.6 and several packages. Everything's fine.
>
> At present, I'm trying to run a package which is only available with python 
> 2.5.
> So, i installed 2.5 and the various dependencies needed to run this package:
> PIL, numpy... which were already installed in my 2.6 site-packages.
>
> Unfortunately, when I try to run it under Idle 2.5, python goes in the 2.6
> site-packages to get these dependencies (PIL,...) and throws me a traceback 
> (due
> to incompatibilities).
>
> I understand it is a paths problem.
>
> So, I added the path of python 2.5 and that of my application to the path and
> Pythonpath in the windows environ variables.
> But the same problems arise.
>
> So, I tried to load the normal 2.5 Idle and unload ('remove') everything 
> related
> to 2.6 from sys.path, but it's strangely not working completely.
>
> Finally, I managed to run the program :
> - by launching D:\python25\python.exe -E -S in a console (which seems to 
> prevent
> python from loading the paths)
> - then appending the application path to sys.path
> but it's really not fun working with this bloody windows console where cut and
> paste is impossible...
>
> So, here is my question:
> How can I force py2.5 to go and find the dependencies only in the 2.5
> site-packages ?
>
> Thanks in advance for your help.
>
> Dominique
>
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
forgot to hit reply all
>From wht the ole swiss cheese kinda recalls, just cd into the 2.5 main
dir from the windows command propmpt, and then you should be able to
type python /path/to/2.5/idlelib/idle.py, or whatever is on your
system.

If that's not it, then let me know, and I'll switch os's to make sure
what it was.

Also, there is a list specifically for window's python. pywin32.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exercise correct ??

2010-09-06 Thread Sander Sweers
On 6 September 2010 19:32, Roelof Wobben  wrote:
> def index_of(val, seq, start=0):
>     """
>   >>> index_of(9, [1, 7, 11, 9, 10])
>   3
>   >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5))
>   3
>   >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
>   6
>   >>> index_of('y', 'happy birthday')
>   4
>   >>> index_of('banana', ['apple', 'banana', 'cherry', 'date'])
>   1
>   >>> index_of(5, [2, 3, 4])
>   -1
>   >>> index_of('b', ['apple', 'banana', 'cherry', 'date'])
>   -1
>     """
>     plek = 0
>     if type(seq) == type([]):
>     plek = seq.index(val)
>     elif type(seq) == type(()):
>     seq = list (seq)
>     plek = seq.index(val)
>     else :
>     plek = seq.find(val)
>     return plek

Not sure if this is correct but why don't you check for the index
attribute? It is part of both lists and strings. Also you can use
try/except to catch a ValueError. My version below, but I dislike the
list() usage...

def index_of(val, seq, start=0):
if hasattr(seq, 'index'):
try:
return seq.index(val, start)
except ValueError:
return -1
else:
try:
return list(seq).index(val, start)
except ValueError:
return -1

> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 70, in
> __main__.index_of
>
> Failed example:
>
> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
>
> Expected:
>
> 6
>
> Got:
>
> 3
>
> But in that tuple 5 is on position 3.
>
> Is the exercise here wrong ?

Looks like it, or it's a typo.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exercise correct ??

2010-09-06 Thread Walter Prins
Hi Roelof,

On 6 September 2010 18:32, Roelof Wobben  wrote:

>>>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
>   6
>
> But in that tuple 5 is on position 3.
>
> Is the exercise here wrong ?
>
>

Not neccesarily...  I notice that the call is similar to the previous test
case, but has an extra parameter "4",  and that but that tuple that's being
searched contains other 5's.  If the extra parameter is interpreted as a
"starting index", then the next index of "5" starting at position 4, would
indeed be 6.  If my guesstimated intention of the test paramters is correct
then there's nothing wrong with the excercise/test and your implementation
of index_of needs to be enhanced to properly handle this extra parameter/new
test case.

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple Python Problem

2010-09-06 Thread ALAN GAULD
> > I think there is a trick in V2.7 to make it act more like v3 but someone 
> > else will need to tell you what it is... :-)

>Other than changing the input() to raw_input() for Python 2 compatibility,  

And of course you can do that using

input = raw_input

> the following statement could be added to the beginning of the program 
> to allow your Python 2 program to use the Python 3 style print function.

from __future__ import print_function
>That would help.
I wonder if we could create a module that would make v2.7 simulate v3 to 
a close degree? hmm... And is it sensible to try, should we not perhaps
just accept the difference?


Alan G.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exercise correct ??

2010-09-06 Thread Roelof Wobben


 

> Date: Mon, 6 Sep 2010 21:45:17 +0200
> Subject: Re: [Tutor] exercise correct ??
> From: sander.swe...@gmail.com
> To: rwob...@hotmail.com
> CC: tutor@python.org
> 
> On 6 September 2010 19:32, Roelof Wobben  wrote:
> > def index_of(val, seq, start=0):
> > """
> >   >>> index_of(9, [1, 7, 11, 9, 10])
> >   3
> >   >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5))
> >   3
> >   >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
> >   6
> >   >>> index_of('y', 'happy birthday')
> >   4
> >   >>> index_of('banana', ['apple', 'banana', 'cherry', 'date'])
> >   1
> >   >>> index_of(5, [2, 3, 4])
> >   -1
> >   >>> index_of('b', ['apple', 'banana', 'cherry', 'date'])
> >   -1
> > """
> > plek = 0
> > if type(seq) == type([]):
> > plek = seq.index(val)
> > elif type(seq) == type(()):
> > seq = list (seq)
> > plek = seq.index(val)
> > else :
> > plek = seq.find(val)
> > return plek
> 
> Not sure if this is correct but why don't you check for the index
> attribute? It is part of both lists and strings. Also you can use
> try/except to catch a ValueError. My version below, but I dislike the
> list() usage...
> 
> def index_of(val, seq, start=0):
> if hasattr(seq, 'index'):
> try:
> return seq.index(val, start)
> except ValueError:
> return -1
> else:
> try:
> return list(seq).index(val, start)
> except ValueError:
> return -1
> 
> > File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 70, in
> > __main__.index_of
> >
> > Failed example:
> >
> > index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
> >
> > Expected:
> >
> > 6
> >
> > Got:
> >
> > 3
> >
> > But in that tuple 5 is on position 3.
> >
> > Is the exercise here wrong ?
> 
> Looks like it, or it's a typo.
> 
> Greets
> Sander


Hello Sander, 

 

I agree that index is a part of string and list.

But not a part of a tuple.

As far as I know index is not a part of tuple so I have to convert it to a list 
so I can use index.

 

Roelof
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exercise correct ??

2010-09-06 Thread Sander Sweers
On 6 September 2010 22:28, Roelof Wobben  wrote:
> As far as I know index is not a part of tuple so I have to convert it to a
> list so I can use index.

As of version 2.6/3 a tuple does have index(). Not sure which version
you are using.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple Python Problem

2010-09-06 Thread Bill Allen
>Other than changing the input() to raw_input() for Python 2 compatibility,
>
>
> And of course you can do that using
>
> input = raw_input
>
>
> > the following statement could be added to the beginning of the program
> > to allow your Python 2 program to use the Python 3 style print function.
>
> from __future__ import print_function
>
> That would help.
> I wonder if we could create a module that would make v2.7 simulate v3 to
> a close degree? hmm... And is it sensible to try, should we not perhaps
> just accept the difference?
>
> Alan G.
>
>  Ah!  I did not know that input = raw_input would work, thanks!

I am sure someone could create such.  However, to me, it would be more
sensible to just program in v3.  I have decided to code in only v3 since I
do not have any previous code base to maintain and am still very much in
learning mode.   It seems that some of the more popular external modules
such as NumPy and PyGame are also now v3 compatible.

By the way, even though I am far from proficient with Python, it has already
become a useful tool for me at work!

-Bill
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exercise correct ??

2010-09-06 Thread Sander Sweers
On 6 September 2010 21:45, Sander Sweers  wrote:
>> Is the exercise here wrong ?
>
> Looks like it, or it's a typo.

Now that I had a better look the test is correct. Now it is up to you
to figure out why your index_of() fails. Walter gave you a good hint.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] slicing a string

2010-09-06 Thread lists
Hi guys,

Continuing my Python learning, I came across an exercise which asks me
to take a string and reverse it.

I understand that there is a function to do this i.e mytext.reverse()

I imagine that the exercise author would rather I did this the hard
way however. ;-)

Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
doesn't work (as I expected it to) but that mytext[::-1] does.

While that's fine, I just wondered why mytext[-1:-4:-1] doesn't work?

Thanks again,

Chris
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slicing a string

2010-09-06 Thread Sander Sweers
On 7 September 2010 00:14, lists  wrote:
> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
> doesn't work (as I expected it to) but that mytext[::-1] does.
>
> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't work?

How does it not "work"? What did you expect to happen? What did it do instead?

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exercise correct ??

2010-09-06 Thread Alan Gauld


"Roelof Wobben"  wrote

#
def index_of(val, seq, start=0):
   """
 >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
 6
   """

But I get this message :
Failed example:
index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
Expected:
6
Got:
3
#


But in that tuple 5 is on position 3.
Is the exercise here wrong ?


No because the start position is 4 so you don;t see the 5 in position 
3.


HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multiple versions of python and paths problems

2010-09-06 Thread Alan Gauld

"Dominique"  wrote


So, I tried to load the normal 2.5 Idle and unload ('remove') 
everything related

to 2.6 from sys.path, but it's strangely not working completely.


How do you start IDLE? Is it via a desktop or start menu shortcut?
If so what is the startin folder specified as?

What happens when you run it from the command ine with no extra
parameters - what error do you get?

Do you have both versions of Python in your environment variables?
In which order?
Hint: Start a DOS session and type
SET PYTHONPATH
and
SET PATH


Finally, I managed to run the program :
- by launching D:\python25\python.exe -E -S in a console (which 
seems to prevent
python from loading the paths) - then appending the application path 
to sys.path
but it's really not fun working with this bloody windows console 
where cut and

paste is impossible...


Set the Quick Edit option for the terminal it will save you a lot of 
pain.

Cut n paste are then possible. In fact you should probably read the
Windows help on CMD too because there are a lot of settings/registry
tweaks that improves the use of the CMD prompt dramatically.
Also look at the WindowsPowerShell - it has a lot of this "out of the 
box"


But that aside you shouldn't have to do all this!

How can I force py2.5 to go and find the dependencies only in the 
2.5

site-packages ?


There are probably several ways round it, including creating a local 
startup file.


But if the paths are right it should work, and you may need to create 
a startup

DOS file to set them before executing python...

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slicing a string

2010-09-06 Thread Alan Gauld


"lists"  wrote


Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
doesn't work (as I expected it to) but that mytext[::-1] does.

While that's fine, I just wondered why mytext[-1:-4:-1] doesn't 
work?


It does work.
But remember that slices give you the first item to one less
than the second index, so for a 4 letter word you need an
index of of -5...


"test"[-1:-4:-1]

'tse'

"test"[-1:-5:-1]

'tset'




HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slicing a string

2010-09-06 Thread lists
>> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
>> doesn't work (as I expected it to) but that mytext[::-1] does.
>>
>> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't work?
>
> How does it not "work"? What did you expect to happen? What did it do instead?
>
> Greets
> Sander
>

Hi, assuming mytext is "test", word[-1:-4:-1] returns tse

My understanding of how the index works on test would be:

0  1  2  3
t   e  s   t
-4 -3 -2 -1

So I just wasn't clear on what happened to the last 't' I expected to see.

Cheer,

Chris
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slicing a string

2010-09-06 Thread lists
>>> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
>>> doesn't work (as I expected it to) but that mytext[::-1] does.
>>>
>>> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't work?
>>
>> How does it not "work"? What did you expect to happen? What did it do 
>> instead?
>>
>> Greets
>> Sander
>>
>
> Hi, assuming mytext is "test", word[-1:-4:-1] returns tse
>
> My understanding of how the index works on test would be:
>
> 0  1  2  3
> t   e  s   t
> -4 -3 -2 -1
>
> So I just wasn't clear on what happened to the last 't' I expected to see.
>
> Cheer,
>
> Chris
>

Sorry I mean mytext[-1:-4:-1] not word[-1:-4:-1] :-S
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slicing a string

2010-09-06 Thread Steven D'Aprano
On Tue, 7 Sep 2010 08:14:59 am lists wrote:
> Hi guys,
>
> Continuing my Python learning, I came across an exercise which asks
> me to take a string and reverse it.
>
> I understand that there is a function to do this i.e mytext.reverse()

You understand wrong :)

There is a function reversed() which takes any iterable object (a list, 
a string, a tuple, a set, ...) and returns an iterator that yields the 
items in reverse order:

>>> reversed("test")



but that's not useful in this case.


> I imagine that the exercise author would rather I did this the hard
> way however. ;-)
>
> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
> doesn't work (as I expected it to) but that mytext[::-1] does.
>
> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't work?

Remember that slice indexes fall *between* characters:


A slice of [-1:-4:-1] is equivalent to [3:0:-1].

>>> 'Test'[-1:-4:-1]
'tse'
>>> 'Test'[3:0:-1]
'tse'

So, what does this slice do? The slice indexes are equivalent to:

range(3, 0, -1)
=> [3, 2, 1]

Remember that the end position is excluded! Hence you reverse all the 
characters in the string *except* the first.


-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple Python Problem

2010-09-06 Thread Steven D'Aprano
On Tue, 7 Sep 2010 06:02:39 am ALAN GAULD wrote:
> I wonder if we could create a module that would make v2.7 simulate v3
> to a close degree? hmm... And is it sensible to try, should we not
> perhaps just accept the difference?

from __future__ import print_function, unicode_literals
from future_builtins import *


will get you part of the way, but it's probably impossible to get the 
two to be *exactly* the same.

-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Arguments from the command line

2010-09-06 Thread Steven D'Aprano
On Tue, 7 Sep 2010 02:08:27 am Hugo Arts wrote:

> sys.argv is a list of all arguments from the command line. However,
> you'll rarely deal with it directly, there's various modules that
> deal with handling arguments. I believe the current one is argparse:
> http://docs.python.org/library/argparse.html#module-argparse

In my experience, getopt is a gentler introduction to argument parsing, 
because it does much less :)

optparse is another good one.

All three are available up to Python 2.7, and possibly in 3.1 as well, I 
haven't checked.


-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slicing a string

2010-09-06 Thread Andre Engels
On Tue, Sep 7, 2010 at 12:44 AM, lists  wrote:
>>> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
>>> doesn't work (as I expected it to) but that mytext[::-1] does.
>>>
>>> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't work?
>>
>> How does it not "work"? What did you expect to happen? What did it do 
>> instead?
>>
>> Greets
>> Sander
>>
>
> Hi, assuming mytext is "test", word[-1:-4:-1] returns tse
>
> My understanding of how the index works on test would be:
>
> 0  1  2  3
> t   e  s   t
> -4 -3 -2 -1
>
> So I just wasn't clear on what happened to the last 't' I expected to see.


>>> "test"[0:3]
'tes'

[m:n] shows the elements from m upto but excluding n.


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] setattr vs __setattr__

2010-09-06 Thread Steven D'Aprano
On Mon, 6 Sep 2010 09:03:30 pm Rasjid Wilcox wrote:
> I've been using
>
> for attr_name in name_list:
> setattr(a, attr_name, getattr(b, attr_name))
>
> to copy the attributes from one type of class to another, and it is
> not quite as readable as I would like.

The one-liner in the for loop is very concise. The problem is that 
concise is often the opposite of readable. So make it less concise:


for name in name_list:
obj = getattr(b, name)
setattr(a, name, obj)

Does that help?

Another alternative, depending on the class, *might* be this:

a.__dict__.update(b.__dict__)

although that's a hack, and like all hacks, may not do what you expect 
for all classes.


> Actually, I've just thought 
> that the best option would be to make both classes dictionary like
> objects with automatic translation between a['foo'] and a.foo.

How does that help you copy from one class to another? As I see it, it 
just adds more noise to the class.


-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multiple versions of python and paths problems

2010-09-06 Thread Dave Angel



On 2:59 PM, Dominique wrote:

=
but it's really not fun working with this bloody windows console where cut and
paste is impossible...


Cut and paste work fine in a Windows DOS console.   Using Properties, 
the Options tab, turn on Quick-Edit mode.  Once you've done that, you 
can select a rectangle of text in such a console by using click/drag.  
Then you copy it to the clipboard with right click.


If you need to paste into the command line, something that's already in 
the clipboard, you can again use right click.


It's also possible to do copy or past without changing any properties -- 
just use the right-click on the title bar. to mark, then copy, or to paste.


DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Arguments from the command line

2010-09-06 Thread aug dawg
Alrighty! Thanks, everyone!


On Mon, Sep 6, 2010 at 6:48 PM, Steven D'Aprano  wrote:

> On Tue, 7 Sep 2010 02:08:27 am Hugo Arts wrote:
>
> > sys.argv is a list of all arguments from the command line. However,
> > you'll rarely deal with it directly, there's various modules that
> > deal with handling arguments. I believe the current one is argparse:
> > http://docs.python.org/library/argparse.html#module-argparse
>
> In my experience, getopt is a gentler introduction to argument parsing,
> because it does much less :)
>
> optparse is another good one.
>
> All three are available up to Python 2.7, and possibly in 3.1 as well, I
> haven't checked.
>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] setattr vs __setattr__

2010-09-06 Thread Rasjid Wilcox
On 7 September 2010 08:55, Steven D'Aprano  wrote:
> On Mon, 6 Sep 2010 09:03:30 pm Rasjid Wilcox wrote:
>> I've been using
>>
>> for attr_name in name_list:
>>     setattr(a, attr_name, getattr(b, attr_name))
>>
>> to copy the attributes from one type of class to another, and it is
>> not quite as readable as I would like.
>
> The one-liner in the for loop is very concise. The problem is that
> concise is often the opposite of readable. So make it less concise:
>
> for name in name_list:
>    obj = getattr(b, name)
>    setattr(a, name, obj)
>
> Does that help?

Yes, that does help.  Such a simple and obvious thing (once someone
has pointed it out) and addresses my concern with the one-liner that
while easy to write, when looking back at it one has to look carefully
and analyse it to be certain about what is going on.  The two liner
has a few more keystrokes but is much easier on the eyes.  And easy on
the eyes is important to me - it is why I find Python 'beautiful' in a
way that most programming languages are not.

Much thanks,

Rasjid.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor