-2
def PositionLast(x,s):
    position = -1
    for i in s:
        position +=1
        if i == x:
            return position

Is what I have so far - just returns the first. Is there a way using similar means to return the last ? Thanks in advance

Mazdak
  • 105,000
  • 18
  • 159
  • 188

3 Answers3

1

Seems that you want to return the last position of a character in your string.For that aim you can traverse your string from end to start :

def PositionLast(x,s):
    length=len(s)
    position = -1
    for i in s[::-1]:
        position +=1
    if i == x:
        return length-position 

But as a more pythonic way you can use enumerate and a generator expression within next function :

def PositionLast(x,s):
    return next(i for i,j in enumerate(s)[::-1] if j==x)

If you don't want to reverse the string you can use a deque object with max length one to preserve the positions, thus at the end it will preserver the last index :

from dollections import deque
def PositionLast(x,s,d=deque(maxlen=1)):
    position = -1
    for i in s:
        position +=1
    if i == x:
        d.append(position)
    return d.pop()
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • Yeah that works but I want it in a similar way to what I have here ideally - So my way will return the position of the first instance of the object, I need a similar way to return the last instance. – user5390224 Oct 14 '15 at 17:15
  • @user5390224 The first suggestion is based on your algorithm! – Mazdak Oct 14 '15 at 17:16
0

Is it just me or this looks like a CS assignment?

Anyway, one way is to iterate through the string in inverse order and use your code:

def PositionLast(x,s):
    position = -1
    for i in reversed(s):
        position +=1
    if i == x
        return position

There are of course many other ways to do this, and if this is really an assignment you should work a bit on it and figure them out.

0

You can use this:

def PositionLast(x,s):
  return len(x) - x[::-1].index(s) - 1

which basically reverses the array, looks for the first index, then finds the position in the original list.

ergonaut
  • 6,929
  • 1
  • 17
  • 47