Everything starts from the game: The next day: Tight Night: Term: After class review:
Everything starts from the game:
The story is fiction, which is from a real game again.
origin:
This is a sunny Saturday afternoon, you browse online. Suddenly you see a small game on a message board. It is very simple,
The problem is: put five numbers 56789, put them in {{{[] [] [] * [] [], the result is the biggest.
You said the first to himself: "What is difficult to put the biggest place in the maximum number of seats." You will count again, maybe it is wrong. Every result should be seen in other locations. You started thinking about some interest, anyway, you are learning a fun programming language, why not practice?
So you start your beloved Python, start thinking: "In fact, I want a program, I give it a variety of numbers, then it automatically finds the biggest one. If I passed 1, 1, 1 1, 1, 1, 1, 1, 2, it will know that 111 * 11 and 111 * 12, find a larger 111 * 12 and output this combination and its product. This program is not difficult Well."
1 # Calc.py
2 DEF CALC (SEQ):
3 maximum = 0
4 MAX_Item = []
5 for i in seq:
6 product = (i [0] * 100 i [1] * 10 i [2]) * (i [3] * 10 i [4])
7 IF Product> Maximum:
8 Maximum = Product
9 MAX_ITEM = I
10 Elif Product == Maximum:
11 MAX_ITEM = ',' i
12 Return Max_Item, Maximum
13
14 SEQ = [[5, 6, 7, 8, 9], [5, 6, 7, 9, 8]]
15 Max_Item, Maximum = CALC (SEQ)
16 Print "Maximum at", Max_Item, ", Product", Maximum
You tried it,
$ Python Calc.py
Maximum at [5, 6, 7, 9, 8], Product 90160
No problem. Now you just have to give all the arrangements. You have played a few lines, I think [5, 6, 8, 7, 9] is so hard, and use i [0] * 100 i [1 ] * 10 ... method seems to be too ugly, so you need to make a revision. Ok, use the string. "56789", which is convenient, int ("567") * int ("89) ") It should be much better, it should be alive. In addition, you also change the program, it looks like a person who has experienced people.
1 # Calc.py
2 DEF CALC (SEQ, WHERE):
3 maximum, max_item = 0, []
4 for i in seq:
5 Product = Int (i [: where]) * int (i [where:])
6 IF Product> Maximum:
7 maximum, max_item = product, i
8 Elif Product == Maximum:
9 MAX_ITEM = ',' i
10 Print "Maximum at", Max_Item, ", Product", Maximum
11
12 IF __NAME__ == "__main__":
13 SEQ = ["56789", "56798"] 14 where = 3
15 Calc (Seq, Where)
Well, it's better. That sentence if __name__ == "__main__" is set to the future to use Calc.py as a module. In other programs, the line will not run.
Now you can solve more common problems with your own point, such as 123 [] * [] [], or 1234567 [] [] [] [] * [] [] [] this question Now you start to enter the arrangement. "56789", "56798", "56879", "56897", ................................................. Generate these bored arrangements? 56789 has 5! It is 120 kinds of arrangements! If you want to count 123456789, enter the time you may use to use your life !!
So you start thinking about how to generate algorithms. You can use a loop, but the loop will generate a combination of revitalities, such as 555 * 55. But we can add some of the conditions to take the rehabilitation. So you have The first program solution.
1 # permute1.py
2 DEF Permute (SEQ):
3 results = []
4 for a in seq:
5 for b in seq:
6 for c in seq:
7 for d in seq:
8 for e in seq:
9 IF a! = B and a! = C and a! = D and A! = E and /
10 B! = C and B! = D and B! = E and / /
11 C! = D and C! = E and D! = E:
12 result.append (''. Join ([A, B, C, D, E])))
13 Return RESULT
14
15 SEQ = LIST ("56789")
16 where = 3
17 Thelist = Permute (SEQ)
18 Import Calc
19 Calc (Thelist, Where)
Carefully remember to use '' .join () method to generate a string string to use A B C D fast, and also think that it will make you easier for different places easier to use Import Calc. Microwave. You start running the program:
% python permute1.py
Maxmum at 87596, Product 84000
You have succeeded. Ah, you think can be attached to the message board to reward. After some considerations, what do you think is to make more common functions, how many numbers are allowed to enter, how to split. Program, you feel that you can't meet the requirements, because you don't know how many numbers you want beforehand, so you don't know how many loops want to write. Face this situation, you seem to have a recurrent method. .
You know how to get, for example, 5 numbers are arranged: first pick a number, there are five options; if you choose a number, there are only four options left, so on this class. So five There are a total of 5 * 4 * 3 * 2 * 1 total 120 arrangements. When you face the five numbers of "56789", you will pick a number, for example, 6, the rest is one The four numbers are arranged. That is to say, 56789's arrangement can simplify (or simple complications: P) all arrangements of all arrangements of the word head to 5, all arrangements of 7 all arrangements of 7 All arrangements of the plumpet 8 are set to 9 all the arrangements. I want to pass this, you decide to write with the recursive function, first select 5 in 56789, then put the remaining 6789 A new problem with a new four-digit arrangement calls the function again to get all the arrangements of 5 - the stroke; then select 6, the remaining 5789 call function. And each time you ask 6789 or 5789's arrangement It simplifies another number of three numbers, until there is only one number left. The following is your function, but you still don't know if it is correct, because writing recursive functions is very error, so You have to try it first.
1 # permute2.py
2 DEF Permute (SEQ):
3 l = LEN (SEQ)
4 if l == 1:
5 Return [SEQ]
6 Else:
7 res = []
8 for i in range (Len (SEQ)):
9 Rest = SEQ [: i] seq [i 1:]
10 for x in permute (REST):
11 res. lot (SEQ [i: i 1] x)
12 Return RES
13
14 SEQ = LIST ("1234")
15 thelist = permute (SEQ)
16 thelist = ['' .join (x) for x in · elList]
17 Print Thelist
You get the following results after you run:
$ python permute2.py
['1234', '1243', '1324', '1342', '1423', '1432', '2134', '2143', '2314',
'2341', '2414', '3142', '3214', '3241', '3412', '3421',
'4123', '4132', '4213', '4231', '4312', '4321']
It seems correct. But if there is any way to come again? You think of a long time, I finally found that you don't have to wait until L = 1, you can do something when l = 2 will do something. Because you know that L = 2, the arrangement must be [[0, 1], [1, 0]], so that you can use some power to help your computer. Of course, if you put the L = 3's arrangement also written Better, but write to L = 4 or more, it is not necessary. This kind of practice in the process is unroll, you can't remember to have learned. Ok, now you have another program.
1 # permute3.py
2 DEF Permute (SEQ):
3 l = LEN (SEQ)
4 if l <= 2:
5 if l == 2:
6 Return [SEQ, [SEQ [1], SEQ [0]]] ELSE:
8 return [seq]
9 else:
10 res = []
11 for i in range (Len (SEQ)):
12 REST = SEQ [: i] seq [i 1:]
13 for x in permute (REST):
14 Res. Append (SEQ [i: i 1] x)
15 Return RES
16
17 SEQ = LIST ("12345")
18 Thelist = Permute (SEQ)
19 thelist = ['' .join (x) for x in theselist]
20 Print theselist
Now you can formally tested. You change permute3.py so you can get numbers and segmentation methods from the command line. The program turns the following, and you also make the same modification for Permute2.py.
1 # permute3.py
2 DEF Permute (SEQ):
3 l = LEN (SEQ)
4 if l <= 2:
5 if l == 2:
6 return [SEQ, [SEQ [1], SEQ [0]]]
7 else:
8 return [seq]
9 else:
10 res = []
11 for i in range (Len (SEQ)):
12 REST = SEQ [: i] seq [i 1:]
13 for x in permute (REST):
14 Res. Append (SEQ [i: i 1] x)
15 Return RES
16
17 Import Sys, Calc
18 SEQ = List (sys.argv [1])
19 where = int (sys.argv [2])
20 thelist = ['' .join (x) for x in permute (seq)]
21 Print 'Got', Len (TheList), 'Items.'
22 Calc.calc (TheList, Where)
You started trial. How long does it take to use the TIME mode to run.
$ TIME PYTHON Permute2.py 56789 3
Got 120 items.
Maximum at 87596, Product 84000
Real 0m0.057s
User 0m0.050s
SYS 0M0.000S
$ TIME PYTHON Permute3.py 56789 3
Got 120 items.
Maximum at 87596, Product 84000
Real 0m0.040s
User 0m0.030s
SYS 0M0.010S
Oh, good. The modified is fast. At this point, you have begun to feel curious. It is a common problem that is aligned. I don't know how others do it. Maybe I should go online to find, or There are one or two program pieces that have been written can be copied. You don't want to make a mistake for a standard answer. Put the permute2.py to post the message board or you will look like a three-stream programmer. This is, you don't want to see it. So you search online. But it seems to be based on the recursive algorithm until some time, you finally saw this in the online program collection station of ASPN: Segment:
1 # permute4.py
2 Def Permute (SEQ, INDEX): 3 SEQC = SEQ [:]
4 seqn = [seqc.pop ()]
5 Divider = 2
6 While SEQC:
7 index, new_index = Divmod (Index, Divider)
8 seqn.insert (new_index, seqc.pop ())
9 DIVIDER = 1
10 return '' .join (seqn)
The author claims that this algorithm is o (n). You don't feel unbelievable, but you may wish to try. Because you understand that this function is only returned to one of the arrangements, you wrote a small ruler. Ferrate it.
1 # test.py
2 from permute4.py import permute
3
4 SEQ = List ("1234")
5 for i in inning (30):
6 Print Permute (SEQ, I),
Test:
$ Python Test.py
1234 1243 1324 1423 1342 1432 2134 2143 3124 4123 3142 4132 2314
2413 3214 4213 3412 4312 2341 2433 3241 4231 3421 4321 1234 1243
1324 1423 1342 1432
Test shows that this function is no problem. How do it do? You study, each different index value is passed back to the only arrangement, and the index that is bigger is from the end, Divider each time To increase one, the list of lists is reorganized by the rest of the business. Hey, no need to college. Hey! Take it. So you can use permute4.py, add a new function to find Factorial, this You can call Permute to get all the arrangements. Time. You have used more numbers so that the speed difference is more obvious.
1 # permute4.py
2 DEF Permute (SEQ, INDEX):
3 SEQC = SEQ [:]
4 seqn = [seqc.pop ()]
5 Divider = 2
6 While SEQC:
7 index, new_index = Divmod (Index, Divider)
8 seqn.insert (new_index, seqc.pop ())
9 DIVIDER = 1
10 return '' .join (seqn)
11
12 DEF FACT (X):
13 f = 1
14 for i in range (1, x 1):
15 f * = i
16 returnif
In one
18 Import Sys, Calc
19 SEQ = List (sys.argv [1])
20 where = int (sys.argv [2])
21 n = FACT (LEN (SEQ))
22 Thelist = [Permute (SEQ, I) for i in inheng (n)]
23 Print 'Got', Len (TheList), 'Items.'
24 Calc.calc (TheList, Where)
$ TIME CPYTHON Permute3.py 1234567 4
Got 5040 items.
Maximum at 6531742, Product 4846002
Real 0m0.461s
User 0m0.440s
SYS 0M0.020S
$ TIME CPYTHON Permute4.py 1234567 4
Got 5040 items.maximum at 6531742, Product 4846002
Real 0m0.389s
User 0m0.370s
SYS 0M0.010S
Wow! It is really not covered. Very good, and now you know the new answer I don't know. I put it on it. Just when you decide, you hesitate: "I don't have very much for this algorithm." Learn, how do you answer if someone asked? This will make me like a thief of the Western copy! No, or I want to understand its principle, or you will be better than it. "You think Zhuangzhi unlimited.
But now it is very late, you have to go to sleep. Helpless you think about better ways in bed, you have not slept all over the evening.
to be continued......
the next day:
You wake up the first thing, washing your face. Programming enthusiasts are not necessarily synonymous with the heads of the world. Then, look at TV newspaper, do some public welfare activities, today is a rising day. Turning less, finally you are Sit down in front of the computer, log in to your favorite slakeWare / redhat / redflag / mandrake / debian / windowsxp / Chinese2000 / dos / solaris / AIX / UNICOS / OSX [Author Press: Please add it to the actual situation, but don't put SCO Also added] These are platforms that Python can run.
You can remember that you have heard it before: any recursive / retrospective function can restore to non-recursive forms. So you decide to use your own way. You can't think of the method, 5 numbers One, 4, then take one, then 3 .... So you write a new program, and the original very much:
1 # permute5.py
2 DEF Permute (SEQ):
3 results = []
4 for i in seq:
5 seq1 = seq [:]
6 seq1.remove (i)
7 for j in seq1:
8 seq2 = seq1 [:]
9 seq2.remove (j)
10 for l in seq2:
11 SEQ3 = SEQ2 [:]
12 seq3.remove (L)
13 for m in seq3:
14 SEQ4 = SEQ3 [:]
15 seq4.remove (m)
16 Result.Append (''. Join ([I, J, L, M, SEQ4 [0]]))
17 Return RESULT
18
19 Print Permute (List ("12345"))
This program sequentially creates a list of 5, 4, 3, 2, 1, each of which does not include the previously selected number, then combines 5 numbers to complete a arrangement. Of course, you have space to do unroll. But now the problem is that your requirements for the program are not to know how many numbers required in advance, that is, you don't know if you want to write a few Forks. But now you think there is a good way: Since Python is dynamic, it You can perform your own code, why not call it yourself to write this loop program to complete the job? You think this way to write the idea of your own writer very science, and let you remember I used to hear a lot of senior veteran 's M4 macro language. So you tried it. You think you can use Counter0, Counter1, Counter2 ... to replace i, j, l, m ... cycle submission .
1 # permute5.py
2 Def genfunc (n):
3 Head = "" "
4 DEF Permute (SEQ0):
5 fruit = [] "" ""
6 boiler = "" "
7 for counter% i in seq% i:
8 SEQ% i = SEQ% i [:] 9 SEQ% I.Remove (counter% i) "" ""
10 for i in range (1, n):
11 Space = '* i
12 head = head boiler.replace ('/ n', '/ n' space)% (i, i-1, i, i-1, i, i)
13 Temp = ','. Join (['counter% I'% (x) for x in inheng (1, n)] ["SEQ% i [0]"% (N-1)])
14 Head = Head '/ N' Space "Result.Append (''. Join ([% s]))"% (TEMP)
15 RETURN HEAD '/ N RETURN RESULT / N'
16
17 Import Sys
18 functext = genfunc (len (sys.argv [1])))))
19 Print functext
20 Exec (FuncText)
21 Print Dir ()
22 thelist = permute (list (sys.argv [1])))
23 Print 'Got', Len (TheList), 'Items.'
Run,
SH-2.05B $ python permute5.py 12345 3
DEF Permute (SEQ0):
Result = []
For counter1 in seq0:
SEQ1 = SEQ0 [:]
Seq1.remove (Counter1)
For counter2 in seq1:
SEQ2 = seq1 [:]
Seq2.remove (Counter2)
For counter3 in seq2:
SEQ3 = seq2 [:]
Seq3.remove (Counter3)
For counter4 in seq3:
SEQ4 = SEQ3 [:]
Seq4.remove (Counter4)
Result.Append (''. Join ([[Counter1, Counter2, Counter3, Counter4, SEQ4 [0]]))
Return RESULT
['__builtins__', '__doc__', '__name__', 'Calc', 'FuncText', 'Genfunc',
'permute', 'sys']
Got 120 items.
It seems that the format is negative. Now calculate the run time, will it be better? Maybe it is faster than before, maybe because you have to execute yourself, it is slower, everything goes to see the actual data! You have modified permute5.py so that it can standardize time. You start thinking that Import Calc is very smart design.
1 # permute5.py
2 Def genfunc (n):
3 Head = "" "
4 DEF Permute (SEQ0):
5 fruit = [] "" ""
6 boiler = "" "
7 for counter% i in seq% i:
8 SEQ% i = SEQ% i [:]
9 SEQ% I.Remove (Counter% i) "" ""
10 for i in range (1, n): 11 Space = '' * i
12 head = head boiler.replace ('/ n', '/ n' space)% (i, i-1, i, i-1, i, i)
13 Temp = ','. Join (['counter% I'% (x) for x in inheng (1, n)] ["SEQ% i [0]"% (N-1)])
14 Head = Head '/ N' Space "Result.Append (''. Join ([% s]))"% (TEMP)
15 RETURN HEAD '/ N RETURN RESULT / N'
16
17 Import Sys, Calc
18 functext = genfunc (len (sys.argv [1])))))
19 #Print Functext
20 Exec (FuncText)
21 Thelist = Permute (List (sys.argv [1])))
22 Print 'got', len (theList), 'Items.'
23 Calc.calc (Thelist, Int (sys.argv [2]))))
start the timer:
$ TIME CPYTHON Permute5.py 1234567 4
Got 5040 items.
Maximum at 6531742, Product 4846002
Real 0m0.213s
User 0m0.200s
SYS 0M0.010S
Ah! That level O (N) is also defeated by you !! You think that its level is not o (n), then it is only useful to find one of the entire arrangement, you want to put the entire arrangement If you count, you still have to go back to N!
You are very proud. But this may be an appropriate thing when it is appropriate. Since you have arrived at this point, why not take more steps, turn a book, maybe you have found it, you have already found it. This is the case, you, an ignorant idiot, the invent of the big blow is joke everywhere.
So you find a computer and mathematical textbook of the dust. I found a chapter of the arrangement and start reading. I finally found such a picture:
[4321]
[3421]
[321] <[3241]
[21] <[231] ... [3214]
[213] ...
[1]
[321] ...
[21] <[231] ...
[213] ...
The book is written, it is necessary to generate a method in which one can be used: "First select one number 1, then the second number 2 can be placed in front or behind. And each 放 will generate a 2-digit number For each such two digits, the third number 3, can be placed in front, middle, or final; thus producing a 3-digit number; and each 3 digits, the 4th digit You can insert all of these three numbers in any of these pushes. The book also lists a program example! And this method is as follows, and the fastest alignment method is scheduled.
You are in a hurry to start the description of the book. With Python, you have got a new program very quickly:
1 # permute6.py
2 DEF Permute (SEQ):
3 seqn = [seq.pop ()]
4 While SEQ:
5 newseq = []
6 new = seq.pop ()
7 #Print "SEQ:", SEQ, 'SEQN', SEQN, 'New', NEW
8 for i in in (len (seqn):
9 item = seqn [i] 10 for J in Range (Len (item) 1):
11 newseq.append (''. Join ([Item [: J], New, Item [J:]]))
12 seqn = newseq
13 #Print 'newseq', newseq
14 Return SEQN
15
16 Import Sys, Calc
17 SEQ = List (sys.argv [1])
18 where = int (sys.argv [2])
19 thelist = permute (SEQ)
20 Print 'got', len (thelist), 'Items.'
21 Calc.calc (Thelist, Where)
The test results are as follows:
$ TIME CPYTHON Permute6.py 1234567 4
Got 5040 items.
Maximum at 6531742, Product 4846002
Real 0m0.167s
User 0m0.150s
SYS 0M0.020S
Wow! The book is self-owned gold house! I can't think of this is the fastest algorithm. You start to felt that this opponent is not easy, and now it is very late, your body and mind are also tired. Have you desperately look at this new program code and its wonderful structure, make the final attempt:
to be continued...
Night watchman:
Got 24 items.
['1234', '2134', '2314', '2341', '1324', '3241', '3214', '3241', '1342',
'3142', '3412', '3421', '1243', '2143', '243', '2431', '1423', '4123',
'4213', '4231', '1432', '4132', '4312', '4321']
The above is the four digits ranked results generated by Permute7.py. You are carefully viewed, and finally see some ends: the arrangement produced is a symmetrical, the first and the last one is the opposite And the second and the second and the second complement is completely opposite. Use these symmetry, maybe you can make a computing time a pair. And you have studied the implementation method of the program, you find as long as you change your line! You can achieve this Features: The first line seqn = [seq.pop ()] is changed to SEQN = [seq.pop () seq.pop ()]. So you realize only half of them, you only need to put it later. The elements in this list have completed the entire arrangement. The program is as follows
1 # permute7.py
2 DEF Permute (SEQ):
3 seqn = [seq.pop () SEQ.POP ()]
4 While SEQ:
5 newseq = []
6 new = seq.pop ()
7 #Print "SEQ:", SEQ, 'SEQN', SEQN, 'New', NEW
8 for i in in (len (seqn):
9 item = seqn [i]
10 for J in Range (Len (Item) 1):
11 newseq.append (''. Join ([Item [: J], New, Item [J:]])) 12 SEQN = NewSeq
13 #Print 'newseq', newseq
14 Return SEQN
15
16 Import Sys, Calc
17 SEQ = List (sys.argv [1])
18 where = int (sys.argv [2])
19 thelist = permute (SEQ)
20 Print 'got', len (thelist), 'Items.'
21 print thelist
22 # This is another discussion
23 # cagc.calc2 (thelist, where)
The test data said that this improved program is just a hundred times faster than the original. This time it should be enough. But to get the entire arrangement, you should re-copy this half list and every element is in turn: "1234 "->" 4321 ". But in the string in Python, there is no inward function, so you must first turn the string into a list, turn it back, however, List.Reverse () This function is very annoying. Will pass any value (because it is in-place), so you have to use i = list (item); I.reverse; i = '' .join (i); this complex method. You think about it This approach will probably waste the time that is only half-half arranged. You think half a day, finally decided to rewrite the Calc.py part to directly use the known half list.
#! python
# cagc.py
DEF CALC (SEQ, WHERE):
Maximum, max_item = 0, []
For i in seq:
Product = Int (i [: where]) * int (i [where:])
IF Product> Maximum:
Maximum, Max_Item = Product, i
Elif Product == Maximum:
MAX_ITEM = ',' i
Print "Maximum at", Max_Item, ", Product", Maximum
DEF CALC2 (SEQ, WHERE):
Maximum, max_item = 0, []
For i in seq:
Product = Int (i [: where]) * int (i [where:])
IF Product> Maximum:
Maximum, Max_Item = Product, i
Elif Product == Maximum:
MAX_ITEM = ',' i
Rev = List (i)
Rev.reverse ()
i = '' .join (REV)
Product = Int (i [: where]) * int (i [where:])
IF Product> Maximum:
Maximum, Max_Item = Product, i
Elif Product == Maximum:
MAX_ITEM = ',' i
Print "Maximum at", Max_Item, ", Product", Maximum
Of course, you have retained the previous function CALC and just add a CALC2 function that is specially called to permute7.py. You tried the speed, successful than permute6.py. Although it is just this, you also I feel very happy. Because it is once, you feel improved for a good way. Although you know that if you integrate Calc.py into the arranging generator, you will have a better speed of speed, but You feel that many people can agree with your ability. And you can use an efficient alignment generator to be a smart approach, because you will use it again in the future. You read all the programs From Permute1.py to Permute7.py, I have made a speed of verification. Anyway, the last time, simply do a big.
$ TIME PYTHON Permute2.py 123456789 5
Got 362880 items.
Maximum at 875319642, products 843973902
Real 0m46.478s
User 0M46.020S
SYS 0M0.430S
$ TIME PYTHON Permute3.py 123456789 5
Got 362880 items.
Maximum at 875319642, products 843973902
Real 0m38.997s
User 0m38.600s
SYS 0M0.400S
$ TIME PYTHON Permute4.py 123456789 5
Got 362880 items.
Maximum at 875319642, products 843973902
Real 0m33.845s
User 0m33.460s
SYS 0M0.380S
$ TIME PYTHON Permute5.py 123456789 5
Got 362880 items.
Maximum at 875319642, products 843973902
Real 0M10.681s
User 0M10.530S
SYS 0M0.150S
$ TIME PYTHON Permute6.py 123456789 5
Got 362880 items.
Maximum at 875319642, products 843973902
Real 0m8.279s
User 0m8.110s
SYS 0M0.170S
$ TIME CPYTHON Permute7.py 123456789 5
Got 181440 Items.
Maximum at 875319642, products 843973902
Real 0m7.827s
User 0M7.650S
SYS 0M0.180S
Well, it is very good. The fastest is more than seven times higher than the original! So you intend to post this best formula to the Internet tomorrow, let more people share. You are very safe to sleep. .
But I don't know what to do, you always feel that there is something wrong with you, what else is there? You can't think of it, it is fascinated by confused an uneasy mood.
I finally couldn't help but climb it up. I went back to the computer screen. You think of a fatal problem, for a big arrangement, permute7.py will try to make all the arrangements. Don't have to use computer resources will be fired. You may want to think about a method, do only one arrangement each time. But you can use all the arrangements 1, 2, 3, 4 to the number of methods?
You look at the pictures of the textbook, such a tree structure should have a way, you said to yourself.
Slowly read the text on the book. Imagine that there is N numbers, first take the first number. Take the second number, the second number can be placed on the left or right side of the first number, there is 0, 1 two Selection. Take the third number, put it in front of the previously selected two digits, can be placed on the left, middle, the right right, there is 0, 1, 2 three options. Well, is it natural? Sudden You think of the two-in-one, eight into the digital conversion relationship. "I can design such a number, ... XYZ, where the bit number z is bin, that is, the second number of two positions; ten The number Y is the three-in-one, the table is placed in three seats, and then the number of hundreds is the four-in-one, the thousands is the five-in-one, according to the push. "Yes, if this is designed, if 0 Indicates that the number "2021" represents five elements (ABCDE), and then one A, then the second B is placed on the right side of A. ABC, take the right right, and becomes ABC. Take D to the leftmost to DABC; final E put it in the middle to become DAEBC. As for the number of "2021" this special design can be used .. x * 4 y * 3 z * 2 This calculation is reflected Go to the number of natural numbers. Yes, if you see 4 numbers 4! = 24 arrangements, the 18th arrangement can be obtained, 18 except 2, the remainder is 0, so the second number is placed in the first one The left side of the number; then the merchant 9 will be divided by 3, the remainder is 0, so the third is the leftmost number of two numbers in the head; the last 3 is divided by 4, the remainder is 3, so the fourth number is in the top three The 4th vacancy, that is, the rightmost. Using this method, you don't have to ask for the entire arrangement before you can start calculation. Although this seems to sacrifice time, you can save a lot of space. You can calculate 1000 numbers The biggest arrangement method, even if it may be used for a few months. You are more happy to use this method, you can take the entire calculation into a one part: For example, seek 10! = 3628800 Arrangement, You can make a computer to do a computer, 1000001 to 2000001, let another one ... everyone's work is not over, this is equal to implementing parallel operations! Ah! Wonderful!
Suddenly, you are flashing, right, this is not permute4.py algorithm! You haven't understood it yesterday, now you have fully understood. Hey, although such a good algorithm is not your original, but You are still very excited. Because your ideas are actually consistent with those big cows. You gradually remember when you are still playing the DOS game machine, there is a weird person to boast you in a computer poker game. With a great shuffling method, how fast, and fair, don't be afraid of hackers with known random tables. Now you guessed, the algorithm is likely to be this one. 52 Brand, if you want to calculate 52 in advance! The arrangement can be shuffled.
You feel comfortable, you have sorted out the program, I plan to tell you the results. However, the uneasiness just came again. You will be the best program again, and you will comfort yourself: "10 million Don't fall into the trap of low-class programs. They are madly pursuit, but they never know their goals, don't know what is good. The perfect design is not that you can't add new features, perfect design It is no longer able to streamline the existing features. "You think permute7.py has been close to this limit. But your heart is not there soon, a suspension is rising, maybe you are too Tired, then you decide to close your eyes and start online, but you can't get into the dream quickly.
to be continued...
Terminal:
You have made a dream, you see that Avan is coming to your face and challenge you: "Unless you answer my problem, my scorpion will keep in your ear. The screaming makes you can't sleep well! The problem is: Put the number 56789 in [] [] * [] [] to get the biggest product ... "You have a smile, just want to offer At the time of your permute7.py, I suddenly remembered that Aki was impossible to understand the computer programming! Your heart is cool, a big cut: Avanti's method must not have to use the computer to calculate all the arrangement methods, and very fast Know the answer. As you are awakening, you woke up, I found that you have a picture on the computer desk, accidentally pressing the direction keys on the keyboard, making your computer a painful BEEP voice Recall the dream, you plan to leave the computer temporarily, go back to the question itself: How can I "see" the biggest product?
You take the paper and start calculation:
Suppose five numbers [a] [b] [c] * [d] [e], the expanded words become
A * 100 * D * 10
a * 100 * e * 1
B * 10 * D * 10
B * 10 * E * 1
C * 1 * D * 10
C * 1 * E * 1
This can be written into a matrix:
DE
A 1000 100
B 100 10
C 10 1
You think this: In the entire answer, the pages brought by A are a hundred digits plus a ten digit, and the page of D is a hundred digits plus ten digits plus a bit number, so D is better than A is more important. To achieve the greatest point of accounting, you must put the largest 9 in the 56789 in the position of D, then A, so push.
For convenience of calculation, you simply use the logarithmic number 100 = 10E2, and 2 to represent it, so:
DE
A 3 2
B 2 1
C 1 0
Calculate each line or column, call it as the base value of the number, we get
A = 5, B = 3, C = 1, D = 6, E = 3.
咦? B and E base value are the same, what to do!
You think: "Ah! Because we used the logarithm, and log (1) = 0, therefore ignored the tiny between B and E!" Well, try to increase each number. get:
DE
a 4 3
B 3 2
C 2 1
Thus the base becomes: a = 7, b = 5, C = 3, D = 9, E = 6. These bases represent the importance of this location, and different numbers can be gated according to the size.
Ok, allocate the number by the size of the base, you got 865 * 97. A pair answer, 哟! Different! The correct solution is 875 * 96. Where is wrong? Take a closer analysis, you find B and E interchange. The reason is this:
B Pages: B * D * 100 B * E * 10 E Pages: E * a * 100 E * B * 10 E * C
The pages of rough look E, but because we distribute 9 to D and 8 is given to A, the final result is that the actual page of B is longer than E. Since E and B have only different differences in E * C This bit number, the distribution results between D and A are covered with this small difference.
You have considered: "To calculate this coverage, you may be a second-order group. For example, the base of B * D is 100, but because the base of D is 9, the second-order base of B is 9. Represents and B is a more important number; the same number of e * a is also 100 but because the base of A is only 7, the second-order base of E is only 7. This will give it that B is more than E. Important. "
So you have an idea: first write the correlation matrix, then calculate the base of each number and the second order group, then sort it, when the two courses are very close, it is more important. Um, you I feel that I am smart, so I started to check, but I found out that the second-order base of B and E was originally the same!! Everyone is 15. Maybe we have to use a three-order base to distinguish them. You think about it again. Some new second-order base definitions, some indefinite answers, but you gradually feel that it is not very appropriate. Because even if you can get 56789, but in more arrangements, such as 7 digits or even 9 digits How do you guarantee the answer to be accurate, and how is the two bases to be more close? Carefully review your method, use the right number and even directly add to the so-called base, all, is all impromptu, millions Not rigorous. Or truly solve the need to put every situation, and if you do, you must calculate N! So many times! Say it is still necessary.
You are somewhat disappointed, but I feel relieved in the secret because it is permute7.py gets the last victory. You stretched a lazy waist. It turned out that the sky was bright. At this time, you feel a little hungry, take a half The cool bun, rushing some. You are sitting about ten minutes against the empty fluoresch screen, then the answer enters your mind, the mystery is unspeakable.
Your way is to find "Importance" in all positions (using your language is the number of optional), then assign the largest number to the most important position. But the importance of the location is entangled with other locations. Therefore, the importance of all positions once must consider a large number of different combined arrangements and are not practical.
However, we can actually only seek only the first maximum of the largest base (the largest base of ABC * DE), this largest base is no controversial. When you find this location, you simply put the biggest The number is placed on this bit, then finds a base, finding the next largest seat, this seat is also unimagined. In this way, the original arrangement of 5 numbers is simplified to 5 simple back Circle. A problem for Factorial (n) becomes N times!
Ah!
You are good, from another angle:
If 5 numbers are the same, 11111, the largest product can only be 111 * 11, now allowing a number of numbers, which will make the biggest biggest?
211 * 11, 121 * 11, 112 * 11, 111 * 21, 111 * 12? The answer is 111 * 21, that is, the position of D. Good, replace D to 9.
The problem becomes 5 numbers, 111 * 91, change a number (except 9), which one is changed?
211 * 91, 121 * 91, 112 * 91, 111 * 19? The answer is 211 * 91, that is, the position of A. Good, replace it into 8.
According to this type, the answer is 875 * 96.
You reopen your computer and quickly entered the new method and renamed it.py.
1 DEF SOLVE (SEQ, WHERE):
2 n = LEN (SEQ)
3 seq.sort ()
4 SEQ.REVERSE ()
5 Table = [[] for i in range (n)]
6 left, right = where, n - where
7 leftr = long ('1' * left)
8 Rightr = long ('1' * right)
9 flag = []
10 for item in [int (x) for x in seq]:
11 for i in range (left):
12 Table [Left-I-1] = (Leftr 10 ** i) * Rightr
13 for i in tribution:
14 Table [Right-i where-1] = Leftr * (Rightr 10 ** i)
15 for i in flag:
16 Table [I] = 0
17 TABLESORTED = Table [:] 18 TABLESORTED.SORT ()
19 MAXINDEX = Table.index (TableSorted [-1])
20 IF maxindex> = where:
21 Rightr = Rightr (Item-1) * 10 ** (Right-MaxIndex WHERE-1)
22 Else:
23 Leftr = Leftr (Item-1) * 10 ** (Left-maxIndex-1)
24 flag.append (maxIndex)
25 #Print MaxIndex, Leftr, Rightr
26 RTURN LEFTR, RIGHTR
27
28 Import Sys
29 Leftr, Rightr = SOLVE (List (sys.argv [1]), int (sys.argv [2]))))
30 Print "Maximum at", Leftr, Rightr, ', Product', Leftr * Rightr
You check the result, completely right! At this time, you can once again TIME's speed
$ TIME PYTHON Permute7.py 123456789 5
Got 181440 Items.
Maximum at 875319642, products 843973902
Real 0m7.827s
User 0M7.650S
SYS 0M0.180S
$ TIME Python Wise2.py 123456789 5
Maximum at 87531 9642, Product 843973902
Real 0m0.042s
User 0m0.010s
SYS 0M0.030S
Wow! It's almost two hundred times! Of course. If you are more than a more bit, you will be more fast, because wise.py jumps from N!'S restrictions.
You are now feeling more comfortable. You really solve this problem. You are no longer afraid that someone will write faster 10 times the program. You have both "smart" answers (soft solution) to deal with Avanti and His scorpion, and in hard solution, you are also confident with the world's first array generator. You are completely satisfied, you will not feel tired, the heart is suspected of being empty. At this time, your body feels a shudder but In the heart, I'm happy, you first feel the baptism of the programming. And you learned that all the masters have attitude: I can't use Chinese to describe, this attitude is called "to hack". You know You are skilled and keep this attitude to face problems in life, you can quickly go out of the mountain.
Your last time I browsed your program code, found in wise.py, in fact, each cycle is completed, the most important position and the most appropriate seat are not controversial, so replace two numbers in peace of mind Instead of one, the program can be twice as fast. But you feel that it is enough now, you have a Zen machine to speak from the language: "I have found the Mingyue, and I've been entangled. It's just a fortune. Hand. "You are proficient in the system and close the computer, you know that you can really sleep with peace of mind this time.
Hey! The sky is bright, today is a week, you have to go to work. Hey! I have to be said to work in a worm by the boss, get off work ... miserable .......
Finished.
After class review:
I) In the above story, we have seen five ways to solve programming problems.
This is easier to communicate with others, so it is easier to communicate with others and find relevant information. I try to find a answer. I have a better answer online. I want a way to defeat this better answer. Turning the textbook or literature Since the basic start thinking is the best solution. These books can be chosen to have a reason to have it. The special case of research issues may have a good method.
2) There are only two or 30 lines in each program in the story.
3) The Python program is concentrated, and its language is also clear. Back to the above program, you will find that they all don't understand. This shows that the Python is easier to maintain. IV) In the story, we have a big The space is to discuss the method and only a small part is to describe the language characteristics of Python. This proves that Python is more suitable for teaching programming. In fact, Python author guido and many people think Python is the preferred language of computer education. Teachers can let students think quietly, and learn the rules of learning; rather than crazy, beat the keyboard, and remember a quirky feature of a large pile of computer languages.
5) The entire story is less than the improvement of the algorithm and less touches the Python program. Maybe it is continued (if any), we have to try to improve under the conditions of the fixed algorithm and minimize the code code. The efficiency of the Python program. The way I think about is:
Use new and faster syntax. Such as Yield, Generator. With Python's own optimization options and built-in modules. Use third-party extension modules, such as Numpy, SCIPY. Indefes with compilation, such as Freeze, Py2exe With the JIT class, such as psyco. With Thread, in parallel to multi-CPU's machine. Finally, it is necessary to make a big retrieval. Use c to do it. More 'to hack' feels, modify Python trunk, Add a secondary function like String.Reverse ().
Test hardware used in the article:
CPU: Pentium III 866 RAM: 128 MB
Test software used in the article:
Slackware Linux: 9.0 Linux Kernel: 2.4.2 GCC: 3.2.2 Python: Modified 2.1.3
7) The cool steamed bun is helpful to the brain.
8) If you can think of a better way, welcome to contact himself: glace_at_chinesepython.org
(This article is first published in http://www.dohao.org technology forum)