As colleagues have already said, the two points are missing :
after for x in seq
and if x == max
and python does not allow certain constructs to be positioned on the same line:
cont = 0
seq = [1, 2, 3, 6, 10, 77, 92, 10, 10]
max = 10
for x in seq:
if x == max:
cont = cont+1
print(cont)
I would like to suggest another approach, functional programming using the module functools that offers functions that act on or return other functions.
In case the solution uses the function reduce() which bears the following signature:
functools.reduce( função , iterável [ , inicializador ] )
Applies to função
of two arguments cumulatively to the items of the eternal
left to right, so as to reduce the iterable to a single
value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
calculates ((((1+2)+3)+4)+5)
.
The left argument, x
, is the accumulator and the right argument, y
, is a value from the eternal.
If the optional initializer is present, it is placed before the iterable items in the calculation and serves as the default when the iterable is empty.
If the initializer is not provided and the iterable contains only one item, the first item will be returned.
In the example was used a lambda function comparing an element e
of seq
with max
. If both are equal sum 1
to the accumulator a
or just give it back a
:
from functools import reduce
seq = [1, 2, 3, 6, 10, 77, 92, 10, 10]
max = 10
cont = reduce(lambda a, v : a + (1 if v==max else 0), seq, 0)
print(cont) #3
Test the code on Repl.it
You can read my answer about how to filter a Python list for more information. Obviously if the intention is only to count the amount of elements equal to the
max
, the more pythonic isseq.count(max)
as commented in the replies.– Woss
Take a look at this link
– Solkarped