Why is this code only returning 1?
Multiple reasons.
First, there's no loop in the code, so there's no way it could ever return more than 1.
Second, if "Z" and "E" in data
doesn't mean what you think. It's true if "Z"
is true, and also "E" in data
is true. In other words, it's equivalent to if ("Z") and ("E" in data)
. But, even if the parentheses went the other way, and it were if ("Z" and "E") in data)
it wouldn't work. Since "Z" and "E"
is just "E"
(try it and see), that would just be checking whether "E"
appears in data.
You need if "Z" in data and "E" in data
to do what you're trying to do.
Third, even if you fix that, the logic doesn't make any sense. This is true if there's any "Z" anywhere, and any "E" anywhere. So, it would be true for "EZ", which is obviously wrong. You only want it to be true if the substring "ZE"
appears in the data, right? You can use if "ZE" in data
to mean exactly that. Or, if you're not allowed to do that for some reason, first find a "Z"
and check whether the next character is "E"
.
Here's a way you could do this (not a very good way, but the closest I could come up with to what you tried):
def count_eaten(data):
count = 0
while True:
index = data.find('Z')
if index == -1:
return count
data = data[index+1:]
if data[0] == 'E':
count += 1
Or, more simply:
def count_eaten(data):
count = 0
while True:
index = data.find('ZE')
if index == -1:
return count
data = data[index+1:]
count += 1
Or, even more simply:
def count_eaten(data):
return data.count('ZE')
I'm guessing your professor doesn't want this last one, and probably doesn't want the one before it either… but that's really just a guess (as is the fact that this is homework in the first place).