简体   繁体   English

python递归函数调用

[英]python recursive function calls

I'm trying to implement a recursive function and have run into some difficulties, would appreciate your thoughts. 我正在尝试实现一个递归函数并遇到一些困难,会很感激你的想法。 As an example, let's try to create a function called sliding that does this 作为一个例子,让我们尝试创建一个名为sliding的函数来执行此操作

sliding("python", 2)
["py", "yt", "th", "ho", "on"]

That is, for the chosen integer, we slide along the string, grabbing substrings of the appropriate length, and then return them all in a list. 也就是说,对于所选择的整数,我们沿着字符串滑动,抓取适当长度的子串,然后将它们全部返回到列表中。

Now here's how I might (foolishly) try to define this recursively: 现在,我可以(愚蠢地)尝试以递归方式定义此方法:

def sliding(string,k):
  return s if len(string)==k else [string[:k]].append(sliding(string[1:],k))

This will not work, mainly because list.append() happens in place and returns a None . 行不通的,这主要是因为list.append()发生在地方和返回None So my question is - Is there a way to do this kind of recursive function even though lots of Python methods occurs in place? 所以我的问题是 - 有没有办法做这种递归函数,即使有很多Python方法到位?

Here's the best I've got so far, 这是我迄今为止最好的,

def sliding(s,k):
    if len(s)==k:
        return s
    else:
        temp = [s[:k]]
        temp.append(sliding(s[1:],k) ) 
        return temp

This results in 这导致了

sliding("python",k=2)
['py', ['yt', ['th', ['ho', 'on']]]]

which is obviously not quite the desired output, but is in the right direction. 这显然不是理想的输出,但是方向正确。 What other ways might there be to do this? 还有什么其他方法可以做到这一点? Thanks for your thoughts. 谢谢你的想法。

Use the + operator to get a new concatenated list: 使用+运算符获取新的连接列表:

def sliding(s, k):
    if len(s) < k: return []
    else: return [s[:k]] + sliding(s[1:], k)

Solution without recursion, just small play on slice syntax . 没有递归的解决方案,只是片段语法上的小玩法。

def sliding(s, i):
    return [s[n:n+i] for n in xrange(len(s)-i+1)]

assert sliding("python", 2) == ["py", "yt", "th", "ho", "on"]
assert sliding("python", 3) == ["pyt", "yth", "tho", "hon"]

How about this? 这个怎么样?

def sliding(string, k):
    return [string[i:i+k] for i in range(len(string)-k+1)]

Here are both iterative and recursive versions: 以下是迭代和递归版本:

def sliding(s, window=2):
    for ind in range(len(s) - (window - 1)):
        yield s[ind:ind+window]


def sliding_recursive(s, window=2, ind=0):
    if ind > len(s) - window:
        return []
    strings = [s[ind: ind+window]] + sliding_recursive(s, window, ind+1)
    return strings


>>> list(sliding('python'))
['py', 'yt', 'th', 'ho', 'on']
>>> list(sliding('python', window=3))
['pyt', 'yth', 'tho', 'hon']

>>> sliding_recursive('python')
['py', 'yt', 'th', 'ho', 'on']
>>> sliding_recursive('python', window=3)
['pyt', 'yth', 'tho', 'hon']

I'd suggest: 我建议:

temp.extend(sliding(s[1:],k) ) 

instead of append since you'll be getting lots of imbricated objects. 而不是追加,因为你将获得大量的复杂物体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM