Re: [Tutor] Immutable objects

2010-08-19 Thread Alan Gauld


"Nitin Das"  wrote 


class mymut(object):

 def __setattr__(self,k,v):
 if hasattr(self,k):
 if self.__dict__.get(k) == None:
 self.__dict__[k] = v


Do you need to look up the dict? 
Surely you could just use


if self.k is None
  self.k = v

which looks a lot simpler to me...


 else:
 raise TypeError("Cant Modify Attribute Value")


You could mention the class for example.
Compare it with the string and tuple messages:


'fred'[2] = 'g'

Traceback (most recent call last):
 File "", line 1, in 
TypeError: 'str' object does not support item assignment


(1,2,30)[1] = 5

Traceback (most recent call last):
 File "", line 1, in 
TypeError: 'tuple' object does not support item assignment




So if your error said 
TypeError: mymut object does not support item assignment


that would be more consistent with the Python internal objects.


 else:
 raise TypeError("Immutable Object")


The Python immutables seem to raise an Attribute Error here 
rather than a Type error. And again mentioning the class name 
makes debugging easier:



'l'.x = 4

Traceback (most recent call last):
 File "", line 1, in 
AttributeError: 'str' object has no attribute 'x'




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] question about a exercise.

2010-08-19 Thread Roelof Wobben

Hello, 

 

I follow the online book " How to think like a computer scientist".

But now I have a problem with a exercise.

This is not homework.

 

The exercise is :

 

Using a text editor, create a Python script named tryme3.py . Write a function 
in this file called nine_lines that uses three_lines to print nine blank lines. 
Now add a function named clear_screen that prints out twenty-five blank lines. 
The last line of your program should be a call to clear_screen.

 

So I begin with this code :

 

def threelines():
print 
print  
print  

 

print "regel 1"
threelines() 
print "regel 2"

 

But now I get a terminated at line 2 message.

What did I do wrong.

 

I work on a Win7 machine with python 2.7 and as a editor SPE.

 

Regards,

 

Roelof

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


[Tutor] AUTO: James D Mcclatchey is out of the office. (returning 09/07/2010)

2010-08-19 Thread James D Mcclatchey


I am out of the office until 09/07/2010.

I will respond to your message when I return.


Note: This is an automated response to your message  "Tutor Digest, Vol 78,
Issue 83" sent on 8/19/10 3:00:03.

This is the only notification you will receive while this person is away.
*IMPORTANT NOTICE: This communication, including any attachment, contains 
information that may be confidential or privileged, and is intended solely for 
the entity or individual to whom it is addressed.  If you are not the intended 
recipient, you should delete this message and are hereby notified that any 
disclosure, copying, or distribution of this message is strictly prohibited.  
Nothing in this email, including any attachment, is intended to be a legally 
binding signature.
*
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Immutable objects

2010-08-19 Thread Steven D'Aprano
On Thu, 19 Aug 2010 01:24:11 pm Nitin Das wrote:
> Hello,
>
>  Can somebody help me how to make immutable objects in python. I
> have seen overriding the __new__, __setattr__ methods.. but not
> comfortable with how to use them to make the object immutable.
>
> thanks in advance
> --nitin

I have found this useful:


http://northernplanets.blogspot.com/2007/01/immutable-instances-in-python.html

Keep in mind that the only way to make *truly* immutable objects in 
Python is to write them in C. Immutability of pure-Python objects can 
be broken if you try hard enough. Immutability is by cooperation, not 
enforced.



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


Re: [Tutor] question about a exercise.

2010-08-19 Thread Joel Goldstick
Can you copy and paste the exact error message you receive in the traceback
when you run your program.  Also, copy the complete program here since it is
only a handful of lines

On Thu, Aug 19, 2010 at 7:31 AM, Roelof Wobben  wrote:

>  Hello,
>
> I follow the online book " How to think like a computer scientist".
> But now I have a problem with a exercise.
> This is not homework.
>
> The exercise is :
>
> Using a text editor, create a Python script named tryme3.py . Write a
> function in this file called nine_lines that uses three_lines to print
> nine blank lines. Now add a function named clear_screen that prints out
> twenty-five blank lines. The last line of your program should be a *call*to
> clear_screen.
>
> So I begin with this code :
>
> def threelines():
> print
> print
> print
>
> print "regel 1"
> threelines()
> print "regel 2"
>
> But now I get a terminated at line 2 message.
> What did I do wrong.
>
> I work on a Win7 machine with python 2.7 and as a editor SPE.
>
> Regards,
>
> Roelof
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


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


