【问题标题】:python recursive function callspython递归函数调用
【发布时间】:2023-04-04 02:37:01
【问题描述】:

我正在尝试实现一个递归函数,但遇到了一些困难,不胜感激。例如,让我们尝试创建一个名为 sliding 的函数来执行此操作

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

也就是说,对于选定的整数,我们沿着字符串滑动,抓取适当长度的子字符串,然后将它们全部返回到一个列表中。

现在我可以(愚蠢地)尝试递归地定义它:

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

这将不起作用,主要是因为list.append() 发生在适当的位置并返回None。所以我的问题是 - 即使有很多 Python 方法出现,有没有办法执行这种递归函数?

这是我目前为止最好的,

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

这会导致

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

这显然不是理想的输出,但方向正确。还有什么其他方法可以做到这一点?感谢您的想法。

【问题讨论】:

  • 您知道+ 列表运算符吗?
  • 也许将 append 改为 extend

标签: python recursion


【解决方案1】:

使用+ 运算符获取新的串联列表:

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

【讨论】:

    【解决方案2】:

    没有递归的解决方案,只是在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"]
    

    【讨论】:

      【解决方案3】:

      这个怎么样?

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

      【讨论】:

        【解决方案4】:

        以下是迭代和递归版本:

        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']
        

        【讨论】:

          【解决方案5】:

          我建议:

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

          而不是追加,因为你会得到很多叠瓦状的物体。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-04-10
            • 2017-12-05
            • 2017-06-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多