6.00 introduction to computer science and programming LEC 9: Lecture 9: memory and search methods

Source: Internet
Author: User

This LEC mainly talks about sorting algorithms, starting with the implementation of list. The list in python is obviously variable. You can add or delete various types of elements to it freely, and you can use subscript to search for them, which is similar to the list in Java. The list in Python obviously cannot be implemented with continuous memory space, because the elements stored in the list can be of different types. The linked list can solve this problem, but there is a efficiency problem, for example, if you want to search for the 199th alist [198] elements in list alist, You need to link it for 198 times. If the pure array and pure linked list cannot solve this problem, combining the two can form a better solution. Shows the implementation of list in Python:

The other parts of this LEC are mainly focused on the explanation of common sorting algorithms. Just paste the code and look at it:

def bSearch(L, e, low, high):    if high - low < 2:        return L[low] == e or L[high] == e    mid = low + int((high - low)/2)    if L[mid] == e:        return True    if L[mid] > e:        return bSearch(L, e, low, mid - 1)    else:        return bSearch(L, e, mid + 1, high)def selSort(L):    """Assumes that L is a list of elements that can be compared       using >.  Sorts L in ascending order"""    for i in range(len(L) - 1):        #Invariant: the list L[:i] is sorted        minIndx = i        minVal= L[i]        j = i + 1        while j < len(L):            if minVal > L[j]:                minIndx = j                minVal= L[j]            j += 1        temp = L[i]        L[i] = L[minIndx]        L[minIndx] = temp        print 'Partially sorted list =', L##L = [35, 4, 5, 29, 17, 58, 0]##selSort(L)##print 'Sorted list =', Ldef merge(left, right, lt):    """Assumes left and right are sorted lists.     lt defines an ordering on the elements of the lists.     Returns a new sorted(by lt) list containing the same elements     as (left + right) would contain."""    result = []    i,j = 0, 0    while i < len(left) and j < len(right):        if lt(left[i], right[j]):            result.append(left[i])            i += 1        else:            result.append(right[j])            j += 1    while (i < len(left)):        result.append(left[i])        i += 1    while (j < len(right)):        result.append(right[j])        j += 1    return result            def sort(L, lt = lambda x,y: x < y):    """Returns a new sorted list containing the same elements as L"""    if len(L) < 2:        return L[:]    else:        middle = int(len(L)/2)        left = sort(L[:middle], lt)        right = sort(L[middle:], lt)        print 'About to merge', left, 'and', right        return merge(left, right, lt)##L = [35, 4, 5, 29, 17, 58, 0]##newL = sort(L)##print 'Sorted list =', newL##L = [1.0, 2.25, 24.5, 12.0, 2.0, 23.0, 19.125, 1.0]##newL = sort(L, float.__lt__)##print 'Sorted list =', newLdef lastNameFirstName(name1, name2):    import string    name1 = string.split(name1, ' ')    name2 = string.split(name2, ' ')    if name1[1] != name2[1]:        return name1[1] < name2[1]    else:        return name1[0] < name2[0]def firstNameLastName(name1, name2):    import string    name1 = string.split(name1, ' ')    name2 = string.split(name2, ' ')    if name1[0] != name2[0]:        return name1[0] < name2[0]    else:        return name1[1] < name2[1]##L = ['John Guttag', 'Tom Brady', 'Chancellor Grimson', 'Gisele Brady',##     'Big Julie']##newL = sort(L, lastNameFirstName)##print 'Sorted list =', newL##newL = sort(L, firstNameLastName)##print 'Sorted list =', newL

In the above Code, there is an interesting code segment:

def sort(L, lt = lambda x,y: x < y):

Where, Lt = XXXX means that the default value of LT parameter is lambda X, Y: x <Y. Lambda here is a manifestation of the python functional programming style, the following section about Lambda is Excerpt from here: http://woodpecker.org.cn/diveintopython/power_of_introspection/lambda_functions.html

Python supports an interesting syntax that allows you to quickly define the smallest function of a single row. These are calledLambdaThe function is borrowed from lisp and can be used wherever a function is needed.

Example 4.20. LambdaFunction Introduction
>>> def f(x):...     return x*2...     >>> f(3)6>>> g = lambda x: x*2  >>> g(3)6>>> (lambda x: x*2)(3) 6
This isLambdaFunction. Note the short Syntax: there are no parentheses around the parameter list, and ignoreReturnKeyword (implicit, because the entire function has only one row ). In addition, this function does not have a function name, but you can assign it to a variable for calling.
UseLambdaYou do not even need to assign a value to a variable. This may not be the most useful thing in the world. It just showsLambdaA function is just an inline function.

In general,LambdaA function can receive any number of parameters (including optional parameters) and return the value of a single expression.LambdaA function cannot contain commands and cannot contain more than one expression. Do not tryLambdaToo many things are inserted into the function; if you need something more complex, you should define a common function and how long it will take.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.