[Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Jojo Mwebaze
Hi There,

i would like to implement the following in lists

assuming

x = 3
y = 4
z = None

i want to create a dynamic list such that

mylist = [ x , y, z ] ,   if z in not None

if z is None then

mylist = [x,y]

Anyhelp!

cheers

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


[Tutor] Encoding

2010-03-03 Thread Giorgio
Hi,

i am looking for more informations about encoding in python:

i've read that Amazon SimpleDB accepts every string encoded in UTF-8. How
can I encode a string? And, what's the default string encoding in python?

the other question is about mysql DB: if i have a mysql field latin1 and
extract his content in a python script, how can I handle it?

thankyou

Giorgio

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


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Alan Gauld


"Jojo Mwebaze"  wrote


i would like to implement the following in lists

assuming

x = 3
y = 4
z = None

i want to create a dynamic list such that

mylist = [ x , y, z ] ,   if z in not None

if z is None then

mylist = [x,y]



Assuming you actually mean that you don;t want to include 
any item that is None you can use an if clause at the end 
of the comprehension:


mylist = [irtem for item in aList where item != None]

and aList is any list, which could be [x,y,z] in your example.

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] List comprehension possible with condition statements?

2010-03-03 Thread C.T. Matsumoto

Jojo Mwebaze wrote:

Hi There,

i would like to implement the following in lists

assuming

x = 3
y = 4
z = None

i want to create a dynamic list such that

mylist = [ x , y, z ] ,   if z in not None

if z is None then

mylist = [x,y]

Anyhelp!

cheers

Jojo







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

Yes a list comprehension can have if statements.

You can get the values of x and y pretty simply:

>>> [i for i in mylist if i]
[3, 4]


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


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Christian Witts

Jojo Mwebaze wrote:

Hi There,

i would like to implement the following in lists

assuming

x = 3
y = 4
z = None

i want to create a dynamic list such that

mylist = [ x , y, z ] ,   if z in not None

if z is None then

mylist = [x,y]

Anyhelp!

cheers

Jojo







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


 |  for , 

So something like `x**2 for x in [1, 2, 3, 4, 5, None, 9] if x != None` 
would iterate over your input set pumping the current item into the 
variable x, it will check "if x != None" and if that condition evaluates 
true it will perform the function you set out to perform.


The predicate section acts as a filter to your data set ensuring the 
variable you are working with meets certain conditions.  If you wanted 
to for eg. still accept the None but perform a different function on it 
Python does allow it like `x**2 if x else 'Not a number' for x in [1, 2, 
3, 4, 5, None, 9]`.


Hope that helps.

--
Kind Regards,
Christian Witts


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


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Dave Angel

Jojo Mwebaze wrote:

Hi There,

i would like to implement the following in lists

assuming

x = 3
y = 4
z = None

i want to create a dynamic list such that

mylist = [ x , y, z ] ,   if z in not None

if z is None then

mylist = [x,y]

Anyhelp!

cheers

Jojo

  


Are there any constraints on x and y ?  If you want to throw out all 
None values, then it's a ready problem.  You try it, and if it doesn't 
quite work, post the code. We'll try to help.


But if only the third value is special, then there's little point in 
making a comprehension of one value.  Just conditionally append the z 
value to the list containing x and y.


DaveA

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


Re: [Tutor] Encoding

2010-03-03 Thread Stefan Behnel

Giorgio, 03.03.2010 09:36:

i am looking for more informations about encoding in python:

i've read that Amazon SimpleDB accepts every string encoded in UTF-8. How
can I encode a string?


  byte_string = unicode_string.encode('utf-8')

If you use unicode strings throughout your application, you will be happy 
with the above. Note that this is an advice, not a condition.




And, what's the default string encoding in python?


"default encodings" are bad, don't rely on them.

Stefan

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


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Jojo Mwebaze
Thanks to everyone, nice ideas!
cheers


On Wed, Mar 3, 2010 at 10:02 AM, Christian Witts wrote:

> Jojo Mwebaze wrote:
>
>> Hi There,
>>
>> i would like to implement the following in lists
>>
>> assuming
>>
>> x = 3
>> y = 4
>> z = None
>>
>> i want to create a dynamic list such that
>>
>> mylist = [ x , y, z ] ,   if z in not None
>>
>> if z is None then
>>
>> mylist = [x,y]
>>
>> Anyhelp!
>>
>> cheers
>>
>> Jojo
>>
>>
>>
>>
>>
>> 
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
>  |  for , 
>
> So something like `x**2 for x in [1, 2, 3, 4, 5, None, 9] if x != None`
> would iterate over your input set pumping the current item into the variable
> x, it will check "if x != None" and if that condition evaluates true it will
> perform the function you set out to perform.
>
> The predicate section acts as a filter to your data set ensuring the
> variable you are working with meets certain conditions.  If you wanted to
> for eg. still accept the None but perform a different function on it Python
> does allow it like `x**2 if x else 'Not a number' for x in [1, 2, 3, 4, 5,
> None, 9]`.
>
> Hope that helps.
>
> --
> Kind Regards,
> Christian Witts
>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread C.T. Matsumoto

Dave Angel wrote:

Jojo Mwebaze wrote:

Hi There,

i would like to implement the following in lists

assuming

x = 3
y = 4
z = None

i want to create a dynamic list such that

mylist = [ x , y, z ] ,   if z in not None

if z is None then

mylist = [x,y]

Anyhelp!

cheers

Jojo

  


Are there any constraints on x and y ?  If you want to throw out all 
None values, then it's a ready problem.  You try it, and if it doesn't 
quite work, post the code. We'll try to help.


But if only the third value is special, then there's little point in 
making a comprehension of one value.  Just conditionally append the z 
value to the list containing x and y.


DaveA

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


Hello,

I wrote a solution which isn't correct.

>>> [i for i in mylist if i]
[3, 4]


The if condition should test like the other examples given to the list.

>>> [i for i in mylist if i != None]
[3, 4]

'if i' would also leave out the integer 0.

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


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Steven D'Aprano
On Wed, 3 Mar 2010 07:46:39 pm Alan Gauld wrote:

> mylist = [irtem for item in aList where item != None]

Comparisons with None almost always should be one of:

item is None
item is not None

The reason is that "item is None" is ONLY ever true if the item actually 
is the singleton object None (accept no substitutes!).

On the other hand, "item == None" might be true for some customer items. 
So if you actually *do* want to accept substitutes, you can use ==, but 
that would be an unusual thing to do, and worthy of a comment 
explaining that you did mean == and it isn't a mistake.

Likewise for "item != None" versus "item is not None".



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


[Tutor] sorting algorithm

2010-03-03 Thread C.T. Matsumoto

Hello,

This is follow up on a question I had about algorithms. In the thread it 
was suggested I make my own sorting algorithm.


Here are my results.

#!/usr/bin/python

def sort_(list_):
   for item1 in list_:
   pos1 = list_.index(item1)
   pos2 = pos1 + 1
   try:
   item2 = list_[pos2]
   except IndexError:
   pass

   if item1 >= item2:
   try:
   list_.pop(pos2)
   list_.insert(pos1, item2)
   return True
   except IndexError:
   pass

def mysorter(list_):
   while sort_(list_) is True:
   sort_(list_)

I found this to be a great exercise. In doing the exercise, I got pretty 
stuck. I consulted another programmer (my dad) who described how to go 
about sorting. As it turned out the description he described was the 
Bubble sort algorithm. Since coding the solution I know the Bubble sort 
is inefficient because of repeated iterations over the entire list. This 
shed light on the quick sort algorithm which I'd like to have a go at.


Something I haven't tried is sticking in really large lists. I was told 
that with really large list you break down the input list into smaller 
lists. Sort each list, then go back and use the same swapping procedure 
for each of the different lists. My question is, at what point to you 
start breaking things up? Is that based on list elements or is it based 
on memory(?) resources python is using?


One thing I'm not pleased about is the while loop and I'd like to 
replace it with a for loop.


Thanks,

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


Re: [Tutor] Why is the max size so low in this mail list?

2010-03-03 Thread spir
On Wed, 03 Mar 2010 02:38:57 +1100
Lie Ryan  wrote:

> On 03/02/2010 04:13 AM, Wayne Watson wrote:
> > See Subject. 40K here, but other Python lists allow for larger (total)
> > sizes.
> 
> I don't know, I've never realized it; that's an indication that the 40K
> limit is reasonable, at least to me.

A pocket book typically holds ~ 1000 chars per page. Even with a long thread 
accumulation (because people do not always cut off irrelevant parts), 40K is 
more than enough.
This post holds 651 chars (spaces, signature & this comment all included).

Denis
-- 


la vita e estrany

spir.wikidot.com

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


Re: [Tutor] Encoding

2010-03-03 Thread Patrick Sabin

Giorgio wrote:

i am looking for more informations about encoding in python:

i've read that Amazon SimpleDB accepts every string encoded in UTF-8. 
How can I encode a string? And, what's the default string encoding in 
python?


I think the safest way is to use unicode strings in your application and 
convert them to byte strings if needed, using the encode and decode methods.





the other question is about mysql DB: if i have a mysql field latin1 and 
extract his content in a python script, how can I handle it?


if you have a byte string s encoded in 'latin1' you can simply call:

s.decode('latin1')

to get the unicode string.



thankyou

Giorgio


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


Re: [Tutor] Encoding

2010-03-03 Thread Giorgio
>
>
>>  byte_string = unicode_string.encode('utf-8')
>
> If you use unicode strings throughout your application, you will be happy
> with the above. Note that this is an advice, not a condition.



Mmm ok. So all strings in the app are unicode by default?

Do you know if there is a function/method i can use to check encoding of a
string?


>
> "default encodings" are bad, don't rely on them.
>

No, ok, it was just to understand what i'm working with.

Patrick, ok. I should check if it's possible to save unicode strings in the
DB.

Do you think i'd better set my db to utf8? I don't need latin1, it's just
the default value.

Thankyou

Giorgio


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


Re: [Tutor] Encoding

2010-03-03 Thread Giorgio
Oh, sorry, let me update my last post:

if i have a string, let's say:

s = "hi giorgio";

and want to store it in a latin1 db, i need to convert it to latin1 before
storing, right?

2010/3/3 Giorgio 

>
>>>  byte_string = unicode_string.encode('utf-8')
>>
>> If you use unicode strings throughout your application, you will be happy
>> with the above. Note that this is an advice, not a condition.
>
>
>
> Mmm ok. So all strings in the app are unicode by default?
>
> Do you know if there is a function/method i can use to check encoding of a
> string?
>
>
>>
>> "default encodings" are bad, don't rely on them.
>>
>
> No, ok, it was just to understand what i'm working with.
>
> Patrick, ok. I should check if it's possible to save unicode strings in the
> DB.
>
> Do you think i'd better set my db to utf8? I don't need latin1, it's just
> the default value.
>
> Thankyou
>
> Giorgio
>
>
> --
> --
> AnotherNetFellow
> Email: anothernetfel...@gmail.com
>



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


[Tutor] Bowing out

2010-03-03 Thread Kent Johnson
Hi all,

After six years of tutor posts my interest and energy have waned and
I'm ready to move on to something new. I'm planning to stop reading
and contributing to the list. I have handed over list moderation
duties to Alan Gauld and Wesley Chun.

Thanks to everyone who contributes questions and answers. I learned a
lot from my participation here.

So long and keep coding!
Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Encoding

2010-03-03 Thread Patrick Sabin



