I'm trying to solve a problem where I generate a three random number array and loop through it until the sum of it is below or equal to 21. My question is if there is a better/more performant way to do it than the following, just to adjust myself to the best practices.
rng = np.random.default_rng()
a = 1
while a == 1:
rints = rng.integers(low=1, high=11, size=3)
suma = np.sum(rints)
if (suma <= 21):
print(rints, suma)
break
Thanks!
CodePudding user response:
The while loop and the if statement can be combined. This will make it a little more efficient.
rng = np.random.default_rng()
target_value = 21
suma = 999
while suma >= target_value:
rints = rng.integers(low=1, high=11, size=3)
suma = np.sum(rints)
I would also suggest posting this to code review. They are more suited to these kind of questions.
CodePudding user response:
Just a shorter form using itertools
import numpy as np
from itertools import dropwhile
rng = np.random.default_rng()
rints = list(dropwhile(lambda x: np.sum(x)>21, rng.integers(low=1, high=11, size=3)))
print(rints, np.sum(rints))