我对Python和整个递归函数都很陌生,所以请原谅我的无知.
我试图在Python中实现二进制搜索树并具有以下插入方法(从类中取出):
def insert(self, key, root=None):
'''Inserts a node in the tree'''
if root == None:
root = self.root
if root.key == None:
self._update(root, key)
return 0
else:
tmp = root
if key > tmp.key: # we work with the right subtree
self.insert(key, root=tmp.right)
elif key < tmp.key: # we work with the left subtree
self.insert(key, root=tmp.left)
else: # key already exists
return 0
Run Code Online (Sandbox Code Playgroud)
我不确定这是否清晰,但是它会遍历树,直到它达到None值并使用要插入的键更新节点.
现在,该方法可以正常工作并从头开始正确创建BST.但是返回语句存在问题,因为如果没有执行递归,它只返回0.
>>> bst.insert(10)
0
>>> bst.insert(15)
>>> bst.root.right.key
15
>>>
Run Code Online (Sandbox Code Playgroud)
"插入"根键再次返回0(从第15行)它应该的方式.
>>> bst.insert(10)
0
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚为什么会这样.如果我在第6行放置一个print语句,它会正确执行,但它不会在第一次插入后返回任何内容.为什么是这样?(我很确定我遗漏了一些关于Python和递归的基本信息) …
这可能是一个重复的问题,所以请原谅我的搜索技巧.
我需要在Windows/cygwin机器(使用Perl 5.10.1)上下载特定Perl模块(local :: lib和其他)的所有依赖项,并将它们移动到没有Internet的Solaris机器(带有Perl 5.8.8)连接.
我已经看到minicpan在这个问题中提出了建议,但创建完整的CPAN副本不是一种选择,因为我在带宽有限的企业网络上.CPAN :: Mini有一些过滤选项,但它处理路径而不是依赖.
有没有办法实现这个目标?
谢谢,
伊万
我正在使用YAML作为Python项目的配置文件格式.
最近我发现Rx是唯一可用于Python和YAML的模式验证器.: - /Kwalify与YAML一起使用,但它仅适用于Ruby和Java.:(
我一整天都在阅读他们缺乏的文档,似乎无法编写有效的模式来表示我的文件结构.救命?
我有以下YAML配置文件:
cmd:
exec: mycmd
aliases: [my, cmd]
filter:
sms: 'regex .*'
load:
exec: load
filter:
sms: 'load: .*$'
echo:
exec: echo %
Run Code Online (Sandbox Code Playgroud)
我没有代表嵌套结构.我想要的是最外面的项目(在这种情况下为cmd,load和echo)是一个任意字符串,而后者又包含其他项目.'exec'是一个固定的字符串和必填项; 'aliases'和'filter'也是固定的,但应该是可选的.过滤器又有另一组必需和可选项.我应该如何用Rx表示这个?
到目前为止,我有以下模式(在YAML中),Rx无法编译:
type: //rec
required:
type: //rec
required:
exec: //str
optional:
aliases:
type: //arr
contents: //str
length: {min: 1, max: 10}
filter:
type: //rec
optional:
sms: //str
email: //str
all: //str
Run Code Online (Sandbox Code Playgroud)
在IPython中测试这个给了我:
/Rx.py in make_schema(self, schema)
68 raise Error('invalid schema argument to make_schema')
69
---> 70 uri = …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用pytest fixture来模拟调用open(),然后在测试拆卸时重置它,但由于某种原因,mock不会应用于测试函数中.
这是我的样本:
# tests.py
@pytest.fixture(scope='module')
def mock_open(request):
mock = flexmock(sys.modules['__builtin__'])
mock.should_call('open')
m = (mock.should_receive('open')
.with_args('/tmp/somefile')
.and_return(read=lambda: 'file contents'))
request.addfinalizer(lambda: m.reset())
def test_something(mock_open):
ret = function_to_test()
ret[1]() # This actually uses the original open()
Run Code Online (Sandbox Code Playgroud)
而且,如果它很重要,这就是function_to_test()看起来像:
# some_module.py
def function_to_test():
def inner_func():
open('/tmp/somefile').read() # <-- I want this call mocked
# More code ...
return (True, inner_func)
Run Code Online (Sandbox Code Playgroud)
如果我使用xUnit-style setup_module()/ teardown_module()functions 也会发生这种情况.但是如果我把模拟代码放在测试函数本身(我显然不想这样做),那么它工作正常.
我错过了什么?谢谢!
python ×3
dependencies ×1
flexmock ×1
perl ×1
pytest ×1
recursion ×1
schema ×1
unit-testing ×1
yaml ×1