A common issue is returning at the wrong place in your code. Be sure you don’t use return inside of a loop or the loop will only run one time, depending on where inside the loop you wrote it.
Remember: as soon as a function executes a return statement, it exits immediately and returns that value to wherever the function was called in the program.
In the count() function, we want to return at the end of the function, after we loop through the list provided, so our return should be indented only once with two spaces.
This statement checks if each item in sequence is equal to 1, that is, it is exactly 1. Only the last element in sequence is equal to 1, so result, and therefore count, is only incremented by 1. You would need to use multiple nested for loops if you wanted to count the total number of 1s in sequence.
Using both result and count in this way is also redundant, since count is only increased by 1 every time. You should set count += result instead if you change your code to check every index of every element of every element in sequence.
Not elegant but I thought my way through the exercise.
I like to print whenever I can because it teaches me as I progress.
print "Sequence(s) to check: ", sequence
print "Check for #: ", item
accumulator = 0
for x in sequence:
for y in x:
if y == item:
accumulator += 1
print "Your number: ", item, "was counted this many times:"
print count([[11, 1, 1, 2, 2222], [1, 4], [1, 4]], 4)
def count(sequence, item):
total = 0
for i in range(0, len(sequence)):
if sequence[i] == item:
total += 1
Just a heads up for anyone who might be running into an error that says “list indices must be int, not str” – if you write your iteration through the list as “for i in sequence”, I think that the values passed through the loop end up being of type str instead of integers. To fix this, use “for i in range(0, len(sequence))” so that the numbers of the indices get passed through. I used len(sequence) so that it would stop at the end of the list because the first index of any list is
If there’s any place I am incorrect, please feel free to make any corrections/suggestions.