I want to check each element in the list, if it is smaller than the next after it and print all the numbers that met the condition.
Example:
A = [3,1,2,4]
A[0] < A[3]
A[1] < A[2]
A[1] < A[3]
A[2] < A[3]
And I don't want to check the last element.
What is the best way to do that?
I tried to do that with for loop:
A = [3,1,2,4]
for i in range(0,len(A)-1):
for j in range(i,len(A)-1):
if A[j] < A[j + 1]:
print(A[j],A[j + 1])
A[j] = A[j + 1]
And the result is:
1 2
2 4
1 4
While the desired results is:
3 4
1 2
1 4
2 4
You should fix some indices in comparison as well as the ranges. The first counter i
should iterate from 0
to len(A)-1
and the second counter should iterate from i+1
to len(A)
.
The comparison should happen between A[i]
, A[j]
instead of A[j]
,A[j+1]
. No need for the last line A[j] = A[j + 1]
because the counters get incremented automatically.
A = [3, 1, 2, 4]
for i in range(0,len(A)-1):
for j in range(i+1,len(A)):
if A[i] < A[j]:
print(A[i],A[j])
3 4
1 2
1 4
2 4