Re: [Tutor] Immutable objects

2010-08-19 Thread Peter Otten
Nitin Das wrote:

> class mymut(object):
> 
>   def __setattr__(self,k,v):
>   if hasattr(self,k):
>   if self.__dict__.get(k) == None:
>   self.__dict__[k] = v
>   else:
>   raise TypeError("Cant Modify Attribute Value")
>   else:
>   raise TypeError("Immutable Object")
> 
> 
> class mm(mymut):
> x = ''
> y = ''
> def __init__(self,x,y):
> self.x = x
> self.y = y
> 
> 
> 
> p = mm(10,11)
> print p.x
> print p.y
> 
> 
> I have created this immutable object.Is there any other better
> implementation?

How about

>>> from collections import namedtuple
>>> Mm = namedtuple("Mm", "x y")
>>> p = Mm(10, 11)
>>> p.x
10
>>> p.y
11
>>> p.x = 42
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: can't set attribute
>>> p.z = 42
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'Mm' object has no attribute 'z'
>>>

Peter

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


Re: [Tutor] question about a exercise.

2010-08-19 Thread Roelof Wobben

Hello, 

 

I don't see a traceback only this output.

 

regel 1 

 

 

regel 2 

script terminated.

 

And the code I gave you was the whole code because Im still working on this one.

I have learned to do one problem at the time so in mu opion first make the part 
which prints out 3 lines and then expand to 9 lines and then expand to the 
function clear_screen 

 

 

Roelof

 

 


Date: Thu, 19 Aug 2010 08:37:25 -0400
Subject: Re: [Tutor] question about a exercise.
From: joel.goldst...@gmail.com
To: rwob...@hotmail.com
CC: tutor@python.org

Can you copy and paste the exact error message you receive in the traceback 
when you run your program.  Also, copy the complete program here since it is 
only a handful of lines


On Thu, Aug 19, 2010 at 7:31 AM, Roelof Wobben  wrote:


Hello, 
 
I follow the online book " How to think like a computer scientist".
But now I have a problem with a exercise.
This is not homework.
 
The exercise is :
 
Using a text editor, create a Python script named tryme3.py . Write a function 
in this file called nine_lines that uses three_lines to print nine blank lines. 
Now add a function named clear_screen that prints out twenty-five blank lines. 
The last line of your program should be a call to clear_screen.
 
So I begin with this code :
 
def threelines():
print 
print  
print  
 
print "regel 1"
threelines() 
print "regel 2"
 
But now I get a terminated at line 2 message.
What did I do wrong.
 
I work on a Win7 machine with python 2.7 and as a editor SPE.
 
Regards,
 
Roelof
 

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



-- 
Joel Goldstick

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


Re: [Tutor] Immutable objects

2010-08-19 Thread Peter Otten
Peter Otten wrote:

> Nitin Das wrote:
> 
>> class mymut(object):
>> 
>>   def __setattr__(self,k,v):
>>   if hasattr(self,k):
>>   if self.__dict__.get(k) == None:
>>   self.__dict__[k] = v
>>   else:
>>   raise TypeError("Cant Modify Attribute Value")
>>   else:
>>   raise TypeError("Immutable Object")
>> 
>> 
>> class mm(mymut):
>> x = ''
>> y = ''
>> def __init__(self,x,y):
>> self.x = x
>> self.y = y
>> 
>> 
>> 
>> p = mm(10,11)
>> print p.x
>> print p.y
>> 
>> 
>> I have created this immutable object.Is there any other better
>> implementation?
> 
> How about
> 
 from collections import namedtuple
 Mm = namedtuple("Mm", "x y")
 p = Mm(10, 11)
 p.x
> 10
 p.y
> 11
 p.x = 42
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: can't set attribute
 p.z = 42
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: 'Mm' object has no attribute 'z'


By the way, you can see the class definition with

namedtuple("Mm", "x y", verbose=True)

Peter

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


Re: [Tutor] question about a exercise.

2010-08-19 Thread Alan Gauld


"Roelof Wobben"  wrote


I don't see a traceback only this output.


That looks about right to me, what did you expect to see that was 
different?



