deffunc(x=10): print'the beginning of function' if x <= 0ornotisinstance(x, int): return for i inrange(x): print'before yield', i yield i print'after yield', i
******************** the beginning of function before yield 0 -> yielding: 0 ******************** after yield 0 before yield 1 -> yielding: 1 ******************** after yield 1 Traceback (most recent call last): File "D:\Projects\test.py", line 28, in <module> print '-> yielding: %s' % gen.next() StopIteration
defbubble_sort(arry): n = len(arry) while n > 1: n -= 1 for x inrange(n): if arry[x] > arry[x+1]: arry[x], arry[x+1] = arry[x+1], arry[x] return arry
改进版本
1 2 3 4 5 6 7 8 9 10 11 12
defbubble_sort(arry): n = len(arry) while n > 1: n -= 1 swap_flag = False# 增加一个标记,当排好序后直接退出 for x inrange(n): if arry[x] > arry[x+1]: arry[x], arry[x+1] = arry[x+1], arry[x] swap_flag = True ifnot swap_flag: break return arry