Recursion and Python List

I found out about recursion in python, and I have this code:

def search(l,key):
    """
    locates key in list l.  if present, returns location as an index; 
    else returns False.
    PRE: l is a list.
    POST: l is unchanged; returns i such that l[i] == key; False otherwise.
    """

    if l:   # checks if list exists
        if l[0] == key:     # base case - first index is key
            return True

        s = search(l[1:], key)      # recursion
        if s is not False:          
            return s

    return False            # returns false if key not found

Can someone explain to me that line

s = search(l[1:], key)

does for sure? and what does l [1:] in the list do?

+4
source share
3 answers

The usual way to pass recursive list in functional programming languages - to use a function that accesses the first item in the list (with name car, first, headdepending on the language) and other functions, which refers to the rest of the list ( cdr, rest, tail). There is no direct equivalent in Python to these functions, but we can do this for the same effect using fragments :

lst[0]  # first element of a list
lst[1:] # rest of the elements in the list, after the first

, Python, , (, True False), :

def search(lst, key):
    if not lst:         # base case: list is empty
        return False
    elif lst[0] == key: # base case: current element is searched element
        return True
    else:               # recursive case: advance to next element in list
        return search(lst[1:], key)

- ( ) False ( ):

def search(l, key):
    if not l:
        return False
    elif l[0] == key:
        return 0
    else:
        idx = search(l[1:], key)
        return 1+idx if idx is not False else False
+8

search, l. l[1:] , 1. ,

data = [1, 2, 3, 4, 5]
print data[1:]            # [2, 3, 4, 5]
print data[2:]            # [3, 4, 5]

,

print data[1:4]           # [2, 3, 4]
print data[2:3]           # [3]

( )

print data[:4]           # [1, 2, 3, 4]
print data[:3]           # [1, 2, 3]

. , ,

print data[-2:]          # [4, 5]
print data[1:-2]         # [2, 3]
print data[:-3]          # [1, 2]

, -1, , -2 . .

+3

. ( ), key, l ( ).

, , key . , True . , ( key. False.

This will just tell you if keythe list is, but not the index you can find in.

+1
source

Source: https://habr.com/ru/post/1526030/


All Articles