#๐Ÿ”’ recursion not working as intended

23 messages ยท Page 1 of 1 (latest)

spiral juniper
#

taking a list of integers and duplicating all elements in it while keeping order; no auxiliary structures available
eg: [1,2,3,] becomes [1,1,2,2,3,3]
this is my approach:

def stutter_list(lst):
    if not lst:
        return
    tmp = lst.pop()
    lst.append(tmp)
    lst.append(tmp)
    stutter_list(lst[:-2])```
im thinking i pop the last element in the list, append it twice because the goal is change the parameter of the list given(would the verb for mutable be mutate), and then recursively call the function without the last two elements
spare jasperBOT
#

@spiral juniper

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

regal portal
#

lst[:-2] will make a copy of the list

#

so when the recursive calls make edits to lst[:-2], they are not editing the orignal list

#

try

def stutter_list(lst):
    if not lst:
        return
    tmp = lst.pop()
    stutter_list(lst[:-2])
    lst.append(tmp)
    lst.append(tmp)
spiral juniper
#

doesnt seem to work, same output

#

if lst[:-2] makes a copy of the lst i probably cant use it though(?)

spare jasperBOT
#

:white_check_mark: Your 3.12 eval job has completed with return code 0.

None
vagrant owl
#

!e

def stutter_list(lst):
    if not lst:
        return
    tmp = lst.pop()
    lst.append(tmp)
    lst.append(tmp)
    stutter_list(lst[:-2])
a = [1,2,3]
stutter_list([1,2,3])
print(a)```
spare jasperBOT
sand whale
#

this can be simplified a lot more:

#

!e

def stutter(list):
  if not list:
    return []
  return [list[0], list[0]] + stutter(list[1:])

print(stutter([1, 2, 3]))
spare jasperBOT
sand whale
#

unless it must be mutating in place?

vagrant owl
sand whale
vagrant owl
#

yes

spiral juniper
#

im not sure what mutating in place means, i would like to mutate the parameter that was passed

sand whale
#

ah yeah, that is in-place

spiral juniper
#

also i think that returns a new list(?)

spare jasperBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.