简体   繁体   中英

Splitting a string with recursion using no loops in python

So I'm trying to figure out this question, it asks me to split a string and returns a tuple of the split strings, this is supposed to be done with recursion, with absolutely no usage of loops. This is the function that I've managed to come up with:

def split_path(s):
    tup=[]

    i=s.find("/")
    if i!=-1:
        tup.append(s[0:i])
        new_str=s[i+1:]
        tup.append(split_path(new_str))


    else:
        tup.append(s)
    return tup

"E:/cp104/2005/labs/lab11t4" is the string I'm putting into the function, the output SHOULD be:

['E:', 'cp104','2005','labs','lab11t4']

but this is what I have:

['E:', ['cp104', ['2005', ['labs', ['lab11t4']]]]]

So right now I'm successfully getting all of the values in the string that I need, I know the problem is that I'm returning a tuple so it's just appending a tuple within a tuple so my outer tuple only has 2 elements in it.

So how exactly do I untuple the inner elements so I can make the final tuple 1 dimensional instead of the 5 dimensional one that I have?

Existing answers are correct as regards the smallest fix to the given program. However, the given program isn't great recursive form. Explicitly building up the result in memory like that is a more iterative sort of idiom.

Here's an alternate version, which is somewhat more in the recursive style:

def split_rec(path):
    i = path.find('/')
    if i == -1:
        return (path,)
    else:
        return (path[:i],) + split_rec(path[i+1:])

This also returns an actual tuple, as in the text of the question, as opposed to a list, as in the code. To make it return a list, replace (something,) with [something] both times it appears.

Change append to extend when you do the recursion. Since you return a list, you want to extend the current list you have, not append another inner list.

def split_path(s):
    tup=[]
    i=s.find("/")
    if i!=-1:
        tup.append(s[0:i])
        new_str=s[i+1:]
        tup.extend(split_path(new_str))
    else:
        tup.append(s)
    return tup

split_path("E:/cp104/2005/labs/lab11t4")
['E:', 'cp104', '2005', 'labs', 'lab11t4']

您可以使用extend代替append

tup.extend(split_path(new_str))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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