-1

""" If every character appears more than once, return -1. Example input: s: "Who wants hot watermelon?. output: 8."""

def findLastIndex(str, x): 
    index = -1
    for i in range(0, len(str)): 
        if str[i] == x: 
            index = i 
    return index 

# String in which char is to be found 
str = "Who wants hot watermelon"

# char whose index is to be found 
x = 's'

index = findLastIndex(str, x) 

if index == -1: 
    print("Character not found") 
else: 
    print(index) 
Fioat N
  • 1
  • 1
  • Does this answer your question? [Count the number occurrences of a character in a string](https://stackoverflow.com/questions/1155617/count-the-number-occurrences-of-a-character-in-a-string) – glotchimo Nov 30 '19 at 19:20
  • BTW, the output for your input string should be 0, since upper case `W` appears in it only once. – goodvibration Nov 30 '19 at 19:26

2 Answers2

0

Try this:

def func(s):
    for i in range(len(s)):
        if s.count(s[i]) == 1:
            return i
    return -1
goodvibration
  • 5,980
  • 4
  • 28
  • 61
0

I think this is a simple way to do it:

def f(s):
    for i,c in enumerate(s):
        if s.count(c) == 1:
            return i
    return -1

assert f("who wants hot watermelon?") ==  8
assert f("aa") == -1
Christian Sloper
  • 7,440
  • 3
  • 15
  • 28