regel 1





regel 2

script terminated.
=

I have learned to do one problem at the time so in mu opion first 
make
the part which prints out 3 lines and then expand to 9 lines and 
then

expand to the function clear_screen


Yes thats good thinking.

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 file open

2010-08-19 Thread nitin chandra
Hello All,



>> Please guide with the syntax.
>
> All beginners tutorials on the web teach the syntax of python.. I am
> unsure what your questions is.

My bad  with code.

>
>> below is the existing program with Formula A (Mean). Formula B will be
>> Extrapolation,
>> also I have not been able to do justice to 'except IOError:' part.The
>
> It has many errors which need fixing but..
>
>> program ends with an error.
>
> And if you get an error always make sure you provide it to this list.
> People on this list can not read minds ;-).

I was wondering ... what else i need to post. Thank you. I REALLY need
to keep that in mind.

>
>> 
>> import sys,os, fileinput
>>
>>
>> file11 = raw_input('Enter PR1 File name :')
>> fp1 = open(file11,'r')
>>
>> file12 = raw_input('Enter PR3 File Name :')
>> fp2 = open(file12,'r')
>>
>> file3 = raw_input('Enter PR2 / PR4 OUTPUT File Name :')
>> fp3 = open(file3,'w')
>
> What happens when you enter a wrong filename? It will raise IOError
> the moment you use open(). Below is 1 example of what you might want
> tot do.
>
> file11 = raw_input('Enter PR1 File name :')
> try:
>    fp1 = open(ffile11, 'r')
> except IOError:
>   sys.exit('Could not open file: %s' % file11)
>

Adding this 'try-except'


>> while True:
>>   try:
>>       line1A = fp1.readline()
>
> You can read and split the line in 1 go.
>         line1 = fp1.readline().split(",")

:) so much better ... adding again.

>
>>       line1B = fp2.readline()
>>       line1 = line1A.split(",")
>
> You can now remove the above, see earlier comment.
>
>>       col1 = line1[0]
>>       col2 = line1[1]
>>       col3 = line1[2]
>>       col4 = line1[3]
>>       col5 = line1[20]
>>       col6 = line1[21]
>>       col7 = line1[22]
>>       line2 = line1B.split(",")
>>       col8 = line2[1]
>>       col9 = line2[2]
>>       col10 = line2[3]
>>       col11 = line2[20]
>>       col12 = line2[21]
>>       col13 = line2[22]
>
> Above you create a list "line1 = fp1.readline().split(",")". Lists are
> mutable so you can add, remove and insert new items. You can also
> access the items in the list by index. You can even add 2 lists to
> make a new list, eg: .
>
 [1,2,3,4,5] + [6,7,8,9,0]
> [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>
> Now try and apply this to all your col variables.

Actually I needed to do further computation, therefore I preferred to
keep the values separate.

>
>>       # calculation of PR2 as per formula
>>       #(A+B)/2 , ie. Mean of the two values
>>       col14 = ( (float(col2)) + (float(col8)) / 2)
>
> You can write this as:
>  col14 = (float(line1[1])) + (float(line2[1])) / 2)

I did this in one of my attempts. Pl dont ask me what was the error.
Did not save.

>
> And avoid creating all these col variables. But what would happen if
> col2/line1[1] has a value of "I am not a number"? Do note the comment
> below on the actual calculation.

I am keeping (cleaning) the Input data file as per the program.

>
>>       col15 = ( (float(col3)) + (float(col9)) / 2)
> 
>>       col19 = ( (float(col7)) + (float(col13)) / 2)
>
> Your "mean" calculation is wrong (hint, division has precedence over adding).

THANKS  aarrhh ... I missed another pair of braces.


>
> Greets
> Sander
>

Once the Final version is over will post it.

Thanks

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


Re: [Tutor] Immutable objects

2010-08-19 Thread Nitin Das
Thanks guys,
NamedTuple implementation is preety nice solution.

--nitin

On Thu, Aug 19, 2010 at 6:28 PM, Peter Otten <__pete...@web.de> wrote:

