I don't know what I did wrong


#1

def count(sequence, item):
found = 0
for i in found:
found+=1
if i in item:
return found

Please take a look at my code, I am obviously getting it wrong but can someone please explain it to me, I'm tired of having to come on here to look for other answers. I really want to know this stuff.


#2

Which part are you really having trouble understanding? This is one of the hardest, (if not the hardest), module of python.
I know the problem with your code is that you're doing

found is a variable you just defined, but you really want to iterate through sequence and if the number in sequence is equal to the argument item, found += 1. Last, just return found inside of the count function but after you iterate through the sequence.

I hope this helps you understand the lesson, but what else is troubling you or preventing you from fully getting the module?


#3

So what you're saying is that I should take out the "for i in found:"?


#4

No. You have some logical errors.

Your code has been corrected & given below.

Code

def count(sequence, item):
    found = 0
    for i in sequence:
        if i == item:
            found += 1
    return found

About the line:if i == item: I don't know why this works, but it just does. It might be different if the item given is a list, in which case if i in item could be used.


#5

Thank you very much. It feels so good to pass it.


#6

It works because it's testing if i is equal to item. If you back up to

this is saying, which you know, that it's iterating through sequence, and each part of sequence is one 'i'. After that, it's testing if I == item, and if i, one part of sequence is found and it's the same as item, then found is going to increment each time this happens.


#7

And what if the item is a list? I mean item = [8, 52, 'jarvis"]. Will then if i == item work as well?


#8

yes, so you call the function by saying count(list, item in list you want to count)
In your example, I could call it and write count([8, 52, "Jarvis"], 52)
The function works by iterating through sequence, the list. If an specific part of the list is equal to item, (52), then found will increment. If the list was [8, 52, 29, "jarvis", 52], then found will be 2 because in the loop, if an thing in the list is equal to item, then found will continue to get larger.


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.