Title: Merge sort Python implementation
External sort--merging sort principle
Merge sorting basically merges and sorts two sorted data, and if the data you read is not sorted, you can use other sort methods to process the two data before merging the two sorted data.
Importrandom
Importcopy
Number1 =random.sample (range (100), 10)
Number2 =random.sample (range (100), 10)
Number1.sort ()
Number2.sort ()
Defrecursive_sort (Lista, LISTB):
"""
Recursive implementation
"""
Iflen (lista) = = 0:
return LISTB
Elif len (listb) = = 0:
return lista
Elif Lista[0] < Listb[0]:
return [lista[0]] +recursive_sort (lista[1:], Listb)
Else
return [listb[0]] +recursive_sort (listb[1:], Lista)
Defsort (Lista, LISTB):
"""
Non-recursive implementation
"""
len_a = Len (lista)
Len_b = Len (LISTB)
If len_a = 0:
return LISTB
elif Len_b = = 0:
return lista
Else
i = 0
j = 0
LISTC = []
While I < len_a and J < len_b:
If Lista[i] <= Listb[j]:
Listc.append (Lista[i])
i + 1
Else
Listc.append (Listb[j])
J + 1
While I < len_a:
Listc.append (Lista[i])
i + 1
While J < len_b:
Listc.append (Listb[j])
J + 1
Return LISTC
Printnumber1
Printnumber2
LISTC =recursive_sort (Number1, number2)
Printlistc
LISTC =sort (Number1, number2)
The results of the operation are as follows:
[9, 15, 20, 27, 32, 33, 56, 62, 78, 84]
[29, 35, 46, 50, 66, 69, 84, 87, 89, 90]
[9, 15, 20, 27, 29, 32, 33, 35, 46, 50, 56, 62, 66, 69, 78, 84, 84, 87, 89, 90]
Topic: Traversal string
TheString = ' Ix lixkxex xpxytxhxonx! '
Defprintengine (c):
IFC!= ' x ':
PRINTC,
Map (printengine,thestring)
Output result: I l i k e p y t h o n!
Topic: Division Tips
A python divides two integers, and the default result is an integer. Using the following statement, you can get the result of dividing as a decimal
From __future__ Import Division
Print7/3
Output results:
2.3333333333
Title: Print string Format
print ' | ', ' * ' Ljust (10), ' | '
print ' | ', ' * ' Ljust (10, '-'), ' | '
print ' | ', ' * ' Rjust (10, '-'), ' | '
print ' | ', ' * '. Center (10, '-'), ' | '
For a in range (1, 6):
print ' A = '. Ljust (5), repr (a). Ljust (a), ' B = '. Ljust (5), repr (A * 2)
| * |
|*--------- |
|---------* |
|----*----- |
A= 1 B = 2
A= 2 B = 4
A= 3 B = 6
A= 4 B = 8
A= 5 B = 10
Initializing multidimensional Arrays
In Python, initializing a 5x3 array of 0 is a good way to
multilist = [[0 for Col in range (5)] Forrow in range (3)]
Multilist[0][0]= ' Love '
Print Multilist
[[' Love ', 0, 0, 0, 0], [0, 0, 0, 0,0], [0, 0, 0, 0, 0]]