Reputation: 217
I have a list, the_list = [[3, 2, 0, 1, 4, 5], [4, 2, 1, 3, 0, 5], [0, 1, 2, 3, 4, 5], [1, 5, 2, 4, 3, 0]]
.How do I find out the distance from the smallest element to the largest element in the list.For example, for the first sublist in the_list
the index for the smallest element 0
is 2
and the index for the largest element 5
is 5
. Therefore, the distance between the two indices is 3
Thus I get the following output:
3
1
5
0
Edit: For the last output, it is 0 because the list ends there and assume that the list only looks for distance in bound to the right
Upvotes: 4
Views: 182
Reputation: 131
I don't know python very much, but the algorithm could be similar to this (in pseudocode):
Foreach list in the_list do begin
Min:=maxint;
MinPos:=0;
Max:=0;
MaxPos:=0;
For I := 0 to list.length do begin
If list[i] > Max then begin
Max := list[i];
MaxPos := i;
End;
If list[i] < Min then begin
Min := list[i];
MinPos := i;
End;
End;
If MinPos < MaxPos then
Write MaxPos - MinPos;
Elsewhere
Write 0;
End;
(I'm sorry, I wrote this post at the mobile, and I couldn't format correctly the text).
Upvotes: 0
Reputation: 5668
>>>list(map(lambda x: x.index(max(x)) - x.index(min(x)) if x.index(max(x)) - x.index(min(x)) > 0 else 0 ,l))
[3, 1, 5, 0]
Upvotes: 1
Reputation: 236124
Try this:
lst = [[3, 2, 0, 1, 4, 5], [4, 2, 1, 3, 0, 5], [0, 1, 2, 3, 4, 5], [1, 5, 2, 4, 3, 0]]
[max(s.index(max(s)) - s.index(min(s)), 0) for s in lst]
=> [3, 1, 5, 0]
Upvotes: 1