Python implements detailed explanation of actual problems sorted by student age, and python actual problems

Source: Internet
Author: User

Python implements detailed explanation of actual problems sorted by student age, and python actual problems

Preface

This article mainly tells you about the use of Python to sort students by age and share the content for your reference and learning. I will not talk much about it below. Let's take a look at the detailed introduction:

Question: define a Class that includes name, gender, and age. Students must be sorted by age.

Input: List of student objects.

Output: List sorted by age.

Idea 1: Use Bubble sorting to compare adjacent students. If the age value of the first student is greater than that of the second student, the two elements are exchanged as a whole. Continue to repeat the above steps for fewer and fewer elements each time. Until there is no comparison between students.

Idea 2: Use the Python internal creation method sorted ().

(This is actually a practical question written by the author during the interview. It is more oriented to Tom. We can review some basic knowledge points of Python through this simple question)

1. Preparations

1.1 define Class

Class Student (object): def _ init _ (self, name, gender, age): self. _ name = name self. _ gender = gender self. _ age = age # obtain the age attribute def getAge (self): return self. _ age # print def printStudent (self): return self. _ name, self. _ gender, self. _ age

1.2 generate a List containing random student objects.

# Generate listdef generateStudent (num) containing random student objects: # num is the number of test objects to be generated list = [] for I in range (num): randName = ''. join (random. sample (string. ascii_letters, 4) randGender = random. choice (['male', 'female']) randAge = random. randint (10, 30) s = Student (randName, randGender, randAge) list. append (s) return list

2. Start sorting

2.1 use Bubble Sorting

The idea is introduced at the beginning. Let's look at the Code:

def sortStudent(list): for i in range(len(list)): for j in range(1, len(list)-i):  if list[j-1].getAge() > list[j].getAge():  list[j-1], list[j] = list[j], list[j-1] return list

2.2 Use the Python internal creation method sorted

The Code is as follows:

Sorted (list, key = lambda student: student. getAge () # Use the age attribute of the object as the Key for sorting

Here we will add some knowledge about sorted () and lambda expressions:

2.2.1 sorted (iterable, *, key = None, reverse = False)

Official documentation

Parameter description:

Key specifies a function of one argument that is used to extract a comparison key from each list element: key = str. lower. The default value is None (compare the elements directly ).
Reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

  • Key can receive a value returned by a specified function (such as a lambda function) as the basis for the specified comparison.
  • The default value of reverse is "False", which is sorted in ascending order. If it is set to "True", it can be sorted in ascending order.

Stability description:

The built-in sorted () function is guaranteed to be stable.

(This method is stable, as described in the official document !)

Principles: the built-in sorted () method in Python uses the Timsort algorithm. The closer the Data is to Ordered Data, the closer the time complexity is to O (N ). In our case, the age attribute is more in line with Ordered Data. If you are interested, click Timsort to view more details!

2.2.2 lambda expressions

Simply look at a simple example to understand it ~

>>> Pairs = [('one', 1), ('two', 2), ('Three ', 3), ('five', 5 ), ('zero ', 0), ('four', 4)]> sorted (pairs, key = lambda pair: pair [1]) # The tuple pairs in the List are sorted Based on the 2nd values in the tuple [('0', 0), ('one', 1), ('two', 2 ), ('Three ', 3), ('four', 4), ('five', 5)]

3. run the test.

Construct random data for testing and calculate the execution time of the two methods for comparison ~

If _ name _ = '_ main _': # The list format is [('hzdw ', 'female', 17)...] list = generateStudent (10000) # Method 1: use bubble to sort start_Time1 = time. time () sortStudent (list) end_Time1 = time. time () # In method 1, the sorting time of 10000 test data is more than 22.243 seconds (inaccurate) print ('% s cost time % s' % ('sortstudent ', end_Time1-start_Time1) # Method 2: Use the Python built-in sorted method + lambda expression # because the timsort method is used behind the sorted method, when the data is closer to Ordered data, the closer the time complexity is to O (N ). # In this example, the age attribute is close to Ordered data. Start_Time2 = time. time () sorted (list, key = lambda student: student. getAge () # Use the object attribute as the sort Key end_Time2 = time. time () print ('% s cost time % s' % ('sorted', end_Time2-start_Time2 ))

Test results:

Use method 1 (Bubble Sorting). When the number of tested data records is 10000, the sorting time is about 22.243 seconds.

Use method 2 (internal creation method). When the number of tested data records is 1000000, the sorting time is about 0.575 seconds.

Although not accurate, the difference is clearly visible!

Above.

In case of any errors, please correct them ~

Complete implementation and testing can be found on Github: ActualProblem-Solution

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

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.