I'm having problem with cycles. I have a simple for loop that append random numbers, what I need is that if a number appears consecutive times break the for loop, this is an example.
import numpy as np
stop = 3
value = []
for i in range(100):
value.append(np.random.randint(0, 2))
print(value)
if value[-stop:] == [0]*stop or value[-stop:] == [1]*stop:
break
What this code does is, I want to do a for loop 100 times but if the number 0 or the number 1 appear 3 times in consecutive order in the final of the list, then the loop break, how can I generalized to any random number without having to add infinite or for each random value. I tried using another for loop to iterate trough each value in the appended list, but it's not working, it keeps appending random numbers even if the condition is reached:
stop = 3
value = []
for i in range(15):
value.append(np.random.randint(0, 3))
print(value)
for i in value:
if value[-stop:] == [i]*stop:
break
This is what I get in the 10th iteration, here it should stop, since 0 appears three times:
[0, 1, 0, 1, 1, 2, 0, 2, 0, 0, 0]
But it keeps doings iterations and the next one is
[0, 1, 0, 1, 1, 2, 0, 2, 0, 0, 0, 2]
Any idea would be appreciated, if something is not clear, please let me know and I'll edit the question. Thank you, again!
Aucun commentaire:
Enregistrer un commentaire