Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Check if element is less than the next elements

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[3] < A[3]

And I don’t want to check the last element.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading