#๐Ÿ”’ cant work out why my recursion code isnt wokring(im supposed to return a list of ints=their index)

109 messages ยท Page 1 of 1 (latest)

crimson cipher
#
  index_list=[]
  if plist==[]:
    return 
  elif x==(len(plist)-1):
    return index_list
  elif plist[x]==x:
    index_list.append(x)
  linearSearchValueIndexEqual(plist,x+1)
  return index_list
royal basinBOT
#

Hey @crimson cipher!

Please edit your message to use a code block

Add a py after the three backticks.

```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
#

@crimson cipher

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.

zinc condor
#

Please put in a docstring describing what the function is supposed to achieve.

#

(Grumbling, as I'm putting docstrings in a colleague's code right now ...)

crimson cipher
#

its supposed to take an input list, and then return another list containing all the values within the input list that were equal to the index they were on

#

condition: the list'll always contain integers

#

or might be empty

#

according to visualisation for every recursion a new index_list is made andn appended to wiht the same name

#

whys that happening?

zinc condor
#

So [3,1,2,5,4,7] should return [1,2,4]? Or something else?

crimson cipher
#

yep

zinc condor
#

Why is this recursive?

crimson cipher
#

its supposed to be recursive

#

part of the q

#

cant be iterative

zinc condor
#

Ok.

#

The index_list=[] line make a new empty list on each call. Don't you need a single list to share between the recursive calls? Or do you want to append the result of the inner calls to the list you're making? Thinking the latter based on what's in the code.

crimson cipher
#

yeah

#

got that just now

#

i dont neccessarily need to make a new list

#

just need to rerurn onw witht he desired result

zinc condor
#

So, currently you just discard the result of the inner call.

crimson cipher
#

yeah

#

cuz i make teh list empty again

zinc condor
#

So don't discard it.

crimson cipher
#

but

#

i need to initialze the var to an empty list

#

to append to it

zinc condor
#

You do init it to [] up the top.

#

Then just extend it with whatever you get from the recursive call.

crimson cipher
#

mmm

#

yeah ig

#

thats one way

#

what if i remove all the elemnts that dont satisfy the condition for the given list

zinc condor
#

A recursive function takes the result of the inner calls and combines them to make the result. You're not doing that - you're discarding the result of the inner call.

crimson cipher
#

and then return that

zinc condor
#

That would modify the original list.

crimson cipher
#

so?

zinc condor
#

That might be ok but is a destructive action and might mangle a caller's data.

crimson cipher
#

its still returning the desired result

zinc condor
#

But also, removing items changes the indices of the remaining items.

crimson cipher
#

oh yeah

zinc condor
#

We try to write functions which do not have side effects. Amongst other things, that means not modifying data you gave to the function.

#

It makes everything much easier to think about.

crimson cipher
#

yeah got that

#

but

#

this isnt a class

zinc condor
#

So what?

crimson cipher
#

so i cant rlly initialize an empty list

zinc condor
#

The first line of the function inits an empty list.

crimson cipher
#

yeah

#

but it initializes it for each recursive call

#

i dont want that

zinc condor
#

Why not?

#

I mean, you could pass it through. Like you do for x.

crimson cipher
#

ah

#

make it a parameter

zinc condor
#

Yes.

crimson cipher
#

mmm

#

yeha

zinc condor
#

Or you could keep your current code and append the result of the inner call to your list.

crimson cipher
#

def can

crimson cipher
#

like after the recursive call ends?

zinc condor
#

The recursive call returns the list from the inner call. So just accrue that onto your local list.

crimson cipher
#
  if plist==[]:
    return plist
  elif x==(len(plist)-1):
    return index_list
  elif plist[x]==x:
    index_list.append(x)
  linearSearchValueIndexEqual(plist,x+1)
  return index_list```
royal basinBOT
#

Hey @crimson cipher!

Please edit your message to use a code block

Add a py after the three backticks.

```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
zinc condor
#

The second last line: shouldn't its result get into index_list?

crimson cipher
#

it is

#

im appending it

zinc condor
#

No you're append the value for x. But the result of checking x+1 onward by calling linearSearchValueIndexEqual is discarded. You want that, also.

crimson cipher
#

elif plist[x]==x:
index_list.append(x)

#

isnt this ensuring that happens

#

here its wokring fine

zinc condor
#

Oh you've switched to using a parameter. Ok.

crimson cipher
#

ye

zinc condor
#

Now do me a favour:
run the function twice.

crimson cipher
#

lol wut?

#

like call it twice

zinc condor
#

Yes:

print(linearSearchValueIndexEqual([3,1,2,5,4,7]))
print(linearSearchValueIndexEqual([3,1,2,5,4,7]))
crimson cipher
#

what in the world

#

its adding ontpo the same list

zinc condor
#

Right.

crimson cipher
#

but heres its called once and its still wrong

zinc condor
#

See this line?

def linearSearchValueIndexEqual(plist,x=0,index_list=[]):

The default object for index_list is defined when the function is defined. Not evaluated when the function is called.
So the default list is always the same list. thus the extra items on the second run.

#

Fix this first, then debug whatever else isn't working.

crimson cipher
#

oh yeah

#

the def never runs after the first call

zinc condor
#

The idiom we use in Python for mutable defaults is this:

def linearSearchValueIndexEqual(plist,x=0,index_list=None):
    if index_list is None:
        index_list = []

so that you make a new empty list at call time, if it's left out.

crimson cipher
#

but after the first csll, if appended to , the index_list is never gonna be none again right

#

cuz for the second call of the func the index_list is gonna have the elemtns it got from the forst call

zinc condor
#

No, this:
index_list = []
points the local variable at a shiny new list.
Next call gets a new local variable.

crimson cipher
#

yes but that only happesn if index_list is none

#

after the firs tcall isnt index_likst gonna be filled wiht the ints it got from the first call?

zinc condor
#

Each index_list variable is new. The default None is recorded in the function definition.

crimson cipher
#

yeah but the func def isnt called again after the first call

#

idk

#

i get what ur sayinf but cant visualize it

#

what was the other methd u were referring to

#

where i didn tneed to add a parameter

zinc condor
#

What you were doing the first time. Set index_list=[] at the top of the function.
Then down the bottom where you're discarding the results of the inner recursive call, don't discard those results. Accrue them into index_list.

crimson cipher
#

but how do i accrue them wihtoiour saving them somehwere else first during he recursive call

#
  index_list=[]
  if plist==[]:
    return 
  elif x==(len(plist)-1):
    return index_list
  elif plist[x]==x:
    index_list.append(x)
  linearSearchValueIndexEqual(plist,x+1)
  return index_list```
royal basinBOT
#

Hey @crimson cipher!

Please edit your message to use a code block

Add a py after the three backticks.

```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
royal basinBOT
#
Python help channel closed for inactivity

This help channel has been closed. 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.