newbie question
Dennis Lee Bieber
wlfraed at ix.netcom.com
Sun Dec 15 19:31:09 EST 2002
Classified fed this fish to the penguins on Saturday 14 December 2002
07:53 am:
> Hi, I'm new to python and I encounter a problem...
> I'm frustrated because the following code won't work...
> a=[('a',1),('c',5),('k',5),('o',3), ('i',3)]
> for i in range(0, len(a)-1):
> for j in range(1, len(a)):
> if a[i][1]>a[j][1]:
> a[i],a[j]=a[j],a[i]
> print a
> it appears that the bubble sort will not sort a...
> I guess I must have made a stupid mistake somewhere...
> I'm a newbie, I don't know how to use the debugger...
> thanks to whoever that can help me!
Firstly, I don't think that is a bubble-sort algorithm; the inner loop
is hitting the same data already processed. I'd need to spend some time
studying to create the proper bubble sort, but the following seems more
effective than yours: (unwrap the long first line)
a=[('a',1),('c',5),('k',5),('o',3), ('i',3), ('m', 1), ('n', 0),
('z',2)]
for i in range(0, len(a)-1):
for j in range(i+1, len(a)):
if a[i][1]>a[j][1]:
print "swapping", i, j
print a
a[i],a[j]=a[j],a[i]
print a
print a
The primary change I made is to run the inner loop from the outer
loop+1, not from 1 on each pass.
--
> ============================================================== <
> wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
> wulfraed at dm.net | Bestiaria Support Staff <
> ============================================================== <
> Bestiaria Home Page: http://www.beastie.dm.net/ <
> Home Page: http://www.dm.net/~wulfraed/ <
More information about the Python-list
mailing list