Mmm ok. So all strings in the app are unicode by default?

Depends on your python version. If you use python 2.x, you have to use a 
u before the string:


s = u'Hallo World'

Do you know if there is a function/method i can use to check encoding of 
a string?


AFAIK such a function doesn't exist. Python3 solves this by using 
unicode strings by default.


Patrick, ok. I should check if it's possible to save unicode strings in 
the DB.


It is more an issue of your database adapter, than of your database.



Do you think i'd better set my db to utf8? I don't need latin1, it's 
just the default value.


I think the encoding of the db doesn't matter much in this case, but I 
would prefer utf-8 over latin-1. If you get an utf-8 encoded raw byte 
string you call .decode('utf-8'). In case of an latin-1 encoded string 
you call .decode('latin1')



Thankyou

Giorgio

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


Re: [Tutor] Bowing out

2010-03-03 Thread kevin parks

Dang!

I wish you were not going. But really, I have to say a HUGE thank you  
to you for all the fine teaching you have done on this list. I learned  
so much from reading your posts. Thanks for all the time and effort  
(and code) you put into this! I wish you were staying. Hats off to  
you. Wish there was some way to give a standing ovation over the  
internet. Glad to see though that the list has been handed off to 2  
fantastic folks but still sad to see you go. Wish Danny Yoo was still  
here too.


Thank you Kent. Thank you very much~

-kevin--



On Mar 3, 2010, at 10:17 PM, Kent Johnson wrote:


Hi all,

After six years of tutor posts my interest and energy have waned and
I'm ready to move on to something new. I'm planning to stop reading
and contributing to the list. I have handed over list moderation
duties to Alan Gauld and Wesley Chun.

Thanks to everyone who contributes questions and answers. I learned a
lot from my participation here.

So long and keep coding!
Kent
___
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] Bowing out

2010-03-03 Thread Shashwat Anand
Kent

We salute you. Thanks for everything you did for the community.

~l0nwlf

On Wed, Mar 3, 2010 at 7:09 PM, kevin parks  wrote:

> Dang!
>
> I wish you were not going. But really, I have to say a HUGE thank you to
> you for all the fine teaching you have done on this list. I learned so much
> from reading your posts. Thanks for all the time and effort (and code) you
> put into this! I wish you were staying. Hats off to you. Wish there was some
> way to give a standing ovation over the internet. Glad to see though that
> the list has been handed off to 2 fantastic folks but still sad to see you
> go. Wish Danny Yoo was still here too.
>
> Thank you Kent. Thank you very much~
>
> -kevin--
>
>
>
>
> On Mar 3, 2010, at 10:17 PM, Kent Johnson wrote:
>
>  Hi all,
>>
>> After six years of tutor posts my interest and energy have waned and
>> I'm ready to move on to something new. I'm planning to stop reading
>> and contributing to the list. I have handed over list moderation
>> duties to Alan Gauld and Wesley Chun.
>>
>> Thanks to everyone who contributes questions and answers. I learned a
>> lot from my participation here.
>>
>> So long and keep coding!
>> Kent
>> ___
>> 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 maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Encoding

2010-03-03 Thread Stefan Behnel

Giorgio, 03.03.2010 14:09:

  byte_string = unicode_string.encode('utf-8')


If you use unicode strings throughout your application, you will be happy
with the above. Note that this is an advice, not a condition.


Mmm ok. So all strings in the app are unicode by default?

Do you know if there is a function/method i can use to check encoding of a
string?


Not sure what exactly you mean here. If you meant to say "guess the 
encoding of a byte string", then there are a few ways to do that. But none 
of them is guaranteed to work. Therefore my advice: use unicode everywhere 
and decode byte strings on the way in, where you (hopefully) know their 
encoding. If you don't know the encoding on the way in, reject the input.


Stefan

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


Re: [Tutor] Bowing out

2010-03-03 Thread عمـ نوفل ـاد
On Wed, Mar 3, 2010 at 9:17 AM, Shashwat Anand wrote:

> Kent
>
> We salute you. Thanks for everything you did for the community.
>
> ~l0nwlf
>
>
> On Wed, Mar 3, 2010 at 7:09 PM, kevin parks  wrote:
>
>> Dang!
>>
>> I wish you were not going. But really, I have to say a HUGE thank you to
>> you for all the fine teaching you have done on this list. I learned so much
>> from reading your posts. Thanks for all the time and effort (and code) you
>> put into this! I wish you were staying. Hats off to you. Wish there was some
>> way to give a standing ovation over the internet. Glad to see though that
>> the list has been handed off to 2 fantastic folks but still sad to see you
>> go. Wish Danny Yoo was still here too.
>>
>> Thank you Kent. Thank you very much~
>>
>> -kevin--
>>
>>
>>
>>
>> On Mar 3, 2010, at 10:17 PM, Kent Johnson wrote:
>>
>>  Hi all,
>>>
>>> After six years of tutor posts my interest and energy have waned and
>>> I'm ready to move on to something new. I'm planning to stop reading
>>> and contributing to the list. I have handed over list moderation
>>> duties to Alan Gauld and Wesley Chun.
>>>
>>> Thanks to everyone who contributes questions and answers. I learned a
>>> lot from my participation here.
>>>
>>> So long and keep coding!
>>> Kent
>>> ___
>>> 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 maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
> Thank you Kent,
I personally learned a lot from you.


-- 
لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.محمد
الغزالي
"No victim has ever been more repressed and alienated than the truth"

Emad Soliman Nawfal
Indiana University, Bloomington

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


Re: [Tutor] Encoding

2010-03-03 Thread Giorgio
>
>
>>  Depends on your python version. If you use python 2.x, you have to use a
> u before the string:
>
> s = u'Hallo World'


Ok. So, let's go back to my first question:

s = u'Hallo World' is unicode in python 2.x -> ok
s = 'Hallo World' how is encoded?


>> I think the encoding of the db doesn't matter much in this case, but I
> would prefer utf-8 over latin-1. If you get an utf-8 encoded raw byte string
> you call .decode('utf-8'). In case of an latin-1 encoded string you call
> .decode('latin1')
>

Ok, setting it to UTF-8.


> If you don't know the encoding on the way in, reject the input.
>
>
Well, the problem comes,  i.e when i'm getting a string from an HTML form
with POST. I don't and can't know the encoding, right? It depends on
browser.

Giorgio



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


Re: [Tutor] Bowing out

2010-03-03 Thread Vern Ceder

Kent,

Thanks for all of the work you've done over the years to help make this 
one of the best/most useful lists around. Enjoy the new challenges ahead!


It was great to finally meet you at PyCon!

Cheers,
Vern

Kent Johnson wrote:

Hi all,

After six years of tutor posts my interest and energy have waned and
I'm ready to move on to something new. I'm planning to stop reading
and contributing to the list. I have handed over list moderation
duties to Alan Gauld and Wesley Chun.

Thanks to everyone who contributes questions and answers. I learned a
lot from my participation here.

So long and keep coding!
Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


--
This time for sure!
   -Bullwinkle J. Moose
-
Vern Ceder, Director of Technology
Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804
vce...@canterburyschool.org; 260-436-0746; FAX: 260-436-5137

The Quick Python Book, 2nd Ed - http://bit.ly/bRsWDW
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Bowing out

2010-03-03 Thread Daniel Sarmiento
>
> Date: Wed, 3 Mar 2010 08:17:45 -0500
> From: Kent Johnson 
> To: Tutor@python.org
> Subject: [Tutor] Bowing out
> Message-ID:
><1c2a2c591003030517r66cf067fgf2f5a052a4a08...@mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
>
> Hi all,
>
> After six years of tutor posts my interest and energy have waned and
> I'm ready to move on to something new. I'm planning to stop reading
> and contributing to the list. I have handed over list moderation
> duties to Alan Gauld and Wesley Chun.
>
> Thanks to everyone who contributes questions and answers. I learned a
> lot from my participation here.
>
> So long and keep coding!
> Kent
>


Thank you very much. I wish you the best of luck.

I know a lot of people learned a lot from your postings and your (Kent's
Korner site) I hope you keep it online... again, thank you for all the years
you helped the python community.
Farewell Kent.


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


Re: [Tutor] Bowing out

2010-03-03 Thread Wayne Werner
I can only add my personal thanks, and echo the sentiments of others.

I'm certainly glad the archives exist, and that those inheriting
responsibility are certainly well qualified.

So long and thanks for all the fish!
-Wayne

2010/3/3 Emad Nawfal (عمـ نوفل ـاد) 

>
>
> On Wed, Mar 3, 2010 at 9:17 AM, Shashwat Anand 
> wrote:
>
>> Kent
>>
>> We salute you. Thanks for everything you did for the community.
>>
>> ~l0nwlf
>>
>>
>> On Wed, Mar 3, 2010 at 7:09 PM, kevin parks  wrote:
>>
>>> Dang!
>>>
>>> I wish you were not going. But really, I have to say a HUGE thank you to
>>> you for all the fine teaching you have done on this list. I learned so much
>>> from reading your posts. Thanks for all the time and effort (and code) you
>>> put into this! I wish you were staying. Hats off to you. Wish there was some
>>> way to give a standing ovation over the internet. Glad to see though that
>>> the list has been handed off to 2 fantastic folks but still sad to see you
>>> go. Wish Danny Yoo was still here too.
>>>
>>> Thank you Kent. Thank you very much~
>>>
>>> -kevin--
>>>
>>>
>>>
>>>
>>> On Mar 3, 2010, at 10:17 PM, Kent Johnson wrote:
>>>
>>>  Hi all,

 After six years of tutor posts my interest and energy have waned and
 I'm ready to move on to something new. I'm planning to stop reading
 and contributing to the list. I have handed over list moderation
 duties to Alan Gauld and Wesley Chun.

 Thanks to everyone who contributes questions and answers. I learned a
 lot from my participation here.

 So long and keep coding!
 Kent
 ___
 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 maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>> Thank you Kent,
> I personally learned a lot from you.
>
>
> --
> لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.محمد
> الغزالي
> "No victim has ever been more repressed and alienated than the truth"
>
> Emad Soliman Nawfal
> Indiana University, Bloomington
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn’t. - Primo Levi
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Bowing out

2010-03-03 Thread Modulok
> After six years of tutor posts my interest and energy have waned and
> I'm ready to move on to something new. I'm planning to stop reading
> and contributing to the list. I have handed over list moderation
> duties to Alan Gauld and Wesley Chun.
>
> Thanks to everyone who contributes questions and answers. I learned a
> lot from my participation here.

Kent,

I'm a relative newcomer, but even so, I benefited from you. Thanks for
giving what you could!

Best of luck with your new endeavors. Hope to see you check back in
from time to time.
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Bowing out

2010-03-03 Thread Philip Kilner
Hi Kent,

Thank you!


-- 

Regards,

PhilK


'work as if you lived in the early days of a better nation'
- alasdair gray


smime.p7s
Description: S/MIME Cryptographic Signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Encoding

2010-03-03 Thread Stefan Behnel

Giorgio, 03.03.2010 15:50:

  Depends on your python version. If you use python 2.x, you have to use a

u before the string:

s = u'Hallo World'


Ok. So, let's go back to my first question:

s = u'Hallo World' is unicode in python 2.x ->  ok


Correct.


s = 'Hallo World' how is encoded?


Depends on your source code encoding.

http://www.python.org/dev/peps/pep-0263/



Well, the problem comes,  i.e when i'm getting a string from an HTML form
with POST. I don't and can't know the encoding, right? It depends on
browser.


The browser will tell you the encoding in the headers that it transmits.

Stefan

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


Re: [Tutor] Encoding

2010-03-03 Thread Patrick Sabin

Giorgio wrote:


Depends on your python version. If you use python 2.x, you have to
use a u before the string:

s = u'Hallo World'


Ok. So, let's go back to my first question: 


s = u'Hallo World' is unicode in python 2.x -> ok
s = 'Hallo World' how is encoded?


I am not 100% sure, but I think it depends on the encoding of your 
source file or the coding you specify. See PEP 263

http://www.python.org/dev/peps/pep-0263/

Well, the problem comes,  i.e when i'm getting a string from an HTML 
form with POST. I don't and can't know the encoding, right? It depends 
on browser.


Right, but you can do something about it. Tell the browser, which 
encoding you are going to accept:



...


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


Re: [Tutor] Bowing out

2010-03-03 Thread Dave Angel

Kent Johnson wrote:

Hi all,

After six years of tutor posts my interest and energy have waned and
I'm ready to move on to something new. I'm planning to stop reading
and contributing to the list. I have handed over list moderation
duties to Alan Gauld and Wesley Chun.

Thanks to everyone who contributes questions and answers. I learned a
lot from my participation here.

So long and keep coding!
Kent

  
I'm sorry to see you go as well.  I've learned an awful lot from your 
posts over the couple of years I've been here.


Thanks for all the efforts.
DaveA

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


Re: [Tutor] Encoding

2010-03-03 Thread Giorgio
Uff, encoding is a very painful thing in programming.

Ok so now comes last "layer" of the encoding: the webserver.

I now know how to handle encoding in a python app and in interactions with
the db, but the last step is sending the content to the webserver.

How should i encode pages? The encoding i choose has to be the same than the
one i choose in the .htaccess file? Or maybe i can send content encoded how
i like more to apache and it re-encodes in the right way all pages?

Thankyou

2010/3/3 Patrick Sabin 

> Giorgio wrote:
>
>>
>>Depends on your python version. If you use python 2.x, you have to
>>use a u before the string:
>>
>>s = u'Hallo World'
>>
>>
>> Ok. So, let's go back to my first question:
>> s = u'Hallo World' is unicode in python 2.x -> ok
>> s = 'Hallo World' how is encoded?
>>
>
> I am not 100% sure, but I think it depends on the encoding of your source
> file or the coding you specify. See PEP 263
> http://www.python.org/dev/peps/pep-0263/
>
>
>  Well, the problem comes,  i.e when i'm getting a string from an HTML form
>> with POST. I don't and can't know the encoding, right? It depends on
>> browser.
>>
>
> Right, but you can do something about it. Tell the browser, which encoding
> you are going to accept:
>
> 
> ...
> 
>
> - Patrick
>



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


Re: [Tutor] sorting algorithm

2010-03-03 Thread Dave Angel

C.T. Matsumoto wrote:

Hello,

This is follow up on a question I had about algorithms. In the thread 
it was suggested I make my own sorting algorithm.


Here are my results.

#!/usr/bin/python

def sort_(list_):
   for item1 in list_:
   pos1 = list_.index(item1)
   pos2 = pos1 + 1
   try:
   item2 = list_[pos2]
   except IndexError:
   pass

   if item1 >= item2:
   try:
   list_.pop(pos2)
   list_.insert(pos1, item2)
   return True
   except IndexError:
   pass

def mysorter(list_):
   while sort_(list_) is True:
   sort_(list_)

I found this to be a great exercise. In doing the exercise, I got 
pretty stuck. I consulted another programmer (my dad) who described 
how to go about sorting. As it turned out the description he described 
was the Bubble sort algorithm. Since coding the solution I know the 
Bubble sort is inefficient because of repeated iterations over the 
entire list. This shed light on the quick sort algorithm which I'd 
like to have a go at.


Something I haven't tried is sticking in really large lists. I was 
told that with really large list you break down the input list into 
smaller lists. Sort each list, then go back and use the same swapping 
procedure for each of the different lists. My question is, at what 
point to you start breaking things up? Is that based on list elements 
or is it based on memory(?) resources python is using?


One thing I'm not pleased about is the while loop and I'd like to 
replace it with a for loop.


Thanks,

T


There are lots of references on the web about Quicksort, including a 
video at:

http://www.youtube.com/watch?v=y_G9BkAm6B8

which I think illustrates it pretty well.  It would be a great learning 
exercise to implement Python code directly from that description, 
without using the sample C++ code available.


(Incidentally, there are lots of variants of Quicksort, so I'm not going 
to quibble about whether this is the "right" one to be called that.)


I don't know what your earlier thread was, since you don't mention the 
subject line, but there are a number of possible reasons you might not 
have wanted to use the built-in sort.  The best one is for educational 
purposes.  I've done my own sort for various reasons in the past, even 
though I had a library function, since the library function had some 
limits.  One time I recall, the situation was that the library sort was 
limited to 64k of total data, and I had to work with much larger arrays 
(this was in 16bit C++, in "large" model).  I solved the size problem by 
using the  C++ sort library on 16k subsets (because a pointer was 2*2 
bytes).  Then I merged the results of the sorts.  At the time, and in 
the circumstances involved, there were seldom more than a dozen or so 
sublists to merge, so this approach worked well enough.


Generally, it's better for both your development time and the efficiency 
and reliabilty of the end code, to base a new sort mechanism on the 
existing one.  In my case above, I was replacing what amounted to an 
insertion sort, and achieved a 50* improvement for a real customer.  It 
was fast enough that other factors completely dominated his running time.


But for learning purposes?  Great plan.  So now I'll respond to your 
other questions, and comment on your present algorithm.


It would be useful to understand about algorithmic complexity, the so 
called Order Function.  In a bubble sort, if you double the size of the 
array, you quadruple the number of comparisons and swaps.  It's order 
N-squared or O(n*n).   So what works well for an array of size 10 might 
take a very long time for an array of size 1 (like a million times 
as long).  You can do much better by sorting smaller lists, and then 
combining them together.  Such an algorithm can  be O(n*log(n)).



You ask at what point you consider sublists?  In a language like C, the 
answer is when the list is size 3 or more.  For anything larger than 2, 
you divide into sublists, and work on them.


Now, if I may comment on your code.  You're modifying a list while 
you're iterating through it in a for loop.  In the most general case, 
that's undefined.  I think it's safe in this case, but I would avoid it 
anyway, by just using xrange(len(list_)-1) to iterate through it.  You 
use the index function to find something you would already know -- the 
index function is slow.  And the first try/except isn't needed if you 
use a -1 in the xrange argument, as I do above.


You use pop() and push() to exchange two adjacent items in the list.  
Both operations copy the remainder of the list, so they're rather slow.  
Since you're exchanging two items in the list, you can simply do that:

list[pos1], list[pos2] = list[pos2], list[pos1]

That also eliminates the need for the second try/except.

You mention being bothered by the while loop.  You could replace it with 
a simple for loop with xrange(len(l

Re: [Tutor] Encoding

2010-03-03 Thread Dave Angel

Giorgio wrote:


 Depends on your python version. If you use python 2.x, you have to use a
  

u before the string:

s = u'Hallo World'




Ok. So, let's go back to my first question:

s = u'Hallo World' is unicode in python 2.x -> ok
s = 'Hallo World' how is encoded?

  

Since it's a quote literal in your source code, it's encoded by your 
text editor when it saves the file, and you tell Python which encoding 
it was by the second line of your source file, right after the shebang line.


A sequence of bytes in an html file should be should have its encoding 
identified by the tag at the top of the html file.  And I'd  *guess* 
that on a form result, the encoding can be assumed to match that of the 
html of the form itself.


DaveA

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


Re: [Tutor] Bowing out

2010-03-03 Thread Sander Sweers
On 3 March 2010 14:17, Kent Johnson  wrote:
> After six years of tutor posts my interest and energy have waned and
> I'm ready to move on to something new.

Let me join the other people and thank you for your contribution to
this list. Good luck with something new :-)

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


Re: [Tutor] Encoding

2010-03-03 Thread Giorgio
Ok.

So, how do you encode .py files? UTF-8?

2010/3/3 Dave Angel 

> Giorgio wrote:
>
>>
>>>
  Depends on your python version. If you use python 2.x, you have to use
 a


>>> u before the string:
>>>
>>> s = u'Hallo World'
>>>
>>>
>>
>>
>> Ok. So, let's go back to my first question:
>>
>> s = u'Hallo World' is unicode in python 2.x -> ok
>> s = 'Hallo World' how is encoded?
>>
>>
>>
> Since it's a quote literal in your source code, it's encoded by your text
> editor when it saves the file, and you tell Python which encoding it was by
> the second line of your source file, right after the shebang line.
>
> A sequence of bytes in an html file should be should have its encoding
> identified by the tag at the top of the html file.  And I'd  *guess* that on
> a form result, the encoding can be assumed to match that of the html of the
> form itself.
>
> DaveA
>
>


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


Re: [Tutor] Bowing out

2010-03-03 Thread Albert-Jan Roskam
Hi Kent,

Thank you very much for sharing your knowledge. Much appreciated!

Cheers!!

Albert-Jan



~~

In the face of ambiguity, refuse the temptation to guess.

~~

--- On Wed, 3/3/10, Kent Johnson  wrote:

From: Kent Johnson 
Subject: [Tutor] Bowing out
To: Tutor@python.org
Date: Wednesday, March 3, 2010, 2:17 PM

Hi all,

After six years of tutor posts my interest and energy have waned and
I'm ready to move on to something new. I'm planning to stop reading
and contributing to the list. I have handed over list moderation
duties to Alan Gauld and Wesley Chun.

Thanks to everyone who contributes questions and answers. I learned a
lot from my participation here.

So long and keep coding!
Kent
___
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] no bowing out for you

2010-03-03 Thread Gman

Nope ya can't do it Kent, we wont have it !
Looks like a good time to start a patitiion to get you a salary or  
something to keep you on :)



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


Re: [Tutor] getting diagonals from a matrix

2010-03-03 Thread Emile van Sebille

On 3/2/2010 2:54 PM David Eccles (gringer) said...

