Python algorithm problem----inverse sequence table

Source: Internet
Author: User

There is such a list [1, 2, 3, 4, 5, 6, 7, 8, 9] programmed to implement the list in reverse order, turning it into [9, 8, 7, 6, 5, 4, 3, 2, 1].

Topic has, see how to answer, reverse order, only need to first and the penultimate, the second and the penultimate, until the middle of the position of the number in turn to exchange.

Assuming the list is data and the list length is Len (data)

[1, 2, 3, 4, 5, 6, 7, 8, 9]

0 1 2 3 4 5 6 7 8

The following conclusions can be drawn from the list and its subscript:

The 1th element of the list is labeled 0 and the last element is Len (data)-0

The 2nd element of the list is labeled 1 and the last element is Len (data)-1

The 3rd element of the list is labeled 2 and the last element is Len (data)-2

Then we go through the list and assume that the loop variable is I, the above rule can be expressed as len (data)-1-i


Now start writing code implementations:

def inverse (data=none): If not data or not isinstance (data, list) or Len (data) < 1:return n = len (data) For I, V in Enumerate (Data[0:int (N/2)]): If v < data[n-1-i]: Data[i], data[n-1-i] = Data[n-1-i], da Ta[i] # swap element return data


Unit Test

Testing is important, especially to implement complex functions, in order to avoid each change in the code to insert a bunch of print, it is best to write test code, an investment, the long-term return. Ha ha!

Import Unittestclass testinversemethods (unittest. TestCase): def test_inverse (self): data = [1, 2, 3, 4, 5, 6] result = [6, 5, 4, 3, 2, 1] Self.asse Rtequal (Inverse (data), result) if __name__ = = ' __main__ ': Unittest.main ()


.

----------------------------------------------------------------------

Ran 1 Test in 0.002s


Ok


If you see the output as above, it means that the test passed

This article is from the "Candle Shadow Red" blog, be sure to keep this source http://gccmx.blog.51cto.com/479381/1736119

Python algorithm problem----inverse sequence table

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.