我遇到麻烦的一个函数是split_list,我必须通过递归将一个列表拆分为三个元组,每个元组包含一个strlist。第一个包含字符串的元组必须以元音开头,第二个包含字符串的元组必须以辅音开头,第三个包含字符串的元组不应以字母字符开头。
class Node:
    def __init__(self, value, rest):
        self.value = value
        self.rest = rest
    def __eq__(self, other):
        return ((type(other) == Node)
          and self.value == other.value
          and self.rest == other.rest
        )
    def __repr__(self):
        return ("Node({!r}, {!r})".format(self.value, self.rest))
# a StrList is one of
# - None, or
# - Node(string, StrList)
def split_list(strlist):
    if strlist is None:
       return (None, None, None)
    res = split_list(strlist.rest)
    if strlist.value or res(strlist.value) == 'AEIOUaeiou':
       return (Node(strlist.value, res[0]), res[1], res[2])
    if strlist.value or res(strlist.value) != 'AEIOUaeiou':
       return (res[0], Node(strlist.value, res[1]), res[2])
    if strlist.value.isalpha() or res(strlist.value) == False:
       return (res[0], res[1], Node(strlist.value, res[2]))这就是我目前所拥有的,但主要的问题是,当我运行我的单元测试时,我没有得到正确的输出。我遇到的问题是AssertionError。
示例:
strlist = Node("xyz", Node("Abc", Node("49ers", None)))
self.assertEqual(split_list(strlist),(Node('Abc', None), Node('xyz', None), Node('49ers', None)))
strlist = Node("Yellow", Node("abc", Node("$7.25", Node("lime", Node("42", Node("Ethan", None))))))
self.assertEqual(split_list(strlist),(Node('abc', Node("Ethan", None)), Node('Yellow', Node("lime", None)), Node('$7.25', Node("42", None))))输出:
AssertionError: Tuples differ: (Node('Yellow', Node('abc', Node('$7.25', Node('[50 chars]None) != (Node('abc', Node('Ethan', None)), Node('Yellow'[50 chars]ne)))有人能解决这个问题吗?我会很感激的。
发布于 2020-04-15 05:27:57
应该只对遍历部分使用递归。递归函数不应包含3个特定且不同的工艺条件。
您可以做的是编写泛型的节点过滤器函数,该函数将构建一个新的节点链,并使用它来组装您的元组。如果没有特定的条件,这个函数将非常简单且易于测试:
def filter(self,condition): # on the Node class
    nextFound = self.rest.filter(condition) if self.rest else None
    return Node(self.value,nextFound) if condition(self) else nextFound 然后,您可以使用这个带有不同参数的过滤器函数来构建您的元组:
def split_list(strlist):
    return ( strlist.filter(lambda n:n.value[:1].upper() in "AEIOU"), 
             strlist.filter(lambda n:n.value[:1].upper() in "BCDFGHJKLMNPQRSTVWXYZ"), 
             strlist.filter(lambda n:not n.value[:1].isalpha()) )编辑如果您必须在一个函数中完成所有这些工作,您可以将这两个函数组合在一起(尽管它可能很笨拙):
def split_list(strlist):
    nextFound = split_list(strlist.rest) if strlist.rest else (None,None,None)
    return ( Node(strlist.value,nextFound[0]) if strlist.value[:1].upper() in "AEIOU" else nextFound[0], 
             Node(strlist.value,nextFound[1]) if strlist.value[:1].upper() in "BCDFGHJKLMNPQRSTVXYZ" else nextFound[1], 
             Node(strlist.value,nextFound[2]) if not strlist.value[:1].isalpha() else nextFound[2] )如果这是家庭作业,我真心希望您的老师能促进关注点的分离,而不是要求有问题的编码实践
https://stackoverflow.com/questions/61216736
复制相似问题