I've managed to drum up some code to obtain a list containing joined diagonal
elements of a matrix (I'm making a word finder generator), but am wondering if
there's any better way to do this:


This works.  Lots of other ways would work too.  What would make one 
better than another?  Anyway, here's my take on it...


#

# setup so code snippet works properly
sizeW = 4
sizeH = 3
puzzleLayout = ['spam'] * (sizeW * sizeH)

# this allows the result to match your example

from string import digits,letters
puzzleLayout = (digits+letters)[:sizeW * sizeH]


# Starting with, say, an array with these indices:

# It might help to consider the indices numbers as that's what
# python does, so I've assumed these to be the values instead.

# 0 1 2 3
# 4 5 6 7
# 8 9 A B

# Looking at the index table above, note that all the results
# start on an edge and work diagonally from there.  I'll guess
# you found the back diags easier -- no messy 'in-the-same-row'
# problems -- but the forward diags are harder.  Note if we
# flype the table the forward diags can be built from the back
#
diag instructions

#FpuzzleLayout
# 8 9 A B
# 4 5 6 7
# 0 1 2 3

# so we'll build it once like this...
FpuzzleLayout = "".join(
  [ puzzleLayout[ii-sizeW:ii]
for ii in range(sizeW*sizeH,0,-sizeW)
] )

#So now, the only starting positions we need to worry about are
# on the left and top edge ignoring the start and end corners.
edge = (range(sizeW * sizeH,0,-sizeW)+range(sizeW-1))[2:]

# and to avoid any modular impact, we'll add a length constraint
lens = range(2,sizeH+1)+range(sizeW-1,1,-1)

# and do it
result = []

for ii,ln in zip(edge,lens):
  result.append(puzzleLayout[ii::sizeW+1][:ln])
  result.append(FpuzzleLayout[ii::sizeW+1][:ln])


# now add in the reversed results
for ii in result[:]:
  result.append("".join(reversed(ii)))

# and the corners
result.extend([puzzleLayout[0],
   puzzleLayout[-1],
   FpuzzleLayout[0],
   FpuzzleLayout[-1]])


#

Emile



# I want the following items for a back diagonal (not in square brackets):
# [-2],[3],8 (+5) | div 4 = -1, 1, 2
# [-1],4,9 (+5)   | div 4 = -1, 1, 2
# 0,5,A (+5)  | div 4 =  0, 1, 2
# 1,6,B (+5)  | div 4 =  0, 1, 2
# 2,7,[C] (+5)| div 4 =  0, 1, 3
# 3,[8],[D] (+5)  | div 4 =  0, 2, 3

# in other words, increase sequence by sizeW + 1 each time (sizeW - 1
# for forward diagonals), only selecting if the line you're on matches
# the line you want to be on

# back as in backslash-like diagonal
puzzleDiagBack = [(''.join([puzzleLayout[pos*(sizeW+1) + i] \
for pos in range(sizeH) if (pos*(sizeW+1) + i) / sizeW == pos])) \
for i in range(-sizeH+1,sizeW)]
puzzleDiagBackRev = [(''.join(reversed([puzzleLayout[pos*(sizeW+1) + i] \
for pos in range(sizeH) if (pos*(sizeW+1) + i) / sizeW == pos]))) \
for i in range(-sizeH+1,sizeW)]
# fwd as in forwardslash-like diagonal
puzzleDiagFwdRev = [(''.join([puzzleLayout[pos*(sizeW-1) + i] \
for pos in range(sizeH) if (pos*(sizeW-1) + i) / sizeW == pos])) \
for i in range(sizeW+sizeH-1)]
puzzleDiagFwd = [(''.join(reversed([puzzleLayout[pos*(sizeW-1) + i] \
for pos in range(sizeH) if (pos*(sizeW-1) + i) / sizeW == pos]))) \
for i in range(sizeW+sizeH-1)]

Cheers,
David Eccles (gringer)
___
Tutor maillist  -tu...@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] Bowing out

2010-03-03 Thread Hansen, Mike
> -Original Message-
> From: tutor-bounces+mike.hansen=atmel@python.org 
> [mailto:tutor-bounces+mike.hansen=atmel@python.org] On 
> Behalf Of Kent Johnson
> Sent: Wednesday, March 03, 2010 6:18 AM
> To: Tutor@python.org
> Subject: [Tutor] Bowing out
> 
> Hi all,
> 
> After six years of tutor posts my interest and energy have waned and
> I'm ready to move on to something new. I'm planning to stop reading
> and contributing to the list. I have handed over list moderation
> duties to Alan Gauld and Wesley Chun.
> 
> Thanks to everyone who contributes questions and answers. I learned a
> lot from my participation here.
> 
> So long and keep coding!
> Kent

We know what's really going on. You are moving to Ruby Tutor. =)

Good luck with your "something new", and thanks for the many years of help on 
this list.

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


[Tutor] Script Building

2010-03-03 Thread David Hutto
I'm new to Python, so I thought as a first project I'd create a basic script 
building wizard to help with my understanding of the flow, and for basic 
practice. The following is a outline of what I would initially like to 
accomplish. 

I've begun creating small functions, and very lightly worded pseudocode, but 
before I go further I'd like to make sure I'm building my script insertions 
correctly, and see if any one has any suggestions on how to refine the process, 
or what I might be able to use as additives to sub-levels of my insertions.

Here is a basic outline of the insertions from either raw_input or, drop down 
menu:

append paths
import modules
from modules import*
import module as x
global variables
docs
version
class
class with docs
def
instance
comment to line x


This is the initial step-by step process which the script will create:

1)Ask for existing or new project

Would you like to open an existing project or create a new one?

1a)
if create new go to step 2

1b)
if open existing project go to step 3a

***

2)Create new project or file

Would you like to created a new project, or a single file? 

2a)
if create single file go to step 4

2b)
if create a project go to step 5

***


3)Select the folder of your existing project

3a)
open project, which would be a folder, not a single file, go to step 6a

3b)
open single existing file go to step 6b

***

4)Setup for single file creation

4a)
What would you like to name your new file?

raw_input

4b) would you like to use the script wizard to
setup your new file?

if yes go to script wizard(it's a choose your own adventure book)

if no
go to step 7a
**

5)Set up for project creation

5a) Two fields to fill in

What would you like to name your new project?
raw_input

You must create a new file to go in your project folder.
What would you like to call your first file?
raw_input

got to step 7b
**
**
6)open project window, or single file, depending
on which of step 3 user is coming from, then
begins 'recording' the current sessions input, until save
or exit

projects will have multiple files, so history
for each file open within the project

6a)
Open window with selection sidepanel of all files in project folder

6b)
Window with single file, and now side panel



*


7) New file has been created, or new project has been created with blank file

7a) open new window with file, but no open project folder

7b) open edit window with blank file and project folder contents, which
at this point consist of the single blank named file
**
***


sequence of events above have terminated at the editor window with
open file


**
**


The above excludes insertions, saving, creating a file or project into the main 
project window, which will probably call on some of the code from above.

If anyone is familiar with it, I'm thinking of using the blender game 
engine(just to combine the learning process of both), but the overall code is 
python, so I'm pretty sure I'm posting this to the right list.

Any suggestions, or critiques, are welcome.


Thanks,
David



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


Re: [Tutor] Bowing out

2010-03-03 Thread Robert
so you're "done" with Python ? :)


> On 3 March 2010 14:17, Kent Johnson  wrote:
>> After six years of tutor posts my interest and energy have waned and
>> I'm ready to move on to something new.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Bowing out

2010-03-03 Thread David Hutto


--- On Wed, 3/3/10, Sander Sweers  wrote:

From: Sander Sweers 
Subject: Re: [Tutor] Bowing out
To: "Kent Johnson" 
Cc: Tutor@python.org
Date: Wednesday, March 3, 2010, 11:06 AM

On 3 March 2010 14:17, Kent Johnson  wrote:
> After six years of tutor posts my interest and energy have waned and
> I'm ready to move on to something new.

Let me join the other people and thank you for your contribution to
this list. Good luck with something new :-)

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


Even if you didn't give me any personal help, I thank people like you. ...I bet 
this looks great on a resume.



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


Re: [Tutor] Bowing out

2010-03-03 Thread Glen Zangirolami
Thank you for all your hard work! I learned a ton from your tutorials.
Good luck on your future endeavors.


On Wed, Mar 3, 2010 at 10:18 AM, Albert-Jan Roskam  wrote:

> Hi Kent,
>
> Thank you very much for sharing your knowledge. Much appreciated!
>
> Cheers!!
> Albert-Jan
>
> ~~
> In the face of ambiguity, refuse the temptation to guess.
> ~~
>
> --- On *Wed, 3/3/10, Kent Johnson * wrote:
>
>
> From: Kent Johnson 
> Subject: [Tutor] Bowing out
> To: Tutor@python.org
> Date: Wednesday, March 3, 2010, 2:17 PM
>
>
> Hi all,
>
> After six years of tutor posts my interest and energy have waned and
> I'm ready to move on to something new. I'm planning to stop reading
> and contributing to the list. I have handed over list moderation
> duties to Alan Gauld and Wesley Chun.
>
> Thanks to everyone who contributes questions and answers. I learned a
> lot from my participation here.
>
> So long and keep coding!
> Kent
> ___
> 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 maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] getting diagonals from a matrix

2010-03-03 Thread Glen Zangirolami
I am not really sure of a better way but if your looking for a way to make
your code cleaner or more efficient
you can try Numpy - http://numpy.scipy.org/


On Tue, Mar 2, 2010 at 4:54 PM, David Eccles (gringer) wrote:

> I've managed to drum up some code to obtain a list containing joined
> diagonal
> elements of a matrix (I'm making a word finder generator), but am wondering
> if
> there's any better way to do this:
>
> # setup so code snippet works properly
> sizeW = 4
> sizeH = 3
> puzzleLayout = ['spam'] * (sizeW * sizeH)
>
> # Starting with, say, an array with these indices:
> # 0 1 2 3
> # 4 5 6 7
> # 8 9 A B
>
> # I want the following items for a back diagonal (not in square brackets):
> # [-2],[3],8 (+5) | div 4 = -1, 1, 2
> # [-1],4,9 (+5)   | div 4 = -1, 1, 2
> # 0,5,A (+5)  | div 4 =  0, 1, 2
> # 1,6,B (+5)  | div 4 =  0, 1, 2
> # 2,7,[C] (+5)| div 4 =  0, 1, 3
> # 3,[8],[D] (+5)  | div 4 =  0, 2, 3
>
> # in other words, increase sequence by sizeW + 1 each time (sizeW - 1
> # for forward diagonals), only selecting if the line you're on matches
> # the line you want to be on
>
> # back as in backslash-like diagonal
> puzzleDiagBack = [(''.join([puzzleLayout[pos*(sizeW+1) + i] \
> for pos in range(sizeH) if (pos*(sizeW+1) + i) / sizeW == pos])) \
> for i in range(-sizeH+1,sizeW)]
> puzzleDiagBackRev = [(''.join(reversed([puzzleLayout[pos*(sizeW+1) + i] \
> for pos in range(sizeH) if (pos*(sizeW+1) + i) / sizeW == pos]))) \
> for i in range(-sizeH+1,sizeW)]
> # fwd as in forwardslash-like diagonal
> puzzleDiagFwdRev = [(''.join([puzzleLayout[pos*(sizeW-1) + i] \
> for pos in range(sizeH) if (pos*(sizeW-1) + i) / sizeW == pos])) \
> for i in range(sizeW+sizeH-1)]
> puzzleDiagFwd = [(''.join(reversed([puzzleLayout[pos*(sizeW-1) + i] \
> for pos in range(sizeH) if (pos*(sizeW-1) + i) / sizeW == pos]))) \
> for i in range(sizeW+sizeH-1)]
>
> Cheers,
> David Eccles (gringer)
> ___
> 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] unittest

2010-03-03 Thread C.T. Matsumoto

Hello,

Can someone tell me the difference between unittests assertEqual and 
assertEquals?


Cheers,

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


Re: [Tutor] Encoding

2010-03-03 Thread Giorgio
Ops, i have another update:

string = u"blabla"

This is unicode, ok. Unicode UTF-8?

Thankyou

2010/3/3 Giorgio 

> Ok.
>
> So, how do you encode .py files? UTF-8?
>
> 2010/3/3 Dave Angel 
>
> Giorgio wrote:
>>
>>>

>  Depends on your python version. If you use python 2.x, you have to use
> a
>
>
 u before the string:

 s = u'Hallo World'


