4. More Than N

https://www.codecademy.com/courses/learn-python-3/articles/python-code-challenges-lists

4. More Than N

Our factory produces a variety of different flavored snacks and we want to check the number of instances of a certain type. We have a conveyor belt full of different types of snacks represented by different numbers. Our function will accept a list of numbers (representing the type of snack), a number for the second parameter (the type of snack we are looking for), and another number as the third parameter (the maximum number of that type of snack on the conveyor belt). The function will return True if the snack we are searching for appears more times than we provided as our third parameter. These are the steps we need:

  1. Define the function to accept three parameters, a list of numbers, a number to look for, and a number for the number of instances
  2. Count the number of occurrences of item (the second parameter) in lst (the first parameter)
  3. If the number of occurrences is greater than n (the third parameter), return True . Otherwise, return False.

My solution:

def more_than_n(lst, item, n):

count=0

for item in range(len(lst)):

count += 1

return count

if count>n:

return True

else:

return False

My solutions only returns “1” without true or false.

check whether the
return count
is outside the for-loop
(You may want to comment it out or eliminate that return count if you want the function to return whether the number of occurrences, count, was greater than parameter n ;
because the function would not ever run past that return.)

Also,
for item in range(len(lst)):
does not check whether the item parameter before this is in lst
it just replaces the item variable (in the scope of the for-loop).
Currently, inside the loop, you’re using item for the index of each thing inside lst

You would have to use an if-statement (or something similar) to check if something at a specific index is the same as item.

  for i in range(len(lst)):
    if lst[i] == item:
      count += 1

Alternatively, you could check things in the list without using indices.

  for thing in lst: 
    if (thing == item):
       count += 1
1 Like