Golden
Golden

Reputation: 417

Most pythonic way to find relation between two elements in a list

Let's say I have the following list:

l = ["watermelon", "banana", "orange", "apple"]

And I want to write a function that returns whatever the element is before another element in the list. for example:

>> is_before("banana", "watermelon")
>> False
>> is_before("banana", "apple")
>> True

What is the most pythonic way to write such a function?

Upvotes: 0

Views: 73

Answers (2)

mohammed wazeem
mohammed wazeem

Reputation: 1328

mylist = ["watermelon", "banana", "orange", "apple"]

def is_before(prev_item, target, arr):
    return prev_item in arr[:arr.index(target)]

>>>is_before("banana", "apple", mylist)
True
>>>is_before("banana", "watermelon", mylist)
False

If you want to handle duplicates you can use something like this

def find_item_last_index(count, item, arr, index=0):
    # A recursive function for finding the last index of an item in a list
    if count == 1:
        return index + arr.index(item)
    return (find_item_last_index(count-1, item, arr[arr.index(item)+1:],  
                                 index+arr.index(item)+1))

def is_before(prev_item, target, arr):
    return prev_item in arr[: find_item_last_index(arr.count(target), target, arr)]

mylist =  ["watermelon", "apple", "banana", "orange", "apple"]

>>>is_before("banana", "apple", mylist)
True
>>>is_before("banana", "watermelon", mylist)
False

Upvotes: 1

user2390182
user2390182

Reputation: 73470

You could do (assuming there are no duplicates):

l = ["watermelon", "banana", "orange", "apple"]

indeces = {w: i for i, w in enumerate(l)}

def is_previous(x, y):
    return indeces[x] < indeces[y]

>>> is_previous("banana", "watermelon")
False
>>> is_previous("banana", "apple")
True

This does not handle the case where any of the arguments aren't in the initial list.

Upvotes: 3

Related Questions