>>>
>>>
>>> Ok. So, let's go back to my first question:
>>>
>>> s = u'Hallo World' is unicode in python 2.x -> ok
>>> s = 'Hallo World' how is encoded?
>>>
>>>
>>>
>> Since it's a quote literal in your source code, it's encoded by your text
>> editor when it saves the file, and you tell Python which encoding it was by
>> the second line of your source file, right after the shebang line.
>>
>> A sequence of bytes in an html file should be should have its encoding
>> identified by the tag at the top of the html file.  And I'd  *guess* that on
>> a form result, the encoding can be assumed to match that of the html of the
>> form itself.
>>
>> DaveA
>>
>>
>
>
> --
> --
> AnotherNetFellow
> Email: anothernetfel...@gmail.com
>



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


[Tutor] lazy? vs not lazy? and yielding

2010-03-03 Thread John
Hi,

I just read a few pages of tutorial on list comprehenion and generator 
expression.  From what I gather the difference is "[ ]" and "( )" at the 
ends, better memory usage and the something the tutorial labeled as "lazy 
evaluation".  So a generator 'yields'.  But what is it yielding too?  

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


Re: [Tutor] sorting algorithm

2010-03-03 Thread Glen Zangirolami
http://www.sorting-algorithms.com/

It is a fantastic website that explains each kind of sort and how it works.
They also show you visuals how the sorts work and how fast they go based on
the amount of data.

Depending on the amount/kind of data I would choose a sorting algorithm that
fits your needs.

Bubble sorts tends to get worse the larger the data set but can be very
useful to sort small lists.

On Wed, Mar 3, 2010 at 3:56 AM, C.T. Matsumoto  wrote:

> Hello,
>
> This is follow up on a question I had about algorithms. In the thread it
> was suggested I make my own sorting algorithm.
>
> Here are my results.
>
> #!/usr/bin/python
>
> def sort_(list_):
>   for item1 in list_:
>   pos1 = list_.index(item1)
>   pos2 = pos1 + 1
>   try:
>   item2 = list_[pos2]
>   except IndexError:
>   pass
>
>   if item1 >= item2:
>   try:
>   list_.pop(pos2)
>   list_.insert(pos1, item2)
>   return True
>   except IndexError:
>   pass
>
> def mysorter(list_):
>   while sort_(list_) is True:
>   sort_(list_)
>
> I found this to be a great exercise. In doing the exercise, I got pretty
> stuck. I consulted another programmer (my dad) who described how to go about
> sorting. As it turned out the description he described was the Bubble sort
> algorithm. Since coding the solution I know the Bubble sort is inefficient
> because of repeated iterations over the entire list. This shed light on the
> quick sort algorithm which I'd like to have a go at.
>
> Something I haven't tried is sticking in really large lists. I was told
> that with really large list you break down the input list into smaller
> lists. Sort each list, then go back and use the same swapping procedure for
> each of the different lists. My question is, at what point to you start
> breaking things up? Is that based on list elements or is it based on
> memory(?) resources python is using?
>
> One thing I'm not pleased about is the while loop and I'd like to replace
> it with a for loop.
>
> Thanks,
>
> T
> ___
> 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] sorting algorithm

2010-03-03 Thread C.T. Matsumoto

Dave Angel wrote:

C.T. Matsumoto wrote:

Hello,

This is follow up on a question I had about algorithms. In the thread 
it was suggested I make my own sorting algorithm.


Here are my results.

#!/usr/bin/python

def sort_(list_):
   for item1 in list_:
   pos1 = list_.index(item1)
   pos2 = pos1 + 1
   try:
   item2 = list_[pos2]
   except IndexError:
   pass

   if item1 >= item2:
   try:
   list_.pop(pos2)
   list_.insert(pos1, item2)
   return True
   except IndexError:
   pass

def mysorter(list_):
   while sort_(list_) is True:
   sort_(list_)

I found this to be a great exercise. In doing the exercise, I got 
pretty stuck. I consulted another programmer (my dad) who described 
how to go about sorting. As it turned out the description he 
described was the Bubble sort algorithm. Since coding the solution I 
know the Bubble sort is inefficient because of repeated iterations 
over the entire list. This shed light on the quick sort algorithm 
which I'd like to have a go at.


Something I haven't tried is sticking in really large lists. I was 
told that with really large list you break down the input list into 
smaller lists. Sort each list, then go back and use the same swapping 
procedure for each of the different lists. My question is, at what 
point to you start breaking things up? Is that based on list elements 
or is it based on memory(?) resources python is using?


One thing I'm not pleased about is the while loop and I'd like to 
replace it with a for loop.


Thanks,

T


There are lots of references on the web about Quicksort, including a 
video at:

http://www.youtube.com/watch?v=y_G9BkAm6B8

which I think illustrates it pretty well.  It would be a great 
learning exercise to implement Python code directly from that 
description, without using the sample C++ code available.


(Incidentally, there are lots of variants of Quicksort, so I'm not 
going to quibble about whether this is the "right" one to be called 
that.)


I don't know what your earlier thread was, since you don't mention the 
subject line, but there are a number of possible reasons you might not 
have wanted to use the built-in sort.  The best one is for educational 
purposes.  I've done my own sort for various reasons in the past, even 
though I had a library function, since the library function had some 
limits.  One time I recall, the situation was that the library sort 
was limited to 64k of total data, and I had to work with much larger 
arrays (this was in 16bit C++, in "large" model).  I solved the size 
problem by using the  C++ sort library on 16k subsets (because a 
pointer was 2*2 bytes).  Then I merged the results of the sorts.  At 
the time, and in the circumstances involved, there were seldom more 
than a dozen or so sublists to merge, so this approach worked well 
enough.


Generally, it's better for both your development time and the 
efficiency and reliabilty of the end code, to base a new sort 
mechanism on the existing one.  In my case above, I was replacing what 
amounted to an insertion sort, and achieved a 50* improvement for a 
real customer.  It was fast enough that other factors completely 
dominated his running time.


But for learning purposes?  Great plan.  So now I'll respond to your 
other questions, and comment on your present algorithm.


It would be useful to understand about algorithmic complexity, the so 
called Order Function.  In a bubble sort, if you double the size of 
the array, you quadruple the number of comparisons and swaps.  It's 
order N-squared or O(n*n).   So what works well for an array of size 
10 might take a very long time for an array of size 1 (like a 
million times as long).  You can do much better by sorting smaller 
lists, and then combining them together.  Such an algorithm can  be 
O(n*log(n)).



You ask at what point you consider sublists?  In a language like C, 
the answer is when the list is size 3 or more.  For anything larger 
than 2, you divide into sublists, and work on them.


Now, if I may comment on your code.  You're modifying a list while 
you're iterating through it in a for loop.  In the most general case, 
that's undefined.  I think it's safe in this case, but I would avoid 
it anyway, by just using xrange(len(list_)-1) to iterate through it.  
You use the index function to find something you would already know -- 
the index function is slow.  And the first try/except isn't needed if 
you use a -1 in the xrange argument, as I do above.


You use pop() and push() to exchange two adjacent items in the list.  
Both operations copy the remainder of the list, so they're rather 
slow.  Since you're exchanging two items in the list, you can simply 
do that:

list[pos1], list[pos2] = list[pos2], list[pos1]

That also eliminates the need for the second try/except.

You mention being bothered by the while loop.  You could replace it 
with a simple fo

Re: [Tutor] Bowing out

2010-03-03 Thread David
>> After six years of tutor posts my interest and energy have waned and
>> I'm ready to move on to something new. 
Another new Python student that received understanding from your style
and knowledge, great teacher. I hope you will post some more tutorials
on Kents Korner when you find the time and motivation, thanks again;
David
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to wrap ctype functions

2010-03-03 Thread Jan Jansen
Hi there,

I wonder what's the best way to wrap given function calls (in this case
ctype function calls but more generally built-in functions and those kinds).
I have a huge c library and almost all functions return an error code. The
library also contains a function, that returns the corresponding error
message to the error code. So, what I need to do for every call to one of
the libraries functions looks like this:

error_code = my_c_library.SOME_FUNCTION_
CALL(argument)
if error_code != 0:
   error_message = my_c_library.GET_ERROR_TEXT(error_code)
   print "error in function call SOME_FUNCTION_CALL"
   print error_message
   my_c_library.EXIT_AND_CLEAN_UP()

Also, for some function calls I would need to do some preperations like:

error_code = my_c_library.LOG_IN_AS_ADMINISTRATOR(admin_user,
admin_password)
error_code = my_c_library.SOME_FUNCTION_CALL(argument)

I like the decorator idea, but I can't figure out if it's applicable here.
To be able to call the function in a manner like this would be great, e.g.

@change_user(admin_user, admin_password)
@error_handling
my_c_library.SOME_FUNCTION_CALL(argument)

Best regards,

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


Re: [Tutor] sorting algorithm

2010-03-03 Thread Dave Angel
(You forgot to do a Reply-All, so your message went to just me, rather 
than to me and the list )



C.T. Matsumoto wrote:

Dave Angel wrote:

C.T. Matsumoto wrote:

Hello,

This is follow up on a question I had about algorithms. In the 
thread it was suggested I make my own sorting algorithm.


Here are my results.

#!/usr/bin/python

def sort_(list_):
   for item1 in list_:
   pos1 = list_.index(item1)
   pos2 = pos1 + 1
   try:
   item2 = list_[pos2]
   except IndexError:
   pass

   if item1 >= item2:
   try:
   list_.pop(pos2)
   list_.insert(pos1, item2)
   return True
   except IndexError:
   pass

def mysorter(list_):
   while sort_(list_) is True:
   sort_(list_)

I found this to be a great exercise. In doing the exercise, I got 
pretty stuck. I consulted another programmer (my dad) who described 
how to go about sorting. As it turned out the description he 
described was the Bubble sort algorithm. Since coding the solution I 
know the Bubble sort is inefficient because of repeated iterations 
over the entire list. This shed light on the quick sort algorithm 
which I'd like to have a go at.


Something I haven't tried is sticking in really large lists. I was 
told that with really large list you break down the input list into 
smaller lists. Sort each list, then go back and use the same 
swapping procedure for each of the different lists. My question is, 
at what point to you start breaking things up? Is that based on list 
elements or is it based on memory(?) resources python is using?


One thing I'm not pleased about is the while loop and I'd like to 
replace it with a for loop.


Thanks,

T


There are lots of references on the web about Quicksort, including a 
video at:

http://www.youtube.com/watch?v=y_G9BkAm6B8

which I think illustrates it pretty well.  It would be a great 
learning exercise to implement Python code directly from that 
description, without using the sample C++ code available.


(Incidentally, there are lots of variants of Quicksort, so I'm not 
going to quibble about whether this is the "right" one to be called 
that.)


I don't know what your earlier thread was, since you don't mention 
the subject line, but there are a number of possible reasons you 
might not have wanted to use the built-in sort.  The best one is for 
educational purposes.  I've done my own sort for various reasons in 
the past, even though I had a library function, since the library 
function had some limits.  One time I recall, the situation was that 
the library sort was limited to 64k of total data, and I had to work 
with much larger arrays (this was in 16bit C++, in "large" model).  I 
solved the size problem by using the  C++ sort library on 16k subsets 
(because a pointer was 2*2 bytes).  Then I merged the results of the 
sorts.  At the time, and in the circumstances involved, there were 
seldom more than a dozen or so sublists to merge, so this approach 
worked well enough.


