-1

I want this function to print True if 200 occurs 3 times in a row. False otherwise.

def aList(n):
    
    if n.count(200) >= 3:
        return True
    else:
        return False

print(aList([100, 200, 200, 300, 200]))

Currently it is returning True because 200 exists 3 or more times, however it should return False because it is not occurring in a row.

Edit: Even if I iterate over the list, how can I pull True if the occurrence happens x amount of times.

for i in range(len(n)):
        if i == 200:
            return True
    else:
        return False
cnsc.bot
  • 23
  • 6

2 Answers2

2

You need a variable to keep track of how many times you have seen the number in a row. Add one when you match the value and reset the count to 0 if you don't. Return true if you get to the threshold. If you finish the loop without hitting the threshold, return false.

def aList(n):
    count = 0
    for i in n:
        if i == 200:
            count += 1
        else:
            count = 0

        if count == 3:
            return True
    return False

print(aList([100, 200, 200, 300, 200]))  # -> False
print(aList([100, 200, 200, 200]))  # -> True
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Patrick
  • 149
  • 7
1

So what you are trying to accomplish requires a consideration for positional elements... so you would need a counter to keep track of the counts and revert it back to zero when it does not match.. Little bit of pseudocode here, but something like this..

def nums_in_row(aList, target_num):
    count = 0
    for nums in aList:
        if count ==3:
            return True
        elif nums == target_num:
            count+=1
        else:
            count = 0
    return False

target_num would be 200 in your example and aList would be the list itself. You could generalize your function further, but based on your question, it seems to suffice.