Exercise 49
Write a Python algorithm as a function that takes a string and a character as inputs and counts the number of times the character appears in the string without using any predefined functions.
Solution
def count_char(string, char): count = 0 for i in range(len(string)): if string[i] == char: count += 1 return count string = "Hello, world!" char = "o" result = count_char(string, char) print(result) # This will output 2, since the character "o" appears twice in the string "Hello, world!".
Explanation of how it works:
- We define a function called count_char(): that takes two arguments: string and char.
- We initialize a variable called count to 0: which will keep track of how many times the character appears in the string.
- We use a for loop: to iterate over the indices of the string.
- For each index: we check if the character at that index is equal to the character we're looking for. If it is, we increment the count variable by 1.
- After the loop is finished: we return the count variable.
Younes Derfoufi
my-courses.net
[…] Exercise 49 || Solution […]