Generally, it's better for both your development time and the 
efficiency and reliabilty of the end code, to base a new sort 
mechanism on the existing one.  In my case above, I was replacing 
what amounted to an insertion sort, and achieved a 50* improvement 
for a real customer.  It was fast enough that other factors 
completely dominated his running time.


But for learning purposes?  Great plan.  So now I'll respond to your 
other questions, and comment on your present algorithm.


It would be useful to understand about algorithmic complexity, the so 
called Order Function.  In a bubble sort, if you double the size of 
the array, you quadruple the number of comparisons and swaps.  It's 
order N-squared or O(n*n).   So what works well for an array of size 
10 might take a very long time for an array of size 1 (like a 
million times as long).  You can do much better by sorting smaller 
lists, and then combining them together.  Such an algorithm can  be 
O(n*log(n)).



You ask at what point you consider sublists?  In a language like C, 
the answer is when the list is size 3 or more.  For anything larger 
than 2, you divide into sublists, and work on them.


Now, if I may comment on your code.  You're modifying a list while 
you're iterating through it in a for loop.  In the most general case, 
that's undefined.  I think it's safe in this case, but I would avoid 
it anyway, by just using xrange(len(list_)-1) to iterate through it.  
You use the index function to find something you would already know 
-- the index function is slow.  And the first try/except isn't needed 
if you use a -1 in the xrange argument, as I do above.


You use pop() and push() to exchange two adjacent items in the list.  
Both operations copy the remainder of the list, so they're rather 
slow.  Since you're exchanging two items in the list, you can simply 
do that:

list[pos1], list[pos2] = list[pos2], list[pos1]

That also eliminates

Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Alan Gauld

"Steven D'Aprano"  wrote


Comparisons with None almost always should be one of:

item is None
item is not None


Yes, but the reason I changed it (I originally had "is not") is that != is
a more general test for illustrating the use of 'if' within a LC which
seemed to be the real issue within the question.

--
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] Bowing out

2010-03-03 Thread Alan Gauld


"kevin parks"  wrote 


Wish Danny Yoo was still  here too.


Technically he is, but just keeps very, very quiet! :-)

Alan G.

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


Re: [Tutor] Encoding

2010-03-03 Thread Stefan Behnel

Giorgio, 03.03.2010 18:28:

string = u"blabla"

This is unicode, ok. Unicode UTF-8?


No, not UTF-8. Unicode.

You may want to read this:

http://www.amk.ca/python/howto/unicode

Stefan

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


Re: [Tutor] Bowing out

2010-03-03 Thread Ken G.
Thanks for helping out.  I enjoyed readying your posts.  Good luck on 
your future endeavors.


Ken

Kent Johnson wrote:
Hi all,

After six years of tutor posts my interest and energy have waned and
I'm ready to move on to something new. I'm planning to stop reading
and contributing to the list. I have handed over list moderation
duties to Alan Gauld and Wesley Chun.

Thanks to everyone who contributes questions and answers. I learned a
lot from my participation here.

So long and keep coding!
Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Encoding

2010-03-03 Thread Giorgio
Please let me post the third update O_o. You can forgot other 2, i'll put
them into this email.

---
>>> s = "ciao è ciao"
>>> print s
ciao è ciao
>>> s.encode('utf-8')

Traceback (most recent call last):
  File "", line 1, in 
s.encode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 5:
ordinal not in range(128)
---

I am getting more and more confused.

I was coding in PHP and was saving some strings in the DB. Was using
utf8_encode to encode them before sending to the utf8_unicode_ci table. Ok,
the result was that strings were "double encoded". To fix that I simply
removed the utf8_encode() function and put the "raw" data in the database
(that converts them in utf8). In other words, in PHP, I can encode a string
multiple times:

$c = "giorgio è giorgio";
$c = utf8_encode($c); // this will work in an utf8 html page
$d = utf8_encode($c); // this won't work, will print a strange letter
$d = utf8_decode($d); // this will work. will print an utf8 string

Ok, now, the point is: you (and the manual) said that this line:

s = u"giorgio è giorgio"

will convert the string as unicode. But also said that the part between ""
will be encoded with my editor BEFORE getting encoded in unicode by python.
So please pay attention to this example:

My editor is working in UTF8. I create this:

c = "giorgio è giorgio" // This will be an UTF8 string because of the file's
encoding
d = unicode(c) // This will be an unicode string
e = c.encode() // How will be encoded this string? If PY is working like PHP
this will be an utf8 string.

Can you help me?

Thankyou VERY much

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


Re: [Tutor] Encoding

2010-03-03 Thread Giorgio
I'm sorry, it's utf8_unicode_ci that's confusing me.

So, "UTF-8 is one of the most commonly used encodings. UTF stands for
"Unicode Transformation Format"" UTF8 is, we can say, a type of "unicode",
right? And what about utf8_unicode_ci in mysql?

Giorgio

2010/3/3 Stefan Behnel 

> Giorgio, 03.03.2010 18:28:
>
>  string = u"blabla"
>>
>> This is unicode, ok. Unicode UTF-8?
>>
>
> No, not UTF-8. Unicode.
>
> You may want to read this:
>
> http://www.amk.ca/python/howto/unicode
>
>
> Stefan
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



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


Re: [Tutor] lazy? vs not lazy? and yielding

2010-03-03 Thread Dave Angel

John wrote:

Hi,

I just read a few pages of tutorial on list comprehenion and generator 
expression.  From what I gather the difference is "[ ]" and "( )" at the 
ends, better memory usage and the something the tutorial labeled as "lazy 
evaluation".  So a generator 'yields'.  But what is it yielding too?  


John

  
A list comprehension builds a whole list at one time.  So if the list 
needed is large enough in size, it'll never finish, and besides, you'll 
run out of memory and crash.  A generator expression builds a function 
instead which *acts* like a list, but actually doesn't build the values 
till you ask for them.  But you can still do things like

   for item in  fakelist:

and it does what you'd expect.


You can write a generator yourself, and better understand what it's 
about.  Suppose you were trying to build a "list" of the squares of the 
integers between 3 and 15.  For a list of that size, you could just use 
a list comprehension.  But pretend it was much larger, and you couldn't 
spare the memory or the time.


So let's write a generator function by hand, deliberately the hard way.

def mygen():
   i = 3
   while i < 16:
   yield i*i
   i += 1
   return

This function is a generator, by virtue of that yield statement in it.  
When it's called, it does some extra magic to make it easy to construct 
a loop.


If you now use
for item in mygen():
  print item

Each time through the loop, it executes one more iteration of the 
mygen() function, up to the yield statement.  And the value that's put 
into item comes from the yield statement.


When the mygen() function returns (or falls off the end), it actually 
generates a special exception that quietly terminates the for/loop.


Now, when we're doing simple expressions for a small number of values, 
we should use a list comprehension.  When it gets big enough, switch to 
a generator expression.  And if it gets complicated enough, switch to a 
generator function.  The point here is that the user of the for/loop 
doesn't care which way it was done.


Sometimes you really need a list.  For example, you can't generally back 
up in a generator, or randomly access the [i] item.  But a generator is 
a very valuable mechanism to understand.


For a complex example, consider searching a hard disk for a particular 
file.  Building a complete list might take a long time, and use a lot of 
memory.  But if you use a generator inside a for loop, you can terminate 
(break) when you meet some condition, and the remainder of the files 
never had to be visited.  See os.walk()


DaveA

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


Re: [Tutor] Encoding

2010-03-03 Thread Dave Angel
(Don't top-post.  Put your response below whatever you're responding to, 
or at the bottom.)


Giorgio wrote:

Ok.

So, how do you encode .py files? UTF-8?

2010/3/3 Dave Angel 

  
I personally use Komodo to edit my python source files, and tell it to 
use UTF8 encoding.  Then I add a encoding line as the second line of the 
file.  Many times I get lazy, because mostly my source doesn't contain 
non-ASCII characters.  But if I'm copying characters from an email or 
other Unicode source, then I make sure both are set up.  The editor will 
actually warn me if I try to save a file as ASCII with any 8 bit 
characters in it.


Note:  unicode is 16 bit characters, at least in CPython 
implementation.  UTF-8 is an 8 bit encoding of that Unicode, where 
there's a direct algorithm to turn 16 or even 32 bit Unicode into 8 bit 
characters.  They are not the same, although some people use the terms 
interchangeably.


Also note:  An 8 bit string  has no inherent meaning, until you decide 
how to decode it into Unicode.  Doing explicit decodes is much safer, 
rather than assuming some system defaults.  And if it happens to contain 
only 7 bit characters, it doesn't matter what encoding you specify when 
you decode it.  Which is why all of us have been so casual about this.



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


Re: [Tutor] Encoding

2010-03-03 Thread Sander Sweers
On 3 March 2010 20:44, Giorgio  wrote:
 s = "ciao è ciao"
 print s
> ciao è ciao
 s.encode('utf-8')
> Traceback (most recent call last):
>   File "", line 1, in 
>     s.encode('utf-8')
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 5:
> ordinal not in range(128)

It is confusing but once understand how it works it makes sense.

You start with a 8bit string so you will want to *decode* it to unicode string.

>>> s = "ciao è ciao"
>>> us = s.decode('latin-1')
>>> us
u'ciao \xe8 ciao'
>>> us2 = s.decode('iso-8859-1')
>>> us2
u'ciao \xe8 ciao'

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


Re: [Tutor] How to wrap ctype functions

2010-03-03 Thread Hugo Arts
On Wed, Mar 3, 2010 at 6:43 PM, Jan Jansen  wrote:
> Hi there,
>
> I wonder what's the best way to wrap given function calls (in this case
> ctype function calls but more generally built-in functions and those kinds).
> I have a huge c library and almost all functions return an error code. The
> library also contains a function, that returns the corresponding error
> message to the error code. So, what I need to do for every call to one of
> the libraries functions looks like this:
>
> error_code = my_c_library.SOME_FUNCTION_
> CALL(argument)
> if error_code != 0:
>    error_message = my_c_library.GET_ERROR_TEXT(error_code)
>    print "error in function call SOME_FUNCTION_CALL"
>    print error_message
>    my_c_library.EXIT_AND_CLEAN_UP()
>
> Also, for some function calls I would need to do some preperations like:
>
> error_code = my_c_library.LOG_IN_AS_ADMINISTRATOR(admin_user,
> admin_password)
> error_code = my_c_library.SOME_FUNCTION_CALL(argument)
>
> I like the decorator idea, but I can't figure out if it's applicable here.
> To be able to call the function in a manner like this would be great, e.g.
>
> @change_user(admin_user, admin_password)
> @error_handling
> my_c_library.SOME_FUNCTION_CALL(argument)
>

Well, decorators only work on function definitions, not function
calls. What you could do is

a) write a function that takes your c function as an argument and does
the error handling for you

would probably look something like this:

def call_with_errorhandling(func, *args):
error_code = func(*args)
if error_code != 0:
error_message = my_c_library.GET_ERROR_TEXT(error_code)
print "error in function call SOME_FUNCTION_CALL"
    print error_message
    my_c_library.EXIT_AND_CLEAN_UP()

b) wrap all your c functions in a python function that does error handling.

the wrapper/decorator would look somewhat like this:

from functools import wraps

def with_error_handling(func):
@wraps(func)
def new_func(*args):
error_code = func(*args)
if error_code != 0:
error_message = my_c_library.GET_ERROR_TEXT(error_code)
print "error in function call SOME_FUNCTION_CALL"
    print error_message
    my_c_library.EXIT_AND_CLEAN_UP()
return new_func