> Peter Otten wrote:
>
> > Nitin Das wrote:
> >
> >> class mymut(object):
> >>
> >>   def __setattr__(self,k,v):
> >>   if hasattr(self,k):
> >>   if self.__dict__.get(k) == None:
> >>   self.__dict__[k] = v
> >>   else:
> >>   raise TypeError("Cant Modify Attribute Value")
> >>   else:
> >>   raise TypeError("Immutable Object")
> >>
> >>
> >> class mm(mymut):
> >> x = ''
> >> y = ''
> >> def __init__(self,x,y):
> >> self.x = x
> >> self.y = y
> >>
> >>
> >>
> >> p = mm(10,11)
> >> print p.x
> >> print p.y
> >>
> >>
> >> I have created this immutable object.Is there any other better
> >> implementation?
> >
> > How about
> >
>  from collections import namedtuple
>  Mm = namedtuple("Mm", "x y")
>  p = Mm(10, 11)
>  p.x
> > 10
>  p.y
> > 11
>  p.x = 42
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > AttributeError: can't set attribute
>  p.z = 42
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > AttributeError: 'Mm' object has no attribute 'z'
> 
>
> By the way, you can see the class definition with
>
> namedtuple("Mm", "x y", verbose=True)
>
> Peter
>
> ___
> 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


[Tutor] List comprehension for dicts?

2010-08-19 Thread Pete
Hi,

I've been reading up on list comprehensions lately, all userful and powerful 
stuff - trying to wrap my brain around it :)

As the examples all seem to relate to lists, I was wondering if there is an 
elegant similar way to apply a function to all keys in a dictionary?

(without looping over it, of course)

I'm trying to convert all keys in a dict to uppercase, as in:

INPUT:
age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 }

OUTPUT:
age_dict = { 'PETE': 42, 'ANN': 25, 'CARL': 30, 'AMANDA': 64 }

I googled 'dictionary comprehension' but couldn't get any code to work with the 
examples given.

http://www.siafoo.net/article/52#dictionary-comprehensions

thanks,

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


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Vince Spicer
Hey you can use list comprehension here

age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 }

you can create a dict from a list of tuples and you can access the dict as
a
list of tuples by accessing its items

Example:

age_dict = dict([(key.upper(), value) for key,value in age_dict.items()])

hope that helps,

Vince

On Thu, Aug 19, 2010 at 8:51 AM, Pete  wrote:

> Hi,
>
> I've been reading up on list comprehensions lately, all userful and
> powerful stuff - trying to wrap my brain around it :)
>
> As the examples all seem to relate to lists, I was wondering if there is an
> elegant similar way to apply a function to all keys in a dictionary?
>
> (without looping over it, of course)
>
> I'm trying to convert all keys in a dict to uppercase, as in:
>
> INPUT:
> age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 }
>
> OUTPUT:
> age_dict = { 'PETE': 42, 'ANN': 25, 'CARL': 30, 'AMANDA': 64 }
>
> I googled 'dictionary comprehension' but couldn't get any code to work with
> the examples given.
>
> http://www.siafoo.net/article/52#dictionary-comprehensions
>
> thanks,
>
> Pete
> ___
> 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] List comprehension for dicts?

2010-08-19 Thread Peter Otten
Pete wrote:

> Hi,
> 
> I've been reading up on list comprehensions lately, all userful and
> powerful stuff - trying to wrap my brain around it :)
> 
> As the examples all seem to relate to lists, I was wondering if there is
> an elegant similar way to apply a function to all keys in a dictionary?
> 
> (without looping over it, of course)
> 
> I'm trying to convert all keys in a dict to uppercase, as in:
> 
> INPUT:
> age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 }
> 
> OUTPUT:
> age_dict = { 'PETE': 42, 'ANN': 25, 'CARL': 30, 'AMANDA': 64 }
> 
> I googled 'dictionary comprehension' but couldn't get any code to work
> with the examples given.

Python 2.4-2.6
>>> dict((k.upper(), v) for k, v in age_dict.iteritems())
{'PETE': 42, 'ANN': 25, 'AMANDA': 64, 'CARL': 30}

Python 2.7
>>> {k.upper(): v for k, v in age_dict.iteritems()}
{'PETE': 42, 'ANN': 25, 'AMANDA': 64, 'CARL': 30}


Python 3.x
>>> {k.upper(): v for k, v in age_dict.items()}
{'PETE': 42, 'ANN': 25, 'AMANDA': 64, 'CARL': 30}


items() instead of iteritems() works in 2.x, too, but is less efficient.

