Hi, trying to learn recursion right now.

I'm trying to write this program where it will tell the position of the letter if found in the list. I'm trying to not use the in function or the .index() function to find the position.

I got everything except the position. Any help would be helpful.

My current code is:

def position(lst,pos):

    if lst == []:
        return False
    if lst[0] == pos:
        #this is where i'm stuck, don't know what to change
        return True  
        return position(lst[1:], pos)

l = ['1', 2, 3]
print position(l, '1')  #this would output 0
print position(l, '4')  #this would output False

For this other one, trying to make a recursive function of selection sort.
I'm trying to extract the maximum instead of the minimum and append it to a recursively sorted sublist, but I'm not sure how to do it.
Trying to do this without using a return value.

def selectionsort(a):

    if len(a) <= 1:
        return a
        #stuck here

Ty for any help.

well for the first problem you need an index to increment in order to find the value you need. So I suggest trying this:

def position( l, target, index ):
    if index == len( l ): # this means the targer element is not in the list
        return False
    if index < len( l ) and l[ index ] == target:
        return index
        index += 1   # go to next element in the list
        return position( l, target, index )

l = [ "1", "2", "3", "d", "9", "0" ]
print position( l, "d", 0 )  # where 0 is the starting index

# -> output

as for the selection sort - it can easily be done without recursion. I suggest you try to do it without recursion first and understand it and then use recursion :) If you have any questions about it though, post your code here and we'll try to give you some ideas :)

hope this helps :)

This article has been dead for over six months. Start a new discussion instead.