0

I wrote a function in python that receive a list of elements, and a string as input, then return a combined list of these two paramteres recursevly. for example:

add_chars([1, 2, 3, 4, 5], "hel") will return [1, 'h', 2, 'e', 3, 'l', 4, 5]

Here is my code:

def add_chars(some_list, some_str, result=[]):
    if some_list==[]: return result
    result.append(some_list[0])
    if some_str!='':
        result.append(some_str[0])
    return add_chars(some_list[1:], some_str[1:])


print(add_chars([2, 3, 18, "what", 9, "else", 8, 5], "absolute"))
# [2, 'a', 3, 'b', 18, 's', 'what', 'o', 9, 'l', 'else', 'u', 8, 't', 5, 'e']
print(add_chars([1, 2, 3, 4, 5], "hel"))
# ([2, 'a', 3, 'b', 18, 's', 'what', 'o', 9, 'l', 'else', 'u', 8, 't', 5, 'e', 1, 'h', 2, 'e', 3, 'l', 4, 5])

I'm just working with recursion and local variables (not globals), So My problem is when I call the function second time, my result list isn't empty (because I passed result list as a parameter), and new data are adding to the old list.
How I can have a clear list when I call the function multiple times? using parameters and local variables.

danial
  • 117
  • 2
  • 8
  • Beause you are re-using the default parameter, which is evaluated *once* when the function is defined. – juanpa.arrivillaga Nov 07 '22 at 23:33
  • As an aside, using recursion here, particularly like this, is *highly* inefficient and this problem could be solved trivially with built in functions or just a loop – juanpa.arrivillaga Nov 07 '22 at 23:33
  • Is that possible to solve the problem with defining a local variable? – danial Nov 07 '22 at 23:37
  • Instead of appending to a single `result` list, have the function `return` its result, adding it to the result of another recursive call if needed. – Samwise Nov 07 '22 at 23:38
  • @Samwise ... thus guaranteeing quadratic time complexity... – juanpa.arrivillaga Nov 07 '22 at 23:39
  • @juanpa.arrivillaga somehow I don't think this assignment is being graded on runtime efficiency. :) – Samwise Nov 07 '22 at 23:40
  • @Samwise that's fine, just pointing this out for people who read this question. – juanpa.arrivillaga Nov 07 '22 at 23:40
  • I'd say that 99% of the time a question asks specifically about how to solve a problem with a recursive function, the objective is to learn about recursion, rather than to write performance-optimized code. – Samwise Nov 07 '22 at 23:41
  • @Samwise I couldn't understand your help about "adding it to the result of another recursive call if needed" . – danial Nov 07 '22 at 23:48
  • 1
    e.g. `return [i[0] for i in (some_list, some_str) if i] + add_chars(some_list[1:], some_str[1:])`. Preceded by `if not some_list and not some_str: return []` so you have a base case once both arguments are empty. – Samwise Nov 07 '22 at 23:51

0 Answers0