Peter

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


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Wayne Werner
On Thu, Aug 19, 2010 at 10:02 AM, Vince Spicer  wrote:

> Hey you can use list comprehension here
>
>
> age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 }
>
> you can create a dict from a list of tuples and you can access the dict as
> a
> list of tuples by accessing its items
>
> Example:
>
> age_dict = dict([(key.upper(), value) for key,value in age_dict.items()])
>

This is a bad place to use a list comprehension. This will create a list of
values first and then create a dict from that list, so now you have a list
floating around that you didn't need.

Generator expressions, OTOH, generate the values on the fly, only as they're
needed, so there's no extra list left over once the dict is created.

Sure it will eventually be garbage collected, but "waste not, want not", as
my grandmother used to say.

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


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Shashwat Anand
On Thu, Aug 19, 2010 at 8:21 PM, Pete  wrote:

> Hi,
>
> I've been reading up on list comprehensions lately, all userful and
> powerful stuff - trying to wrap my brain around it :)
>
> As the examples all seem to relate to lists, I was wondering if there is an
> elegant similar way to apply a function to all keys in a dictionary?
>
> (without looping over it, of course)
>
> I'm trying to convert all keys in a dict to uppercase, as in:
>
> INPUT:
> age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 }
>
> OUTPUT:
> age_dict = { 'PETE': 42, 'ANN': 25, 'CARL': 30, 'AMANDA': 64 }
>
> I googled 'dictionary comprehension' but couldn't get any code to work with
> the examples given.
>
> http://www.siafoo.net/article/52#dictionary-comprehensions
>
> thanks,
>

There is dict comprehension too from python2.7 onwards.

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



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


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Steven D'Aprano
On Fri, 20 Aug 2010 01:40:54 am Wayne Werner wrote:

> > age_dict = dict([(key.upper(), value) for key,value in
> > age_dict.items()])
>
> This is a bad place to use a list comprehension. This will create a
> list of values first and then create a dict from that list, so now
> you have a list floating around that you didn't need.

How do you know that dict() doesn't need it the entire list at once? 
Unless you're an expert on the implementation, for all you know it 
looks something like this:

class dict:
def __new__(cls, arg):
...
try:
n = len(arg)
except AttributeError:
# probably a generator expression
arg = list(arg)
n = len(arg)
allocate_memory_for_items(n)
...

(only written in C). I'm not saying it does, or that it doesn't, but 
you're assuming a pattern of behaviour which might not be the case.

Here's a similarly common idiom: which of these is faster?

' '.join(gen_expr)
' '.join(list_comp)


[st...@sylar ~]$ python -m timeit "' '.join(str(n) for n in 
xrange(30))"
10 loops, best of 3: 437 msec per loop
[st...@sylar ~]$ python -m timeit "' '.join([str(n) for n in 
xrange(30)])"
10 loops, best of 3: 401 msec per loop

The list comprehension is consistently faster, because join() works more 
efficiently if it knows how many items it needs to pre-allocate memory 
for.


> Generator expressions, OTOH, generate the values on the fly, only as
> they're needed, so there's no extra list left over once the dict is
> created.

And sometimes that's a win, and sometimes it's not. 

Generator expressions are more computationally expensive than lists -- 
they're functions which remember their internal state so you can pause 
them and restart them at will. That doesn't happen for free -- it takes 
memory and time. The reason Python has generator expressions is that 
for large amounts of data, the saving you have by not needing to 
produce the entire list all at once more than makes up for the extra 
cost, but for small amounts of data, that's not always the case:

[st...@sylar ~]$ python -m timeit "dict((k,k+1) for k in xrange(2))"
10 loops, best of 3: 5.89 usec per loop
[st...@sylar ~]$ python -m timeit "dict([(k,k+1) for k in xrange(2)])"
10 loops, best of 3: 4.78 usec per loop


Here, using a generator expression is a pessimation, not an 
optimization.


> Sure it will eventually be garbage collected, but "waste not, want
> not", as my grandmother used to say.

Does your grandmother have a box labelled "Pieces of string, too short 
to use" as well?



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


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Dave Angel

(You top-posted, so now I have to delete the older part)

Vince Spicer wrote:

Hey you can use list comprehension here

age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 }

you can create a dict from a list of tuples and you can access the dict as
a
list of tuples by accessing its items

Example:

age_dict = dict([(key.upper(), value) for key,value in age_dict.items()])

