Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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("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. So my question is - Is there a way to do this kind of recursive function even though lots of Python methods occurs in place?

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.

like image 879
keegan Avatar asked Aug 29 '26 00:08

keegan


1 Answers

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)
like image 167
Nayuki Avatar answered Aug 31 '26 13:08

Nayuki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!