Q#50: Function to count tuple elements
Published in
Sep 22, 2021
Suppose you are given a tuple containing ints and strings. Write a Python function to return the # of times a given element, n, appears in the tuple.
For example, given the tuple below, where n=3, your function should return 4, since 3 appears 4 times in the tuple.
TRY IT YOURSELF
ANSWER
This is a simple question that tests your basic programming skills in Python.
We need to create a function that takes in a tuple and an element n and simply iterate over the tuple while having a variable track the number of times our iterator matches the target element.
def tuple_count(tup, n):
cnt = 0
for i in tup:
if i == n:
cnt+=1
return cnt