Returning A Numpy Matrix?
So what I'm trying to do is create a function that'll throw 2 dice n times. For every throw, if at least one dice number is odd, we'll return the sum of the pair's values, if not w
Solution 1:
As you are creating a numpy array of the correct size you don't need to append values to it. Instead you need to fill the array with values. For example:
rolls = np.zeros(shape=(2, 3))
# [[ 0. 0. 0.]
# [ 0. 0. 0.]]
rolls[1,:] = 1,2,3
# [[ 0. 0. 0.]
# [ 1. 2. 3.]]
Another thing to note is that your if
statements are not doing what you think they are. See this question for a good explanation.
So, for your example you would want to do
defdice(n):
rolls = np.empty(shape=(n, 3))
for i inrange(n):
x = random.randint(1,6)
y = random.randint(1,6)
if {x, y} & {1, 3, 5}: # Suggested by Elazar in the comments # if x in [1,3,5] or y in [1,3,5]: # Another way to do it
sum_2_dice = x + y
rolls[i,:] = x, y, sum_2_dice
else:
sum_2_dice = 0
rolls[i,:] = x, y, sum_2_dice
return rolls
If you have to return a matrix (I don't think there is any benefit) you can simply convert it when you return the value:
return np.matrix(rolls)
You can check the type of the output by doing:
result = dice(2)
print (type(result))
# <class 'numpy.matrixlib.defmatrix.matrix'>
Post a Comment for "Returning A Numpy Matrix?"