I got a problem with count function. Function should return the number of times the item appears in the list. I think the code seems fine but it throws a wierd error. I tried it with while and for loops but gives similar error. Here is the code:
def count(sequence, item):
sum = 0
while item in sequence:
sum += 1
count([2, "time", 5, "time", "time", 7, 1], "time")
Why would you need to change the list to count things in it?
(Also, you’re doing it in a horribly inefficient way, doing many passes over the list, both the in operator loops through the list, as does list.remove, and you’re using them both repeatedly)
As for the result, I think you’re using different code in the editor from what you posted, perhaps you have tab characters in there, changing the meaning of the indentation. Because, while there’s no point in removing, and while it’s done inefficiently, the concept does indeed still amount to a correct result.
A different data structure could be used which allows for constant-time membership testing and constant-time deletion. Lists don’t do that. That still leaves that removing is not necessary to counting.
Despite my protests, I still do agree with coming up with an idea that you’re convinced of is correct, and implementing it.
The code you posted doesn’t behave like your screenshot suggests. Something is off.
What I meant with the last part is that your code should match the idea you had.
If that idea is: remove the item until it’s no longer there, then yeah, go for it. If you’re happy with an idea you should go with it. Code is there to describe your ideas. And you shouldn’t change the idea unless you realise that it doesn’t do what you want. It’s the code that should change to match the idea.
But if you thought it would be fast, then it would be a bug. Either you hadn’t thought through how it would happen and it would be a bad assumption, or you had thought of a way that would make it fast, but you wrote something else.
Don’t worry about making it efficient.
All that matters is that you know what things do, that way you can make things efficient, you can ask yourself “how much work will this do” and know whether it’s reasonable. And you’ll see if something is doing lots of unnecessary work, and instead be able to write what you meant.
Sometimes, like here, inefficient simply means that you would never do it that way yourself. It’s not a matter of speed. It’s a matter of describing what you meant.