我正在尝试创建一个输出以下内容的函数:
[1,cos(t),sin(t),cos(2*t),sin(2*t), ... ,cos(n*t),sin(n*t)]
称为row_func
,它接受t和n作为输入。
到目前为止,这是我的代码:
def row_func(t,n):
L=0
g=np.cos()
h=np.sin()
L=[f(k) for k in range(n,t) for f in [g,h]]
L.insert(0,1)
return L
例如,当我使用诸如row_func(1,5)
之类的输入时,它将引发错误,指出参数数量无效。
我也知道n不能满足示例的要求,但是我不知道如何将其合并。
提前谢谢。
答案 0 :(得分:2)
一个简单的循环就可以完成这项工作:
import math
def row_func(t, n):
out = [1]
for k in range(n + 1):
out.append(math.cos(k * t))
out.append(math.sin(k * t))
return out
答案 1 :(得分:0)
In [194]: row_func(1,5)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-194-a47e3d49d002> in <module>
----> 1 row_func(1,5)
<ipython-input-193-d278f021d727> in row_func(t, n)
1 def row_func(t,n):
2 L=0
----> 3 g=np.cos()
4 h=np.sin()
5 L=[f(k) for k in range(n,t) for f in [g,h]]
ValueError: invalid number of arguments
注意第二个->吗?它告诉我们问题在于该np.cos()
表达式。因此,我们需要查看np.cos
的文档,对吧?
拖放(),然后运行:
In [196]: def row_func(t,n):
...: L=0
...: g=np.cos
...: h=np.sin
...: L=[f(k) for k in range(n,t) for f in [g,h]]
...: L.insert(0,1)
...: return L
...:
In [197]:
In [197]: row_func(1,5)
Out[197]: [1]
让我们清理范围:
In [200]: def row_func(t,n):
...: g=np.cos
...: h=np.sin
...: L=[f(k) for k in range(t,n) for f in [g,h]]
...: return L
...:
...:
In [201]: row_func(1,5)
Out[201]:
[0.5403023058681398,
0.8414709848078965,
-0.4161468365471424,
0.9092974268256817,
-0.9899924966004454,
0.1411200080598672,
-0.6536436208636119,
-0.7568024953079282]
np.cos
使用数组,因此我们可以删除最里面的迭代,用arange
代替:
In [202]: def row_func(t,n):
...: g=np.cos
...: h=np.sin
...: L=[f(np.arange(t,n)) for f in [g,h]]
...: return L
...:
In [203]: row_func(1,5)
Out[203]:
[array([ 0.54030231, -0.41614684, -0.9899925 , -0.65364362]),
array([ 0.84147098, 0.90929743, 0.14112001, -0.7568025 ])]
或更紧凑:
In [207]: x = np.arange(1,5)
In [208]: [np.cos(x), np.sin(x)]
Out[208]:
[array([ 0.54030231, -0.41614684, -0.9899925 , -0.65364362]),
array([ 0.84147098, 0.90929743, 0.14112001, -0.7568025 ])]