1.2 KiB
1.2 KiB
String Exercises
Exercise 1.1 (Search)
def search(x: str, s:str) -> int:
"""
Function that counts the number
of occurences of a given character
in a string
@params x (str): the keyword
@params s (str): the string
@return: (int): the number of occurences
"""
i = 0
pos = -1
while i < len(s) and pos == -1:
if s[i] == c:
pos = i
i += 1
return pos
def search2(s: str, x: str) -> int:
"""
Function that counts the number
of occurences of a given character
in a string
@params x (str): the string
@return: (int): the occurence where is appear
"""
i = 1
n = len(s)
for i in range(n):
if s[i] == x:
return i
return -1
Exercise 1.2 (Palindrome)
def palindrome(sentence: str) -> bool:
"""
Function that check if a number is a palindrome
@params sentence(str): the sentence to check
@return (bool): Either a palindrome or not
"""
newSentence = ""
oldSentence = ""
for element in sentence:
if element != " ":
newSentence = element + newSentence
for element in sentence:
if element != " ":
oldSentence += element
if newSentence == oldSentence:
return True
else:
return False