Carlos Eduardo Corpus
Carlos Eduardo Corpus

Reputation: 349

Using a for if break statement to append values in a list

I'm working with loops and I got a question, so I have a simple for loop that append random values between 0 and 1, basically what I need is to keep adding values until a certain number of 0 or 1 appear, for example:

iteration 1 = [0]
iteration 2 = [0,1]
...
iteration 6 = [0,1,1,1,1,1] #Here appear five 1's so I break the loop (it can be another number not necessarily 5 ones or 5 zeros)

The for loop is pretty simple:

import numpy as np

value = []
for i in range(5):
    value.append(np.random.randint(0, 2))
    print(value)

And here is what I tried to break the loop using a if-break statement

value = []
for i in range(5):
    if value == value:
        value.append(np.random.randint(0, 2))
    else
        break

    print(value) 

My biggest problem is that I don't know how to specify the codition that if a certain numbers of 0 or 1 appears break the loop, so I was hoping you can point me to a right direction. Thank you in advance!

Upvotes: 2

Views: 1016

Answers (3)

ThePyGuy
ThePyGuy

Reputation: 18426

In such scenarios when you don't know exactly how many number of iterations are required, using while loop is the defacto standard You can have two variables as maximum allowed numbers, for this example I'm using numOnes as 5 and numbZeros as 3, use While True loop and check for condition at each iteration then break if the condition doesn't satisfy.

import numpy as np
numOnes = 5
numZeros = 3
value = []
while True:
    value.append(np.random.randint(0, 2))
    print(value)
    if value.count(0) >= numZeros or value.count(1)>=numOnes:
        break

Since you typically asked about break statement, so I used if condition, otherwise you can just have the condition with while loop itself like while value.count(0) >= numZeros or value.count(1)>=numOnes:

Also, if you are using for loop because you want only specified number of iterations, then your loop is fine and you don't need to use while loop, just add the if condition at the exit point of loop:

import numpy as np
numOnes = 5
numZeros = 3
value = []
for i in range(5):
    value.append(np.random.randint(0, 2))
    print(value)
    if value.count(0) >= numZeros or value.count(1)>=numOnes:
        break

Upvotes: 2

MarkSouls
MarkSouls

Reputation: 999

You can count the numbers to break.

value = []
count = [0, 0]
while True:
    value.append(np.random.randint(0, 2))
    count[value[-1]] += 1
    if count[1] == 5: # or something like that
        break

Edit: if you need consecutive values, you can reset count accordingly when unwanted value comes.

    count[value[-1]] += 1
    count[1 - value[-1]] = 0

Upvotes: 2

Kwright02
Kwright02

Reputation: 777

Use two variables to keep track of the number of 0s and 1s generated by the random number getter.

Then, in the for loop use if-statement logic to append or break where appropriate

Upvotes: 2

Related Questions