0

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?

1
  • 1
    what a terrible homework for python ... Commented Feb 23, 2015 at 22:38

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Your algorithm builds up a chain of deferred operations which is a recursive process as well as a recursive procedure. The others are iterative processes but they are still recursive procedures
2

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

Comments

0

You can use extend instead of append:

tup.extend(split_path(new_str))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.