user16472631
user16472631

Reputation:

How do I check total amount of times a certain value occurred in a nested loop?

Question: Calculate the total number of apples bought on monday and wendsday only.

This is my code currently:

apple = 0
banana = 0
orange = 0

#number of fruits bought on monday, tuesday and wendsday respectively
fruit = [ ['apple', 'cherry', 'apple', 'orange'], \
          ['orange', 'apple', 'apple', 'banana'], \
          ['banana', 'apple', 'cherry', 'orange'] ]

for x in fruit:
     if 'apple' in x:
          if fruit.index(x) == 0 or fruit.index(x) == 2:
               apple + 1

print(apple)

For some reason, the current result which I am getting for printing apple is 0.

What is wrong with my code?

Upvotes: 0

Views: 64

Answers (3)

Anonymous Coder
Anonymous Coder

Reputation: 586

the problem in your code is you are only incrementing the the number of apples but you are not assigning them into any variable, that's why it is printing it's initial value:

apple = 0
apple + 1

you need to do:

apple += 1

and also fruit.index(x) always return the index of the first occurence of that element, that is:

fruit[1].index('apple')

will return index of first occurence of 'apple' in fruit[1], which is 1.

but According to your question, this solution is incorrect because they were asking no of apples on monday and wednesday only so you need to this manually, because according to your solution it will also count the apples on tuesday also where index of 'apple' is 0 or 2. below is the correct solution

apple = 0
banana = 0
orange = 0

#number of fruits bought on monday, tuesday and wendsday respectively
fruit = [ ['apple', 'cherry', 'apple', 'orange'],
          ['orange', 'apple', 'apple', 'banana'],
          ['banana', 'apple', 'cherry', 'orange'] ]


apple += fruit[0].count('apple')
apple += fruit[2].count('apple')

print(apple)

Upvotes: 2

Wondercricket
Wondercricket

Reputation: 7872

There are two issues with your code.

The first issue is:

if fruit.index(x) == 0 or fruit.index(x) == 2:
     apple + 1

apple + 1 is not doing anything meaningful. If you want you need to increment apple, you need to do apple += 1. This results in apple being 2

The second issue is that you need to calculate the total number, which is 3 apples and not 2. Two apples were bought on Monday and 1 on Wednesday.

You can use collections.Counter for this

from collections import Counter
for x in fruit:
    if 'apple' in x:
        if fruit.index(x) == 0 or fruit.index(x) == 2:
            apple += Counter(x)['apple']

Upvotes: 1

Pizzarules668
Pizzarules668

Reputation: 37

it should be apple += 1, not apple + 1

Upvotes: 0

Related Questions