I wish to find the last occurrence of an item 'x' in sequence 's', or to return None if there is none and the position of the first item is equal to 0
This is what I currently have:
def PositionLast (x,s):
count = len(s)+1
for i in s:
count -= 1
if i == x:
return count
for i in s:
if i != x:
return None
When I try:
>>>PositionLast (5, [2,5,2,3,5])
>>> 4
This is the correct answer. However when I change 'x' to 2 instead of 5 I get this:
>>>PositionLast(2, [2,5,2,3,5])
>>> 5
The answer here should be 2. I am confused as to how this is occurring, if anyone could explain to what I need to correct I would be grateful. I would also like to complete this with the most basic code possible.
Thank you.
Get the last element of the list using the “length of list - 1” as an index and print the resultant last element of the list. Get the last element of the list using − 1(negative indexing) as the index and print the resultant last element of the list.
a=["first","second from last","last"] # A sample list print(a[0]) #prints the first item in the list because the index of the list always starts from 0. print(a[-1]) #prints the last item in the list.
To do it efficiently, enumerate the list in reverse order and return the index of the first matching item (or None
by default), e.g.:
def PositionLast(x, s):
for i, v in enumerate(reversed(s)):
if v == x:
return len(s) - i - 1 # return the index in the original list
return None
Avoid reversing the list using slice notation (e.g. s[::-1]
) as that would create a new reversed list in memory, which is not necessary for the task.
Your logic is incorrect, because you return the count if i==x
and you have an extra loop at the trailing of your function.
Instead you loop over the reverse forms of enumerate of your list and return the index of first occurrence :
def PositionLast (x,s):
return next(i for i,j in list(enumerate(s))[::-1] if j == x)
Demo:
print PositionLast (2, [2,5,2,3,5,3])
2
print PositionLast (3, [2,5,2,3,5,3])
5
print PositionLast (5, [2,5,2,3,5,3])
4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With