course update of 2023-11-27 14:49:47
This commit is contained in:
62
Algo/B2/Exercises/String exercise.md
Normal file
62
Algo/B2/Exercises/String exercise.md
Normal file
@ -0,0 +1,62 @@
|
||||
# String Exercises
|
||||
|
||||
## Exercise 1.1 (Search)
|
||||
|
||||
```python
|
||||
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 = 1
|
||||
n = len(s)
|
||||
for loop in range(n):
|
||||
if s[n] == x:
|
||||
i += 1
|
||||
return i
|
||||
|
||||
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)
|
||||
|
||||
```python
|
||||
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
|
||||
```
|
||||
|
Reference in New Issue
Block a user