Count frequency of item in tuple with kwargs**

Question:

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?

Asked By: TahaAvadi

||

Answers:

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}')
Answered By: LTJ

kwargs is a dictionary of values:

{"math":"Fail", "science":"Fail", "history":"Pass", "english":"Pass"}

in your example.
When you iterate over that dictionary, your are only getting the keys: "math", "science", etc.

To get the value associated with that key, you need to get it from the original dict: kwargs[pas] in your case.

Also, notice that in your code, you are not returning any value, so you are dropping all the work your function is doing to compute count.
Finally, you are returning in your for loop, right after you’ve started it, so you need to return at the end of the loop

However, in your case you can use kwargs.items() to get both the key and the values for instance, or even kwargs.values(), since you don’t actually use the key in your code:

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

result = count_passes(math="Fail", science="Fail", history="Pass", english="Pass") 

print(f'The number of passes: {count_occurrence(result, "Pass")}')
Answered By: Florent Monin

kwargs is a dictionary, so you need to check the values. One option is to convert the values to a list and use the count function

def count_passes(**kwargs):
    return list(kwargs.values()).count('Pass')
Answered By: Guy