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
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
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()
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.
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.