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