hope that helps,

Vince

  
The only catch to that is that two or more of the keys may map to the 
same uppercase key.  If one needs to detect that, one has to write an 
explicit loop, rather than just converting with dict()


DaveA

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


[Tutor] flow problem with a exercise

2010-08-19 Thread Roelof Wobben

Hello, 

 

I have this exercise:

 

Now write the function is_odd(n) that returns True when n is odd and False 
otherwise. Include doctests for this function as you write it.
Finally, modify it so that it uses a call to is_even to determine if its 
argument is an odd integer.

 

So I thought of this :

 

def is_even(argument):
remainder= argument%2
if remainder == 0 :
return True
else :
return False


def is_odd(argument):
  uitkomst=is_even(argument)
return uitkomst
   

even=is_odd(1) ;
if even==True :
  print "Even getal"
if even==False:
print "Oneven getal"



But now I get this error message :

 

return uitkomst

Syntax error : return outside function.

 

 

In my opinon even calls is_odd , then uitkomst calls is_even which gives a true 
or false to uitkomst. So return uitkomst gives the outcome to even.

But the intepreter thinks otherwise.  

 

I work on a Win7 machine with Python 2.7

 

Roelof

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


Re: [Tutor] flow problem with a exercise

2010-08-19 Thread Joel Goldstick
On Thu, Aug 19, 2010 at 3:01 PM, Roelof Wobben  wrote:

>  Hello,
>
> I have this exercise:
>
>
> Now write the function is_odd(n) that returns True when n is odd and 
> Falseotherwise. Include doctests for this function as you write it.
> Finally, modify it so that it uses a call to is_even to determine if its
> argument is an odd integer.
>
> So I thought of this :
>
> def is_even(argument):
> remainder= argument%2
> if remainder == 0 :
> return True
> else :
> return False
>
> def is_odd(argument):
>   uitkomst=is_even(argument)
> return uitkomst
>

NOTE that your return statement is not indented properly.  It must line up
under uitkomst

>
> even=is_odd(1) ;
> if even==True :
>   print "Even getal"
> if even==False:
> print "Oneven getal"
>
>
> But now I get this error message :
>
> return uitkomst
> Syntax error : return outside function.
>
>
> In my opinon even calls is_odd , then uitkomst calls is_even which gives a
> true or false to uitkomst. So return uitkomst gives the outcome to even.
> But the intepreter thinks otherwise.
>
> I work on a Win7 machine with Python 2.7
>
> Roelof
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


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


Re: [Tutor] flow problem with a exercise

2010-08-19 Thread Wayne Werner
On Thu, Aug 19, 2010 at 2:01 PM, Roelof Wobben  wrote:

> 
>
def is_odd(argument):
>   uitkomst=is_even(argument)
> return uitkomst
>
> even=is_odd(1) ;
> if even==True :
>   print "Even getal"
> if even==False:
> print "Oneven getal"
>
>
> But now I get this error message :
>
> return uitkomst
> Syntax error : return outside function.
>

Check your indention. In the email your return is at a different level than
your function. Always use 4 spaces. If your editor can't convert, you need a
better editor!


>  In my opinon even calls is_odd , then uitkomst calls is_even which gives a
> true or false to uitkomst. So return uitkomst gives the outcome to even.
> But the intepreter thinks otherwise.
>

Well, good thing opinions don't count for much when talking to a computer ;)

You are correct that uitkomst contains the result of is_even, but your
return is on a different indention level. Whitespace is significant here.

If I were you, I would define is_odd this way:

def is_odd(argument):
uitkomst = not is_even(argument)
return uitkomst


>  I work on a Win7 machine with Python 2.7
>

Good job providing both the traceback and your system. They make every
problem easier to debug.

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


Re: [Tutor] flow problem with a exercise

2010-08-19 Thread Alex Hall
On 8/19/10, Roelof Wobben  wrote:
>
> Hello,
>
>
>
> I have this exercise:
>
>
>
> Now write the function is_odd(n) that returns True when n is odd and False
> otherwise. Include doctests for this function as you write it.
> Finally, modify it so that it uses a call to is_even to determine if its
> argument is an odd integer.
>
>
>
> So I thought of this :
>
>
>
> def is_even(argument):
> remainder= argument%2
> if remainder == 0 :
> return True
> else :
> return False
>
>
> def is_odd(argument):
>   uitkomst=is_even(argument)
> return uitkomst
The above line, the return statement, has to be indented; it did not
appear to be in your email. Also, maybe you want to return the
opposite of is_even in is_odd? Right now it looks like you are going
to get something like:
is_odd(3): is_even(3)=False, so is_odd(3) will echo that False. Maybe
return !uitkomst instead. I could have read it wrong, though.