and you'd wrap functions with it like so:

# old syntax
wrapped_function = with_error_handling(library.some_C_function)

#decorator syntax
@with_error_handling
def wrapped_function(*args)
return library.some_C_function(*args)

#just call your wrapped function now, the error handling will take place.
wrapped_function(argument)

You can write similar functions that do admin login in both ways. Both
approaches wrap C functions in python functions, so the overhead
should be about the same (the decorator way should consume somewhat
more memory, since it creates a new function object for everything you
wrap, but it's probably not very significant).

HTH,

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


Re: [Tutor] Bowing out

2010-03-03 Thread Kent Johnson
On Wed, Mar 3, 2010 at 11:51 AM, Robert  wrote:
> so you're "done" with Python ? :)

No, I hope not! I still love Python, but my enthusiasm for beginners
questions has pretty much gone away. I'm looking for a place where I
can contribute code rather than answers, possibly with the Mercurial
project or SunlightLabs.org.

Kent

>
>
>> On 3 March 2010 14:17, Kent Johnson  wrote:
>>> After six years of tutor posts my interest and energy have waned and
>>> I'm ready to move on to something new.
> ___
> Tutor maillist  -  tu...@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] unittest

2010-03-03 Thread Steven D'Aprano
On Thu, 4 Mar 2010 04:27:23 am C.T. Matsumoto wrote:
> Hello,
>
> Can someone tell me the difference between unittests assertEqual and
> assertEquals?

assertEqual, assertEquals and failUnless are three spellings for the 
same thing. There is no difference.



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


Re: [Tutor] Encoding

2010-03-03 Thread Sander Sweers
On 3 March 2010 22:41, Sander Sweers  wrote:
> It is confusing but once understand how it works it makes sense.

I remembered Kent explained it very clear in [1].

Greets
Sander

[1] http://mail.python.org/pipermail/tutor/2009-May/068920.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sorting algorithm

2010-03-03 Thread Steven D'Aprano
On Thu, 4 Mar 2010 04:34:09 am Glen Zangirolami wrote:
> http://www.sorting-algorithms.com/
>
> It is a fantastic website that explains each kind of sort and how it
> works. They also show you visuals how the sorts work and how fast
> they go based on the amount of data.

For actual practical work, you aren't going to beat the performance of 
Python's built-in sort. Unless you are an expert, don't even think 
about trying. If you are an expert, you've surely got better things to 
do.


> Depending on the amount/kind of data I would choose a sorting
> algorithm that fits your needs.
>
> Bubble sorts tends to get worse the larger the data set but can be
> very useful to sort small lists.

Bubble sorts are useless for any real work. They are a shockingly bad 
way of sorting anything beyond perhaps 4 or 5 items, and even for lists 
that small there are other algorithms which are barely more complicated 
but significantly faster.

Bubble sorts not only get slower as the list gets bigger, but they do so 
at an every increasing rate: let's say it takes 1 second to sort 100 
items (for the sake of the argument). Then it will take:

4 seconds to sort 200 items
9 seconds to sort 300 items
16 seconds to sort 400 items
25 seconds to sort 500 items
36 seconds to sort 600 items
...

and so forth. In other words, multiplying the number of items by a 
factor of X will multiply the time taken by X squared.

The only advantage of bubble sort is that the algorithm is easy to code. 
Otherwise it is horrible in just about every imaginable way.



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


Re: [Tutor] How to wrap ctype functions

2010-03-03 Thread Steven D'Aprano
On Thu, 4 Mar 2010 04:43:28 am Jan Jansen wrote:
> Hi there,
>
> I wonder what's the best way to wrap given function calls (in this
> case ctype function calls but more generally built-in functions and
> those kinds). I have a huge c library and almost all functions return
> an error code. The library also contains a function, that returns the
> corresponding error message to the error code. So, what I need to do
> for every call to one of the libraries functions looks like this:
>
> error_code = my_c_library.SOME_FUNCTION_
> CALL(argument)
> if error_code != 0:
>error_message = my_c_library.GET_ERROR_TEXT(error_code)
>print "error in function call SOME_FUNCTION_CALL"
>print error_message
>my_c_library.EXIT_AND_CLEAN_UP()


Something like this:

class MyCLibraryError(ValueError):  # Create our own exception.
pass


import functools
def decorate_error_code(func):
@functools.wraps(func)
def inner(*args, **kwargs):
error_code = func(*args, **kwargs)
if error_code != 0:
msg = my_c_library.GET_ERROR_TEXT(error_code)
my_c_library.EXIT_AND_CLEAN_UP()
raise MyCLibraryError(msg)
return inner  # note *no* brackets

Then wrap the functions:

some_function_call = decorate_error_code(
my_c_library.SOME_FUNCTION_CALL)
another_function_call = decorate_error_code(
my_c_library.ANOTHER_FUNCTION_CALL)



> Also, for some function calls I would need to do some preperations
> like:
>
> error_code = my_c_library.LOG_IN_AS_ADMINISTRATOR(admin_user,
> admin_password)
> error_code = my_c_library.SOME_FUNCTION_CALL(argument)
>
> I like the decorator idea, but I can't figure out if it's applicable
> here. To be able to call the function in a manner like this would be
> great, e.g.
>
> @change_user(admin_user, admin_password)
> @error_handling
> my_c_library.SOME_FUNCTION_CALL(argument)

That's not how the decorator syntax works. You can only use the 
@decorator syntax immediately above a function definition:

@error_handling
def some_function():
...


Otherwise, you use the decorator like a function, you give the name of 
another function as argument, and it returns a new function:

new_function = error_handling(some_function)




-- 
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 possible with condition statements?

2010-03-03 Thread Steven D'Aprano
On Thu, 4 Mar 2010 05:18:40 am Alan Gauld wrote:
> "Steven D'Aprano"  wrote
>
> > Comparisons with None almost always should be one of:
> >
> > item is None
> > item is not None
>
> Yes, but the reason I changed it (I originally had "is not") is that
> != is a more general test for illustrating the use of 'if' within a
> LC which seemed to be the real issue within the question.

List comps can include *any* comparison:

[x+1 for x in data if (3*x+2)**2 > 100*x or x < -5]





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


Re: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files.

2010-03-03 Thread Karim Liateni


Hello Alan, Steven,

I was narrow minded about this topic and did not see the benefits of 
these multiple Python

implementations. You opened my eyes.

Regards
Karim


Steven D'Aprano wrote:

On Tue, 2 Mar 2010 11:25:44 am Andreas Kostyrka wrote:
  

Furthermore I do not think that most of the "core" community has a
problem with the alternate implementations, as they provide very
useful functions (it helps on the architecture side, because it
limits somewhat what can be done, it helps on the personal side,
because it increases the value of Python skills, ...), ...



The Python development team values alternative implementations, as it 
gives Python the language a much wider user base.


It also allows other people to shoulder some of the development burden. 
For example, people who want Python without the limitations of the C 
call stack can use Stackless Python, instead of ordinary CPython. 
Google is sponsoring a highly optimized version of Python with a JIT 
compiler: Unladen Swallow. It looks likely that Unladen Swallow will 
end up being merged with CPython too, which will be a great benefit.



  


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


Re: [Tutor] parsing a "chunked" text file

2010-03-03 Thread Karim Liateni


Hello Steven,

Is there a big difference to write your first functions as below because 
I am not familiar with yield keyword?


def skip_blanks(lines):
   """Remove leading and trailing whitespace, ignore blank lines."""
   return [line.strip() in lines if line.strip()]


I tried to write as well the second function but it is not as straight 
forward.

I begin to understand the use of yield in it.

Regards
Karim

Steven D'Aprano wrote:

On Tue, 2 Mar 2010 05:22:43 pm Andrew Fithian wrote:
  

Hi tutor,

I have a large text file that has chunks of data like this:

headerA n1
line 1
line 2
...
line n1
headerB n2
line 1
line 2
...
line n2

Where each chunk is a header and the lines that follow it (up to the
next header). A header has the number of lines in the chunk as its
second field.



And what happens if the header is wrong? How do you handle situations 
like missing headers and empty sections, header lines which are wrong, 
and duplicate headers?


line 1
line 2
headerB 0
headerC 1
line 1
headerD 2
line 1
line 2
line 3
line 4
headerE 23
line 1
line 2
headerB 1
line 1



This is a policy decision: do you try to recover, raise an exception, 
raise a warning, pad missing lines as blank, throw away excess lines, 
or what?



  

I would like to turn this file into a dictionary like:
dict = {'headerA':[line 1, line 2, ... , line n1], 'headerB':[line1,
line 2, ... , line n2]}

Is there a way to do this with a dictionary comprehension or do I
have to iterate over the file with a "while 1" loop?



I wouldn't do either. I would treat this as a pipe-line problem: you 
have a series of lines that need to be processed. You can feed them 
through a pipe-line of filters:


def skip_blanks(lines):
"""Remove leading and trailing whitespace, ignore blank lines."""
for line in lines:
line = line.strip()
if line:
yield line

def collate_section(lines):
"""Return a list of lines that belong in a section."""
current_header = ""
accumulator = []
for line in lines:
if line.startswith("header"):
yield (current_header, accumulator)
current_header = line
accumulator = []
else:
accumulator.append(line)
yield (current_header, accumulator)


Then put them together like this:


fp = open("my_file.dat", "r")
data = {}  # don't shadow the built-in dict
non_blank_lines = skip_blanks(fp)
sections = collate_sections(non_blank_lines)
for (header, lines) in sections:
data[header] = lines


Of course you can add your own error checking.


  


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


Re: [Tutor] List comprehension possible with condition statements?

2010-03-03 Thread Alan Gauld

"Steven D'Aprano"  wrote


List comps can include *any* comparison:

[x+1 for x in data if (3*x+2)**2 > 100*x or x < -5]


Sure, but the wording suggested (maybe wrongly) that the OP 
was a real beginner and so the concept of an expression 
was likely to be foreign. Sticking with equalty or inequality 
seemed likely to be the most familiar test to him/her.


Trying to explain the differnce between is and == seemed 
like it would be a diversion from the primary objective, 
namely how to filter a list comp.


However I guess this discussion has covered that topic too
now, so once again we have managed to kill several 
sparrows with one round of buckshot... :-)



--
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] Understanding (Complex) Modules

2010-03-03 Thread Wayne Watson

First a little preamble before my questions.

Most of my work in Python has required modifying a program that uses 
modules that were imported by the original program. I've made some use 
of modules on a command line like math, and have used the idea of a 
qualifier.  On occasion, I've used examples from matplotlib that 
required from matplotlib.image import AxesImage. Further, I've created 
some simple classes, and produced  objects with them. No use of 
inheritance though.  So far so good.  In a few places, it is said 
modules are objects. I'm slightly puzzled by that, but in some way it 
seems reasonable from the standpoint of period notation. So far I have 
not created a module.


In Lutz's and Ascher's Learning Python, ed. 2, chap. 16, they describe 
the following example, among others:


module2.py as

print "starting to load ..."
import sys
def func(): pass
class klass: pass
print "done loading."

Their description of its use is quite readable.  It shows that there is 
some more to a module than a list of defs, for example.


