目标是实现一个分段表达式,当n为偶数时给出0,当n为奇数时给出1。一种方法是使用如下的地板功能:
from sympy import *
from sympy.abc import n
f = Lambda((n,), Piecewise((0, Eq(n, floor(n / S(2)))),
(1, Eq(n, floor(n / S(2))+1))))
print(f(0))
print(f(1))
print(f(2))
print(f(3))
但是,这会返回错误的输出:
0
1
1
Piecewise()
正确的输出应该是:
0
1
0
1
实现同样目的的另一种方法是使用:
from sympy import *
from sympy.abc import n
f = Lambda((n,), Piecewise((0, Eq((-1)**n, 1)),
(1, Eq((-1)**n, -1))))
print(f(0))
print(f(1))
print(f(2))
print(f(3))
并返回正确的输出。有没有办法在原始代码中使用floor函数实现这个目的?
答案 0 :(得分:3)
更好的方法是使用Piecewise((0, Eq(Mod(n, 2), 0)), (1, Eq(Mod(n, 2), 1)))
,例如
Mod
但是,由于您的功能与Mod(n, 2)
的定义完全一致,您可以直接使用它
n % 2
或等效
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("2:2")) Is Nothing Then
Dim ws As Worksheet
Dim rng As Range
Set ws = Worksheets("Sheet5")'change to what ever sheet your want
Dim strArr() As Variant
ReDim strArr(0)
With Target.Parent
For Each rng In .Range(.Cells(1, 1), .Cells(1, 1).End(xlToRight))
If rng.Offset(1) = "Yes" Then
strArr(UBound(strArr)) = rng
ReDim Preserve strArr(UBound(strArr) + 1) As Variant
End If
Next rng
End With
If ubound(strArr) > 0 then
ReDim Preserve strArr(UBound(strArr) - 1) As Variant
End If
ws.Range("A1").Resize(, UBound(strArr) + 1).Value = strArr
End If
End Sub