1

I'm writing a program that compares two indexes in a string, and returns either True or False depending on if the indexes have the same value. It's also supposed to return false if either of the indexes is outside of the string, but I cant figure out how to move forward without just getting an error message. Here's what I have so far:

def samat(jono,a,b):
    if jono[a] in jono and jono[b] in jono:
        return (jono[a]==jono[b])

if __name__ == "__main__":
    print(samat("koodari", 1, 2))

Student
  • 127
  • 1
  • 8

2 Answers2

3

You can catch the exception and return False when have a error of index

def samat(jono,a,b):

    # check if it the same value
    try: 
        return jono[a]==jono[b]
    except IndexError:
        return False

output:

if __name__ == "__main__":
    print(samat("koodari", -69, 2)) # False
    print(samat("koodari", 420, 2)) # False
    print(samat("koodari", 1, 2)) # True
jacob galam
  • 781
  • 9
  • 21
2

This answer assumes non-negative indexes. Given this fact, we can test if indexes a and b are larger than the length of jono and return False, or compare the character in these positions, and return the result.

def samat(jono, a, b):
    if a >= len(jono) or b >= len(jono):
        return False
    return jono[a] == jono[b]

if __name__ == "__main__":
    print(samat("koodari", 1, 2))

Alternatively you could make the samat function, even shorter, as user @tobias_k suggested:

def samat(jono, a, b):
    return 0 <= a < len(jono) and 0 <= b < len(jono) and jono[a] == jono[b]

Output:

True
solid.py
  • 2,782
  • 5
  • 23
  • 30