Here comes the questions. Recently I began to use matplotlib, scipy, and 
pylab, mostly matplotlib. I've ground out a few useful pieces of code, 
but I'm fairly baffled by the imports required to get at various 
elements, of say, matplotlib (MPL).  Some of the MPL examples use of 
imports make sense, but how the writer pulled in the necessary elements 
is not.  How does one go about understanding the capabilities of such 
modules? MPL seems to have a lot of lower level components. Some of them 
are laid out over numerous pages as in the form of a, say, English 
language, description. How does one decipher this stuff.  For example, 
open the module in an editor and start looking at the organization? I 
thinkthe so called MPL guide ins 900 pages long. Even the numpy guide 
(reference?), I believe borders on 1000 pages. There must be some way to 
untangle these complex modules, I would think. Some of the tutorials 
seem nothing more than a template to follow for a particular problem.  
So far, looking at the plentiful number of examples of MPL, and probably 
some of the other modules mentioned above have not provided a lot of 
insight.


 Is there some relationship between modules and objects that I'm not 
seeing that could be of value?





--
   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

   Stop the illegal killing of dolphins and porpoises.
 
  Wrest the control of the world's fisheries from Japan.

Web Page:

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


Re: [Tutor] Understanding (Complex) Modules

2010-03-03 Thread David Hutto


--- On Wed, 3/3/10, Wayne Watson  wrote:

From: Wayne Watson 
Subject: [Tutor] Understanding (Complex) Modules
To: tutor@python.org
Date: Wednesday, March 3, 2010, 8:24 PM

First a little preamble before my questions.

Most of my work in Python has required modifying a program that uses modules 
that were imported by the original program. I've made some use of modules on a 
command line like math, and have used the idea of a qualifier.  On occasion, 
I've used examples from matplotlib that required from matplotlib.image import 
AxesImage. Further, I've created some simple classes, and produced  objects 
with them. No use of inheritance though.  So far so good.  In a few places, it 
is said modules are objects. I'm slightly puzzled by that, but in some way it 
seems reasonable from the standpoint of period notation. So far I have not 
created a module.

In Lutz's and Ascher's Learning Python, ed. 2, chap. 16, they describe the 
following example, among others:

module2.py as

print "starting to load ..."
import sys
def func(): pass
class klass: pass
print "done loading."

Their description of its use is quite readable.  It shows that there is some 
more to a module than a list of defs, for example.

Here comes the questions. Recently I began to use matplotlib, scipy, and pylab, 
mostly matplotlib. I've ground out a few useful pieces of code, but I'm fairly 
baffled by the imports required to get at various elements, of say, matplotlib 
(MPL).  Some of the MPL examples use of imports make sense, but how the writer 
pulled in the necessary elements is not.  How does one go about understanding 
the capabilities of such modules? MPL seems to have a lot of lower level 
components. Some of them are laid out over numerous pages as in the form of a, 
say, English language, description. How does one decipher this stuff.  For 
example, open the module in an editor and start looking at the organization? I 
thinkthe so called MPL guide ins 900 pages long. Even the numpy guide 
(reference?), I believe borders on 1000 pages. There must be some way to 
untangle these complex modules, I would think. Some of the tutorials seem 
nothing more than a template to follow for a
 particular problem.  So far, looking at the plentiful number of examples of 
MPL, and probably some of the other modules mentioned above have not provided a 
lot of insight.

 Is there some relationship between modules and objects that I'm not seeing 
that could be of value?




--            Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

             (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
              Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

               Stop the illegal killing of dolphins and porpoises.
                     
              Wrest the control of the world's fisheries from Japan.

                    Web Page:

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

How about importing your foot into your ass, for trying to ask an educated 
question and answering it through a false addresss by yourself.



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


Re: [Tutor] Encoding

2010-03-03 Thread spir
On Wed, 3 Mar 2010 16:32:01 +0100
Giorgio  wrote:

> Uff, encoding is a very painful thing in programming.

For sure, but it's true for any kind of data, not only text :-) Think at music 
or images *formats*. The issue is a bit obscured for text but the use of the 
mysterious, _cryptic_ (!), word "encoding".

When editing an image using a software tool, there is a live representation of 
the image in memory (say, a plain pixel 2D array), which is probably what the 
developper found most practicle for image processing. [text processing in 
python: unicode string type] When the job is finished, you can choose between 
various formats (png, gif, jpeg..) to save and or transfer it. [text: 
utf-8/16/32, iso-8859-*, ascii...]. Conversely, if you to edit an existing 
image, the software needs to convert back from the file format into its 
internal representation; the format need to be indicated in file, or by the 
user, or guessed.

The only difference with text is that there is no builtin image or sound 
representation _type_ in python -- only because text and sound are domain 
specific data while text is needed everywhere.

Denis
-- 


la vita e estrany

spir.wikidot.com

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


Re: [Tutor] unittest

2010-03-03 Thread C.T. Matsumoto

Steven D'Aprano wrote:

On Thu, 4 Mar 2010 04:27:23 am C.T. Matsumoto wrote:
  

Hello,

Can someone tell me the difference between unittests assertEqual and
assertEquals?



assertEqual, assertEquals and failUnless are three spellings for the 
same thing. There is no difference.




  

Thanks,
Okay, does anyone know why unittests have 3 ways to do the same thing?

Thanks.

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


Re: [Tutor] Bowing out

2010-03-03 Thread Christian Witts

Kent Johnson wrote:

Hi all,

After six years of tutor posts my interest and energy have waned and
I'm ready to move on to something new. I'm planning to stop reading
and contributing to the list. I have handed over list moderation
duties to Alan Gauld and Wesley Chun.

Thanks to everyone who contributes questions and answers. I learned a
lot from my participation here.

So long and keep coding!
Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

  


Best of luck for all your future endeavours Kent.
/salute

--
Kind Regards,
Christian Witts


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


Re: [Tutor] Encoding

2010-03-03 Thread python
Denis,

That was a great explanation!! I'm not the OP, but your explanation
really clicked with me.

Regards,
Malcolm


For sure, but it's true for any kind of data, not only text :-) Think at
music or images *formats*. The issue is a bit obscured for text but the
use of the mysterious, _cryptic_ (!), word "encoding".

When editing an image using a software tool, there is a live
representation of the image in memory (say, a plain pixel 2D array),
which is probably what the developper found most practicle for image
processing. [text processing in python: unicode string type] When the
job is finished, you can choose between various formats (png, gif,
jpeg..) to save and or transfer it. [text: utf-8/16/32, iso-8859-*,
ascii...]. Conversely, if you to edit an existing image, the software
needs to convert back from the file format into its internal
representation; the format need to be indicated in file, or by the user,
or guessed.

The only difference with text is that there is no builtin image or sound
representation _type_ in python -- only because text and sound are
domain specific data while text is needed everywhere.

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


Re: [Tutor] Bowing out

2010-03-03 Thread python
Hi Kent,

Your posts and web pages really helped me during my early days with
python.

Wishing you great success in your new endeavors!!!

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


Re: [Tutor] Encoding

2010-03-03 Thread spir
On Wed, 3 Mar 2010 20:44:51 +0100
Giorgio  wrote:

> Please let me post the third update O_o. You can forgot other 2, i'll put
> them into this email.
> 
> ---
> >>> s = "ciao è ciao"
> >>> print s
> ciao è ciao
> >>> s.encode('utf-8')
> 
> Traceback (most recent call last):
>   File "", line 1, in 
> s.encode('utf-8')
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 5:
> ordinal not in range(128)
> ---
> 
> I am getting more and more confused.

What you enter on the terminal prompt is text, encoded in a format (ascii, 
latin*, utf*,...) that probably depends on your system locale. As this format 
is always a sequence of bytes, python stores it as a plain str:
>>> s = "ciao è ciao"
>>> s,type(s)
('ciao \xc3\xa8 ciao', )
My system is parametered in utf8. c3-a8 is the repr of 'é' in utf8. It needs 2 
bytes because of the rules of utf8 itself. Right?

To get a python unicode string, it must be decoded from its format, for me utf8:
>>> u = s.decode("utf8")
>>> u,type(u)
(u'ciao \xe8 ciao', )
e8 is the unicode code for 'è' (decimal 232). You can check that in tables. It 
needs here one byte only because 232<255.

[comparison with php]

> Ok, now, the point is: you (and the manual) said that this line:
> 
> s = u"giorgio è giorgio"
> 
> will convert the string as unicode.

Yes and no: it will convert it *into* a  string, in the sense of a 
python representation for universal text. When seeing u"..." , python will 
automagically *decode* the part in "...", taking as source format the one you 
indicate in a pseudo-comment on top of you code file, eg:
# coding: utf8
Else I guess the default is the system's locale format? Or ascii? Someone knows?
So, in my case u"giorgio è giorgio" is equivalent to "giorgio è 
giorgio".decode("utf8"):
>>> u1 = u"giorgio è giorgio"
>>> u2 = "giorgio è giorgio".decode("utf8")
>>> u1,u2
(u'giorgio \xe8 giorgio', u'giorgio \xe8 giorgio')
>>> u1 == u2
True

> But also said that the part between ""
> will be encoded with my editor BEFORE getting encoded in unicode by python.

will be encoded with my editor BEFORE getting encoded in unicode by python
-->
will be encoded *by* my editor BEFORE getting *decoded* *into* unicode by python

> So please pay attention to this example:
> 
> My editor is working in UTF8. I create this:
> 
> c = "giorgio è giorgio" // This will be an UTF8 string because of the file's
> encoding
Right.
> d = unicode(c) // This will be an unicode string
> e = c.encode() // How will be encoded this string? If PY is working like PHP
> this will be an utf8 string.

Have you tried it?
>>> c = "giorgio è giorgio" 
>>> d = unicode(c)
Traceback (most recent call last):
  File "", line 1, in 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 8: ordinal 
not in range(128)

Now, tell us why! (the answer is below *)

> Can you help me?
> 
> Thankyou VERY much
> 
> Giorgio


Denis

(*)
You don't tell which format the source string is encoded in. By default, python 
uses ascii (I know, it's stupid) which max code is 127. So, 'é' is not 
accepted. Now, if I give a format, all works fine:
>>> d = unicode(c,"utf8")
>>> d
u'giorgio \xe8 giorgio'

Note: unicode(c,format) is an alias for c.decode(format):
>>> c.decode("utf8")
u'giorgio \xe8 giorgio'


la vita e estrany

spir.wikidot.com

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


[Tutor] object representation

2010-03-03 Thread spir
Hello,

In python like in most languages, I guess, objects (at least composite ones -- 
I don't know about ints, for instance -- someone knows?) are internally 
represented as associative arrays. Python associative arrays are dicts, which 
in turn are implemented as hash tables. Correct?
Does this mean that the associative arrays representing objects are implemented 
like python dicts, thus hash tables?

I was wondering about the question because I guess the constraints are quite 
different:
* Dict keys are of any type, including heterogeneous (mixed). Object keys are 
names, ie a subset of strings.
* Object keys are very stable, typically they hardly change; usually only 
values change. Dicts often are created empty and fed in a loop.
* Objects are small mappings: entries are explicitely written in code (*). 
Dicts can be of any size, only limited by memory; they are often fed by 
computation.
* In addition, dict keys can be variables, while object keys rarely are: they 
are literal constants (*).

So, I guess the best implementations for objects and dicts may be quite 
different. i wonder about alternatives for objects, in particuliar trie and 
variants: http://en.wikipedia.org/wiki/Trie, because they are specialised for 
associative arrays which keys are strings.

denis

PS: Would someone point me to typical hash funcs for string keys, and the one 
used in python?

(*) Except for rare cases using setattr(obj,k,v) or obj.__dict__[k]=v.
-- 


la vita e estrany

spir.wikidot.com

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