![](/img/trans.png)
[英]How to write a function that takes a positive integer N and returns a list of the first N natural numbers
[英]Write a function called randomization that takes as input a positive integer n, and returns A, a random n x 1 Numpy array
编写一个 function 称为随机化,将正 integer n 作为输入,并返回 A,一个随机的 nx 1 numpy 数组。
以下是我所拥有的,但它不起作用。
import numpy as np
def randomization(n):
if n>0 and n==int:
A=np.random.random([n, 1])
print(A)
x=int(input("enter a positive number: "))
r=randomization(x)
print(r)
如果我运行它,我会收到一条消息,说“赋值前引用了局部变量‘A’”。
首先, n == int
将始终为假,因为n
不是int
类型。 使用isinstance(n, int)
代替。
正因为如此, A
永远不会被分配,但是你调用print(A)
就好像它被分配了一样。
除了 chepner 所说的, np.random.rand 期望维度作为参数而不是列表。 也就是说,您应该使用 A=np.random.rand(n, 1)。 请注意,这将返回一个均匀分布的随机向量。 此外,您的函数不返回任何值。 使用 - 最后返回 A。
我认为您正在寻找的是这样的东西。 您必须定义 function,将 A 设置为等于随机矩阵 nx1,然后在您的定义中返回值 A。
A = np.random.random([n,1])
return A
希望这可以帮助
Q) 编写一个 function 称为随机化,将正数 integer n 作为输入,并返回 A,一个随机的 nx 1 numpy 数组。----
Ans) def randomization(n): random_array=np.random.random([n,1]) return random_array a=randomization(4) 打印(a)
尝试使用这个。 请确保您的缩进是正确的:
def operations(h,w):
"""
Takes two inputs, h and w, and makes two Numpy arrays A and B of size
h x w, and returns A, B, and s, the sum of A and B.
Arg:
h - an integer describing the height of A and B
w - an integer describing the width of A and B
Returns (in this order):
A - a randomly-generated h x w Numpy array.
B - a randomly-generated h x w Numpy array.
s - the sum of A and B.
"""
A = np.random.random([h,w])
B = np.random.random([h,w])
s = A + B
return A,B,s
A,B,s = operations(3,4)
assert(A.shape == B.shape == s.shape)*
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.