Exercise 97 *

Write a python algorithm as a function which takes as parameter a couple (s, x) formed by a text string s and a char x and which returns the index of the second position of the character x in the string s without using no predefined function. The function should return -1 if the char x is not in the string s. Example if s = ‘python programming language’ and x = ‘p’, the function returns the index: 7


# function that determines the postions list of char x in within the string s 
def listPositions (s, x):
# initialize the list of positions of the character x in the string s
listPos = []

# browse the characters of the string s
for i in range (0, len (s)):
if s [i] == x:
listPos.append (i)
if len (listPos) >= 2:
return listPos [1]
return -1

# Example
s, x = 'python programming language', 'p'
print ("The character position of", x, "in s is:", listPositions (s, x))
# The output is:
# The character position of p in s is: 7
Younes Derfoufi

Leave a Reply