小编Nae*_*med的帖子

从递归函数返回字典

我有一个二进制搜索树,其中每个节点代表一个游戏长度。我必须返回一个字典,其中的键是游戏的长度,值是该长度的游戏数。递归调用遍历树中的每个节点,但返回错误的字典。我很肯定问题是我如何退还字典。任何帮助将不胜感激

game_len = {}
if not node.children:
    key = len(node.possible_next_moves())
    if key not in game_len:
        game_len[key] = 1
    else:
        game_len[key] += 1
else:
    key = len(node.possible_next_moves())
    if key not in game_len:
        game_len[key] = 1
    else:
        game_len[key] += 1
    [game_lengths(child) for child in node.children] 
return game_len
Run Code Online (Sandbox Code Playgroud)

python recursion binary-tree dictionary

2
推荐指数
1
解决办法
1337
查看次数

如何使用property()

我在如何实现属性来保护属性方面遇到了麻烦.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def set_x(self, x):
        if '_x' in dir(self):
            raise NotImplementedError("Cannot change x coordinate")
        else:
            self._x = x

    def get_x(self):
        return self._x

    #I beleive my mistake is here. I'm not sure if I'm implementing this correctly
    x = property(get_x, set_x, None, None)
Run Code Online (Sandbox Code Playgroud)

所以我想阻止任何用户更改x坐标.我的问题是,如何让python将用户重定向到set_x()和get_x()方法?我已尝试在终端中运行此代码,每当我应用以下内容时,该点都会发生变化.

p = point(3, 4)
p.x = 5 #x is now 5
Run Code Online (Sandbox Code Playgroud)

python python-3.x

1
推荐指数
1
解决办法
69
查看次数

标签 统计

python ×2

binary-tree ×1

dictionary ×1

python-3.x ×1

recursion ×1