1 classTest (object):2 defrangetest (self):3 forIinchRange (2,0,-1):4 PrintI5 PrintI6i=27 whileI>0:8 PrintI9I=i-1;Ten PrintI
As shown in this code, the output results are
for (2 1)
1
while (2 1)
0
This is a very obvious result. But I confuse the two in the application, causing the program to fail.
The following is an insertion algorithm
1 classinsertion (orderstrategy):2 defSort (Self,args):3args =list (args)4Length =len (args)5 forIinchRange (1, length):6temp =Args[i]7 #For J in Range (i,-1,-1): #range don ' t contain the stop element so the middl-1 means stop at 08 #if args[j-1] > Temp: #here should check j>0 though no error occurs9 #Args[j] = args[j-1]Ten #Else: One # Break Aj=i; - whileJ>0: - ifARGS[J-1] >Temp: theARGS[J] = args[j-1] -J=j-1; - Else: - Break +ARGS[J] = Temp#Asignment The current (position I) element to J (the first element less than it in the left side of I) - + Print "Insertion:" A Printargs at returnArgs
Code with line 7th to 11th is not replaced by line 12th to 18th.
In C #
for (var i = 0; i < i++) { }
He's going to have boundary detection, I will increment to 10, and the result is false, then end
Python's for is only used to traverse the element, and there is no comparison to let him end early. Of course you can force the exit traversal by adding a break in the traversal, as follows
for in Range (i,-1,-1):#range don ' t contain the stop element so the middl-1 means stop at 0
if
and j>
0: = args[j-1
]
else
:
break
This code has an effect with the top 12-18 lines. (But I'm afraid no one will use it ~ ~ ~ after all, Python would have supported negative indexing)
It is the misuse of your own grammar that causes errors and only reminds yourself of the record.