[Tutor] sorting in python

2006-06-12 Thread Kermit Rose
  
Message: 6
Date: Mon, 12 Jun 2006 05:59:16 -0400
From: Kent Johnson [EMAIL PROTECTED]
Subject: Re: [Tutor] assignment statements in python
 
Actually sorting doesn't require copying the values in the list, it just
requires moving values to different locations of the list.
 
 
*
 
Yes.  I wish to know how I can , for examplem,
 
given 
B = [1,2,4,5],
 
move B[3] to a  position of newly created B[4],
move B[2] to position of B[3]
Assign value 3 to position B[2].
 
That is,  I wish to insert the value 3, into it's sorted place within the
already sorted list B.
 

 

 
A list element is somewhat like a name - it is a reference to a value,
not a container for a value.
 
If you say
a=[1,2,3]
B=a
 
then a and B refer to the same list. Likewise, if you say
x=[ [1,2,3], [4,5,6] ]
x[1] = x[0]
 
then x[1] and x[0] refer to the same list.
 
 
***
 x = [ [1,2,3],[4,5,6]]
 x
[[1, 2, 3], [4, 5, 6]]
 x[1] = x[0]
 x
[[1, 2, 3], [1, 2, 3]]
 
 
Needed to make sure I understood what would happen.
 
Does the value [4,5,6] get erased at this point?
 
 

 
 
 
 If you want x[1] (or B) to
refer to a new list, you have to copy the old list:
x[1] = x[0][:]
 
list[:] is the slice of the list that goes from the beginning to the end
- a copy.
 
 
*
 
I missed the significance of the [:] slice until you explained it.
 
 
So, now I could write my code as
 
 
#  to insert 3 between 2 and 4 in 
 
B = [1,2,4,5]
 
B.append(B[3:3])
 
# I expected B[4] to have the value 5 at this point. 
# It is empty.   Why?
#  So, I compensate by making the next line
 
B[4] = B[3:3]
 
# B[4] is still an empty list.   Why?
 
# I try 
 
B[4] = B[3]
 
#  That seemed to work.
 
 
B[3] = B[2]
 
# Now I try
 
B[2] = 3
 
 
That worked.
 
However, I don't see the difference between this code,
 
and what I had before that did not work.
 
 
 
Kermit[EMAIL PROTECTED]  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Kent
 
 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sorting in python

2006-06-12 Thread Python
On Mon, 2006-06-12 at 11:26 -0400, Kermit Rose wrote:
 #  to insert 3 between 2 and 4 in 
  
 B = [1,2,4,5]
  
 B.append(B[3:3])

 B[3:3]
[]
 B[3:4]
[5]
 B[0:1]
[1]
 B[:2]
[1, 2]
 B.append(B[3:3])
 B
[1, 2, 4, 5, []]

  
 # I expected B[4] to have the value 5 at this point. 
 # It is empty.   Why?

You appended an empty list.  

Note that slice notation returns a list, so you would more commonly use
B.extend(B[0:3]) to avoid nested lists.


The number before the : is the index to include from
The number after the : is the index to exclude

Slices are half-open intervals.  The lower-bound is included while the
upper-bound is excluded.

http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF
Provides an excellent justification for this approach
(cited recently on this list)

-- 
Lloyd Kvam
Venix Corp

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor