小编Fre*_*llo的帖子

在给定的文本块的第 n 个字符之后递归地创建一个新的换行符

我写了一个小脚本,在达到某个字符限制后创建一个新的换行符。现在的问题是脚本输出从文本末尾开始的文本。我似乎无法弄清楚如何在不使脚本更复杂的情况下以正确的顺序打印文本。我正在做这个练习以更好地理解递归。

这是代码:

def insertNewlines(text, lineLength):

    if len(text) <= lineLength:
        return text
    else:
        return insertNewlines(text[lineLength:], lineLength) + '\n' + text[:lineLength]
Run Code Online (Sandbox Code Playgroud)

这是 lineLength 为 15 的测试输出:

length.  
e desired line   
s or exceeds th  
ord that reache  
n' after each w  
e character  '\  
Insert a newlin  
ewriter would.   
e text as a typ  
length, wrap th  
a desired line   
Given text and  
Run Code Online (Sandbox Code Playgroud)

实际输入:

text = "Given text and a desired line length, wrap the text as a typewriter would. Insert a …
Run Code Online (Sandbox Code Playgroud)

python recursion line-breaks

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

了解在重复函数中内置到变量赋值中的多个递归调用

我有一个二进制树的对象,由递归函数构建.我试图理解这里的递归调用:

def buildDTree(sofar, todo):
    if len(todo) == 0:
        return binaryTree(sofar)
    else:
        withelt = buildDTree(sofar + [todo[0]], todo[1:])
        withoutelt = buildDTree(sofar, todo[1:])
        here = binaryTree(sofar)
        here.setLeftBranch(withelt)
        here.setRightBranch(withoutelt)
        return here
Run Code Online (Sandbox Code Playgroud)

现在,我不明白的是函数内部语句的执行顺序.具体来说,我不理解变量赋值语句及它们的分配顺序以及它们的分配顺序.

现在,我确实理解了树结构,如何创建类,以及使用return语句启动递归,python中的递归函数有多简单.

如果您感兴趣,树对象是:

class binaryTree(object):
    def __init__(self, value):
        self.value = value
        self.leftBranch = None
        self.rightBranch = None
        self.parent = None 
    def setLeftBranch(self, node):
        self.leftBranch = node
    def setRightBranch(self, node):
        self.rightBranch = node
    def setParent(self, parent):
        self.parent = parent
    def getValue(self):
        return self.value
    def getLeftBranch(self):
        return self.leftBranch
    def getRightBranch(self):
        return self.rightBranch
    def getParent(self): …
Run Code Online (Sandbox Code Playgroud)

python recursion

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

标签 统计

python ×2

recursion ×2

line-breaks ×1