在Mathematica 8中,我想定义一个离散分布,其密度质量作为列表给出.例如,
In[1] f = ProbabilityDistribution[{2/3, 1/3}[[x]], {x, 1, 2, 1}];
Run Code Online (Sandbox Code Playgroud)
这似乎有效.然而,这发出了两次重复的警告:
"Part::pspec: Part specification x is neither an integer nor a list of integers."
Run Code Online (Sandbox Code Playgroud)
然而,f似乎正常工作.这条消息让我觉得可能有更好的方法来定义相同的分布.如何使用列表定义离散分布但不调用警告?
更具体地说,我可以检测是否EXPR
在with EXPR: BLOCK
语句中调用函数?我试图让自己熟悉with
python 中-statement 的用法.作为第一步,我重新实现了一个生成标记文本的示例,出现在(暂时忽略异常处理)的引用中contextlib.contextmanager
.
class Markup(object):
def __init__(self):
self.tags = []
self.append = self.tags.append
self.pop = self.tags.pop
def tag(self, name):
self.append(name)
return self
def __enter__(self):
print('<{}>'.format(self.tags[-1]))
def __exit__(self, exc_type, exc_value, traceback):
print('</{}>'.format(self.pop()))
>>> m = Markup()
>>> with m.tag('ELEMENT'):
... print('sample text')
...
<ELEMENT>
sample text
</ELEMENT>
Run Code Online (Sandbox Code Playgroud)
这按预期工作.然后,我想是否tag()
也可以生成空元素:
>>> m = Markup()
# if a function appears as EXPR of "with EXPR: BLOCK", 'ELEMENT' is a container …
Run Code Online (Sandbox Code Playgroud)