Search code examples
pythonpython-3.xkeyword-argument

Count frequency of item in tuple with kwargs**


This is what I wrote:

def count_passes(**kwargs)
    count = 0 #Complete this function to count the number of passes
    for pas in kwargs:
        if pas == mark:
            count = count + 1
        return 

result = count_passes(math="Fail", science="Fail", history="Pass", english="Pass") 
print(f'The number of passes: {count_occurrence(result, "Pass")}')

How do I make it to count how often 'Pass' is in kwargs?


Solution

  • You seem to be missing some code from the question, but here is how you can do the count:

    def count_occurrences(mark, **kwargs):
        count = 0  # Complete this function to count the number of passes
        for key, value in kwargs.items():
            if value == mark:
                print(f"Passed {key}")
                count = count + 1
        return count
    

    kwargs is a dict so you need to address it's items() or values() when iterating. Otherwise you're just going through the keywords. Also the return statement should be after the loop and actually return the count as a value.

    In case you wanted to improve on the implementation, here is a lighter way to do the same thing:

    def count_occurrences_simpler(mark, **kwargs):
        return sum(1 for v in kwargs.values() if v == mark)
    

    Then just call the function and print the result like you were doing

    result = count_occurrences("Pass", math="Fail", science="Fail", history="Pass", english="Pass")
    print(f'The number of passes: {result}')