Pregunta

I'm having trouble getting the function to work as in the docstring. When I type in

nested_join(' ', ['one', ['two', 'three'], 'four'])

I get 'one four' instead of ’one two three four’ .

Could someone tell me how to fix it?

Thanks

def nested_join(s: str, L: list) -> str:
    """Return join of nested list of strings L with separator string s
    >>> nested_join(’ ’, [])
    >>> nested_join(’ ’, [’one’])
    ’one’
    >>> nested_join(’', [’one’, ’two’])
    ’one two’
    >>> nested_join(' ', ['one', ['two', 'three'], 'four'])
    ’one two three four’
    """
    res = []

    for i in range(len(L)):
        if isinstance(L[i], str):
            res.append(L[i])
        else:
            nested_join(s, L[i])

    return str.join(s, res)
¿Fue útil?

Solución

Change your for loop. You aren't doing anything with the recursive call.

def nested_join(s, L):
    res = []

    for i in range(len(L)):
        if isinstance(L[i], str):
            res.append(L[i])
        else:
            res.append(nested_join(s, L[i]))

    return str.join(s, res)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top