Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing list elements

I make a simple code:

arr =  [4, 9, 5, 3, 2, 10]
kpmp = [] # Empty list to store the comparison

for i in arr:
    if i>0:
        x = 0
        j = i
        while j>=0:
            j-=1
            if arr[i] > arr[j]:
                x+=1
    kpmp.append(x)
print(kpmp)

But, I got this error:

Traceback (most recent call last):
  File "python", line 11, in <module>
IndexError: list index out of range

Which is this line if arr[i] > arr[j]:

The expected output I'd like to print is a list [0, 0, 1, 3, 4, 0]
Explanation:
arr = [4, 9, 5, 3, 2, 10]
1. 4 has nothing to compare so the result is 0
2. 9 > 4 the result is 0
3. 4 < 5 < 9 the result is 1
4. 3 < 4 < 5 < 9 the result is 3
5. 2 < 3 < 4 < 5 < 9 the result is 4
6. Well, 10 is the greatest in the list so the result is 0

I got stuck here, kinda basic knowledge with Python, though.
Thanks for your help!

like image 940
qod Avatar asked Nov 30 '25 11:11

qod


1 Answers

You are currently using elements of list as indices, which will cause an out of range error if they are greater than the length of your list.

Since arr contains 9, this will throw an out of range error. Also, you need to define x before your if statement, or else you will get a variable not found error.

Here is a different solution to your problem using a list comprehension and slicing:

x = [4, 9, 5, 3, 2, 10]
final = [sum(k > j for k in x[:i]) for i, j in enumerate(x)]

# [0, 0, 1, 3, 4, 0]

Explanation:

sum(k > j for k in x[:i])

This counts all previous values that are greater than the current value. x[:i] gets all elements before the current element in your list.

like image 166
user3483203 Avatar answered Dec 02 '25 02:12

user3483203



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!