Write a function called countElements that counts the number
Write a function called countElements that counts the number of times two elements appear in a list. Your task is to ask the user to enter a list and two elements which they need to count in the list. The list and each of the elements should be inputs to a function called countElements. The function should print the count of the number of times the elements appear in the list. def countElements(countList, element1, element2): Example: if the inputs to the function were [“t”, “s”, 7, 7, 2], “t”, and 7, the function would count the instances of the letter “t” and the number 7 in the list, and print the number 3. There was one “t” and two 7’s. Name your file Lastname_Firstname.py
Solution
def countElements(list, ch1, ch2):
count = 0
for i in range(0,len(list)):
if list[i] == ch1:
count = count + 1
for i in range(0,len(list)):
if list[i] == ch2:
count = count + 1
return count;
print countElements([\"t\",\"s\",7,7,2], \"t\", 7)
Output:
sh-4.3$ python main.py
3
