协助理解涉及树木和色彩传播的作业



我得到了如下所述的任务

我们被要求设计一棵能够储存某种传播颜色的树。传播哪种颜色是由子树中排序的颜色决定的。有一个颜色层次,存在一个顺序来确定哪种颜色是将传播的主导颜色。该树用于进行一些基本属性检查;如果";场景。该树包含基于层次结构的颜色传播:

  1. 红色(R(
  2. 绿色(G(
  3. 蓝色(B(
  4. 青色(C(
  5. 黄色(Y(

RED是最强的颜色。

树:

Y
/ 
C   G
   
R    Y

将产生宣传:

R
/ 
R   G
   
R    Y

我非常困惑这意味着什么,有人能帮助我理解这个吗

您可以定义一个递归方法来在表示树的每个节点的类中执行传播:

colors = ['R', 'G', 'B', 'C', 'Y'][::-1]
class Color:
def __init__(self, c, children=[]):
self.c, self.children = c, children
def propagate(self):
#check if node has any child colors while recursively propagating
if [n.propagate() for n in self.children]:
#find maximum child node (based on ranking)
m = max(self.children, key=lambda x:colors.index(x.c)).c
if colors.index(m) > colors.index(self.c):
#if maximum child node is higher ranking than the node color itself, reassign the current node color to the maximum child
self.c = m
def __repr__(self):
return f'{self.__class__.__name__}({self.c}, {self.children})'
tree = Color('Y', [Color('C', [Color('R')]), Color('G', [Color('Y')])])
tree.propagate()

输出:

Color(R, [Color(R, [Color(R, [])]), Color(G, [Color(Y, [])])])

最新更新