user2744489
user2744489

Reputation: 501

returning values greater than the target value

I'm trying to figure out how to change this code. Instead of counting the number of times that the target value appears, I want to be able to return the number of values in the list that are greater than the target value.

def countTarget2(myList, target):
    counter = 0
    for element in myList:
        if element == target:
            counter = counter + 1
    return counter

Do I change the 5 line too?

counter > counter + 1

Upvotes: 0

Views: 345

Answers (5)

pjama
pjama

Reputation: 3044

No, you would only change line 4

def countTarget2(myList, target):
    counter = 0
    for element in myList:
        if element > target:
            counter = counter + 1
    return counter

Note that the if statement requires indentation on line 5

Upvotes: 2

Serdalis
Serdalis

Reputation: 10489

No in this case you are changing the equivalence test to a greater than test.

You are currently testing element == target which will execute the (properly indented) counter = counter+1 line on every equivalence.

To do a greater than test you'd need to change the test to element > target.

The code would look like:

def countTarget2(myList, target):
    counter = 0
    for element in myList:
        if element == target:
            counter = counter + 1 # properly indented, dont forget this!
    return counter

Upvotes: 1

Erik Kaplun
Erik Kaplun

Reputation: 38217

You change line 4 to if element > target::

def countTarget2(myList, target):
    counter = 0
    for element in myList:
        if element > target:
            counter += 1
    return counter

or, you use the more functional (but probably hard to understand for a beginner):

def countTarget2(myList, target):
    return len(x for x in myList if x < target)

P.S. I've also changed counter = counter + 1 to the nicer looking counter += 1.

Upvotes: 2

arshajii
arshajii

Reputation: 129517

The change is fairly trivial:

if element > target:  # if the element is greater than the target

Don't forget to properly indent the line that follows this.

Note that the most Pythonic way to write this function would be to use sum():

def countTarget2(myList, target):
    return sum(1 for element in myList if element > target)

Upvotes: 4

alecxe
alecxe

Reputation: 473873

You can use a list comprehension approach:

def countTarget2(myList, target):
    return len([element for element in myList if element > target])

print countTarget2([1,2,3,4], 2)  # prints 2

UPD:

This is actually a short form of:

def countTarget2(myList, target):
    l = []
    for element in myList:
        if element > target:
             l.append(element)
    return len(l)

So, yes, there is an intermediate list - generator expression is a better choice.

Upvotes: 2

Related Questions