[Tutor] Iterable Understanding
Alan Gauld
alan.gauld at btinternet.com
Sat Nov 14 19:48:51 CET 2009
"Stephen Nelson-Smith" <sanelson at gmail.com> wrote
> List 1 List 2 List 3
> (1, cat) (2, fish) (1, cabbage)
> (4, dog) (5, pig) (2, ferret)
> (5, phone) (6, horse) (3, sausage)
>
> Won't this result in the lowest number *per row* being added to the
> new list? Or am I misunderstanding how it works?
You are right.
I think the algorithm you need goes something like
- read the first item from each flie
- find the lowest item add it to the result
- keep taking items from that file until you find one greater than
- the next lowest item that you first found, put that cvalue in place
of the original lowest value
- repeat for the new lowest value until it matches the next lowest value
and so on until all files are empty
To taker the trivial case of 2 files containing the odd and every other
even
numbers respectively
A = [1, 3, 5, 7,...
B = [2, 6, 10...
lowA = 1
low2 = 2
load lowA into result, get next from A -> 3
lowA becomes 3
load next lowest (lowB=2) into result, get next from B -> 6
lowB becomes 6
load next lowest (lowA=3) into result, get next from A -> 5
load 5 in result and get next from A -> 7
load 7 in lowA
load next lowest (lowB=6) into result, get next from B -> 10
load next lowest(lowA=7) into result, get next from A -> 9
etc until all files are empty
Obviously you can create a dictionary or list of your lowest values
and the matching file. You can simplify the algorithm by always
loading the latest value into lowX and alwayss checking for the
lowest value before storing it, but for high volumes the extra checks
will mount up.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list