Home > Back-end >  How do I find how much times something appears in a function without the count method?
How do I find how much times something appears in a function without the count method?

Time:05-10

I’m not completely sure how to explain it but I need to figure out how to find the number of times something is appearing in a function, without using the count method. Right now I have:

def contains(list_to_check, number):
  value_amount = 0

  for value in list_to_check:
    if value == number:
      value_amount  = 1
      return value_amount
    else:
      if value != number: 
        return 0
        

print(contains([4, 5, 6, 7, 8, 8, 4, 4, 2], 8))
        

And I basically need to figure out how to make it return 2 since there are 2 8’s.

CodePudding user response:

You function can be simplified with only one return out of loop

def contains(list_to_check, number):
        return sum([x==number for x in list_to_check])

print(contains([4, 5, 6, 7, 8, 8, 4, 4, 2], 8))

CodePudding user response:

Your solution is close to the right answer, in the way it iterates through the input list and compares the items in the list (value) with the input argument (number). However, the return statement makes the function exit the iteration at the first iteration. You can open this link and click on the "Next >" button to see how python executes your code.

In order to fix the code, you should move the return statement to the end of the function so that you iterate through all items before python exits the function.

def contains(list_to_check, number):
  value_amount = 0

  for value in list_to_check:
    if value == number:
      value_amount  = 1

  return value_amount
    

print(contains([4, 5, 6, 7, 8, 8, 4, 4, 2], 8))

While the above solution works, I would refactor (i.e. improve the readability of the code without changing its behavior) the function and write the following function:

def count_values(list_to_check, query):
    count = 0

    for value in list_to_check:
        if value == query:
            count  = 1

    return count
    

print(count_values([4, 5, 6, 7, 8, 8, 4, 4, 2], 8))

Finally, notice that the above function may not work properly with many non-integer numbers. For instance, count_values([0.3], 0.1 0.2) returns 0, while it should return 1. Please see this article for further explanation. In order to fix that problem, if your function may accept non-integer numbers, you can use the following function:

from math import isclose
from numbers import Number

def count_values(list_to_check, query):
    count = 0

    for value in list_to_check:
        if value == query or (
            isinstance(query, Number) 
            and isinstance(value, Number) 
            and isclose(value, query)
        ):
            count  = 1

    return count
    

print(count_values([4, 5, 6, 7, 8, 8, 4, 4, 2], 8))
  • Related