python - 如何拆分字符串列表并使用递归返回元组?
问题描述
我遇到问题的一个函数是 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)))
有人能找出问题所在吗?我会很感激的。
解决方案
您应该只对遍历部分使用递归。递归函数不应包含 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] )
如果这是一个家庭作业,我真诚地希望你的老师能够促进关注点分离并且不需要有问题的编码实践
推荐阅读
- javascript - 离开jQuery,写了一个简单的ajax函数,但是链式方法不会等待
- rust - 函数适用于推断的生命周期,但不适用于显式生命周期
- java - Java charAt() 返回随机整数而不是字母
- google-sheets - 在子表中查找
- delphi - 图像幻灯片效果。BitBlt 闪闪发光
- reactjs - antd datepicker 使用 formik 预填充值
- python - 查找最长重复子串的快速算法
- php - 更改 laravel 项目名称
- python - 图像距离变换不同 xyz 体素大小
- html - 如何使用具有 filterUnits="userSpaceOnUse" 的过滤器隐藏可重用的 svg