>
>
> even=is_odd(1) ;
> if even==True :
>   print "Even getal"
> if even==False:
> print "Oneven getal"
>
>
>
> But now I get this error message :
>
>
>
> return uitkomst
>
> Syntax error : return outside function.
>
>
>
>
>
> In my opinon even calls is_odd , then uitkomst calls is_even which gives a
> true or false to uitkomst. So return uitkomst gives the outcome to even.
>
> But the intepreter thinks otherwise.
>
>
>
> I work on a Win7 machine with Python 2.7
>
>
>
> Roelof
>
>
>   


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] flow problem with a exercise

2010-08-19 Thread Dave Angel

Roelof Wobben wrote:



def is_odd(argument):
  uitkomst=is_even(argument)
return uitkomst
   

 



  
You forgot to indent the return statement to match the other 
statement(s) in the function.


DaveA

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


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Emile van Sebille

On 8/19/2010 7:51 AM Pete said...

Hi,

I've been reading up on list comprehensions lately, all userful and powerful 
stuff - trying to wrap my brain around it :)

As the examples all seem to relate to lists, I was wondering if there is an 
elegant similar way to apply a function to all keys in a dictionary?

(without looping over it, of course)


Just fyi, as it sounds you may not understand.  List Comprehensions loop 
over the list.  There's no other magic going on that avoids that.


result = [ ii for ii in lst if cond ]

is just shorthand for

result = []
for ii in lst:
  if cond:
result.append(ii)

Emile


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


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Pete
On 2010-08-19, at 5:25 PM, Emile van Sebille wrote:

> On 8/19/2010 7:51 AM Pete said...
>> Hi,
>> 
>> I've been reading up on list comprehensions lately, all userful and powerful 
>> stuff - trying to wrap my brain around it :)
>> 
>> As the examples all seem to relate to lists, I was wondering if there is an 
>> elegant similar way to apply a function to all keys in a dictionary?
>> 
>> (without looping over it, of course)
> 
> Just fyi, as it sounds you may not understand.  List Comprehensions loop over 
> the list.  There's no other magic going on that avoids that.
> 
> result = [ ii for ii in lst if cond ]
> 
> is just shorthand for
> 
> result = []
> for ii in lst:
>  if cond:
>result.append(ii)
> 
> Emile

Ah, so list comprehensions are a purely syntactic construct?

I had the feeling there might be a performance benefit of some kind.

thanks for all the contributions on this topic, it's been greatly helpful to my 
understanding.

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


Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Steven D'Aprano
On Fri, 20 Aug 2010 09:51:08 am Pete wrote:

[...]
> Ah, so list comprehensions are a purely syntactic construct?

No, I don't think that's what Emile was trying to say. It's not like 
list comps are macros that are expanded into the explicit for-loop like 
that. All he is saying is that both the for-loop and the list 
comprehension loop over the list.

There are some functional differences: for example, the list comp avoids 
needing to look up result.append over and over again. Because it knows 
it is dealing with a list, rather than some arbitrary object that 
conceivably might have some weird append method with strange 
side-effects, it can take optimizing short-cuts that aren't applicable 
to general for-loops. 


> I had the feeling there might be a performance benefit of some kind.

If you write the for-loop in the most straight forward, obvious fashion, 
then there is a small but measurable performance cost from repeatedly 
looking up the append method. On the other hand, for-loops are more 
general -- you can call break to exit early, or continue to skip an 
iteration, so they're easier to optimize. There's no way to break out 
of a list comp early (other than raising an exception, which defeats 
the purpose). No matter how fast you can perform a loop, it's always 
faster to avoid it altogether, so this:

seq = xrange(1000)
result = []
for i in seq:
if i >= 10: break
result.append(i%2)


will be much faster than this:

seq = xrange(1000)
result = [i%2 for i in seq if i < 10]


Other than that, the speed of the loop itself is virtually the same as 
the speed of the list comprehension.



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