swordfish
swordfish

Reputation: 13

Trying to understand the double index in python

def countSmaller(self, nums):
        def sort(enum):
            half = len(enum) / 2
            if half:
                left, right = sort(enum[:half]), sort(enum[half:])
                for i in range(len(enum))[::-1]:
                    if not right or left and left[-1][1] > right[-1][1]:
                        smaller[left[-1][0]] += len(right)
                        enum[i] = left.pop()
                    else:
                        enum[i] = right.pop()
            return enum
        smaller = [0] * len(nums)
        sort(list(enumerate(nums)))
        return smaller

I am a new python coder so this query!.. In left[-1][1] , I understood [-1] makes me think the last index but what does the second index [1] mean.

Upvotes: 1

Views: 19863

Answers (2)

Oleksandr Dashkov
Oleksandr Dashkov

Reputation: 2838

The second index does the same as the first but with the nested value. For exemple:

a = [(1, 2), (2, 3), (3, 4)]
a[-1]  # (3, 4)
a[-1][1]  # 4

In your example you don't have a list with numbers but enumerate objects converted to lists

sort(list(enumerate(nums)))

It means that you have data like this:

nums = [1, 2, 3, 4, 5]
enum_list = list(enumerate(nums))  # [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]

Upvotes: 3

staad
staad

Reputation: 836

It seems like left is an array containing tuples. I.e. Each element of the array is a tuple.

Ex: left=[(value1oftuple1,value2oftuple1),(value1ofarray2,value2ofarray2)]

In this case left[-1][1] would reference the first value in the last element of the array (value1ofarray2).

I found this by running your code and printing the value of left just before your code calls left[-1][1]. This way you can see what data type left is.

Upvotes: 2

Related Questions