Python Code Challenges: Lists ['More Than N' Question]

Hi all,

I am learning Python and enjoying the challenges so far.

I am confused about why I keep getting the incorrect answer for this question. It keeps returning True, when it should return False. I think the issue is that the function is telling the computer to return False if there are more items than n’s in the list, and it can’t find the “n” at all - there’s no 1 in the list! I checked the answer and saw how to create the correct function. I just want to know why mine is wrong. Thanks!

Create a function named more_than_n that has three parameters named lst , item , and n .
The function should return True if item appears in the list more than n times. The function should return False otherwise.

> def more_than_n(lst, item, n):
>   if lst.count(item) > lst.count(n):
>     return True
>   else:
>     return False
> print(more_than_n([2, 3, 4], 2, 1))
> #Uncomment the line below when your function is done
> #print(more_than_n([2, 4, 6, 2, 3, 2, 1, 2], 2, 3))

Hello @sister, welcome to the forums! The problem is here:

Here you are counting the number of times n appears in the list. The question, however, is asking if item appears more than n times. Take the following example:

listvar = [1, 2, 2, 3, 2, 1]
print(more_than_n(listvar, 2, 1))
#This should print True, since the number 2 appears more than once in the list

I hope this helps!

Thank you! I get it now.

1 Like

Hi there, first time posting so I apologize if this is formatted poorly.

What I do not understand about the given solution to this problem, is that it treats one of the function parameters (lst) as a list itself. It does not explain that this is a list - no background information that this is the list we are retrieving “item” from. When ‘lst’ is a parameter of a function being defined, is it common knowledge to know it is in fact a list? And not an undefined random variable name chosen for the function to be defined?

In all fairness Python is dynamically typed and designed to readable. Ideally you’d need very little information to make use of a function like this which makes the naming of variables and such very important. I think using lst as a shorthand name for a list is fairly common but perhaps you could think of a better name considering it is supposed to be a list of integer numbers.

If this was in a full project then hopefully you’d have a docstring describing the basic use of the function and parameters that can be passed to it. Type hinting/annotation is another more recent option for this but both of them are optional at the end of the day. Good code is typically well documented but you can still find plenty that isn’t. But… for the sake of learning Python I think you can skip out on documenting everything :wink:.