算法图解龟速练习中~
超级菜狗一枚,正在龟速学习中,有错误希望批评指正!
快速排序练习代码
def quicksort(list):
less = []
more = []
if len(list) < 2:
return list
else:
pivot = list[0] #选择基准点
for i in range(1, len(list)):
if list[i] <= pivot:
less.append(list[i])
else:
more.append(list[i])
return quicksort(less) + [pivot] + quicksort(more)
list = [39, 5, 6, 2, 6, 7, 0, 4]
print(quicksort(list))
和参考代码不太一样,我写的繁琐了。书上的参考代码:
def quicksort(list):
if len(list) < 2:
return list
else:
pivot = list[0] #选择基准点
less = [ i for i in list[1:] if i <= pivot]
more = [i for i in list[1:] if i >=pivot]
return quicksort(less) + [pivot] + quicksort(more)
print(quicksort([10 ,5 ,2, 3]))
从中间选取基准值:
def quicksort2(list):
mid = len(list)//2
if len(list) < 2:
return list
else:
pivot = list[mid] #选择基准点
less = [i for i in list[0:mid] + list[mid+1:len(list)] if i <= pivot]
more = [i for i in list[0:mid] + list[mid+1:len(list)] if i > pivot]
return quicksort(less) + [pivot] + quicksort(more)
list = [39, 5, 6, 2, 6, 7, 0, 4]
print(quicksort2(list))
debug方法推荐
Python装饰器方案
内容来源:递归函数的Debug技巧
def debugHelper(func): # 装饰器
cnt = 0
indent = '│ ' # 根据自己的喜好来选择缩进方式
def wrapper(*args, **kwargs):
nonlocal cnt
# 按照自己的需求来打印 begin
print(indent*cnt,end="")
print(args[0])
# 按照自己的需求来打印 end
cnt += 1
res = func(*args, **kwargs) # 被修饰函数
cnt -= 1
# 按照自己的需求来打印 begin
print(indent*cnt,end="")
print(args[0],':',res)
# 按照自己的需求来打印 end
return res
return wrapper
非常好用,只要在要debug的递归函数之前放上这个函数,再加上@debugHelper即可。
使用案例
def debugHelper(func): # 装饰器
cnt = 0
indent = '│ ' # 根据自己的喜好来选择缩进方式
def wrapper(*args, **kwargs):
nonlocal cnt
# 按照自己的需求来打印 begin
print(indent*cnt,end="")
print(args[0])
# 按照自己的需求来打印 end
cnt += 1
res = func(*args, **kwargs) # 被修饰函数
cnt -= 1
# 按照自己的需求来打印 begin
print(indent*cnt,end="")
print(args[0],':',res)
# 按照自己的需求来打印 end
return res
return wrapper
@debugHelper
def quicksort(list):
less = []
more = []
if len(list) < 2:
return list
else:
pivot = list[0] #选择基准点
for i in range(1, len(list)):
if list[i] <= pivot:
less.append(list[i])
else:
more.append(list[i])
return quicksort(less) + [pivot] + quicksort(more)
list = [39, 5, 6, 2, 6, 7, 0, 4]
print(quicksort(list))
输出结果:
[39, 5, 6, 2, 6, 7, 0, 4]
│ [5, 6, 2, 6, 7, 0, 4]
│ │ [2, 0, 4]
│ │ │ [0]
│ │ │ [0] : [0]
│ │ │ [4]
│ │ │ [4] : [4]
│ │ [2, 0, 4] : [0, 2, 4]
│ │ [6, 6, 7]
│ │ │ [6]
│ │ │ [6] : [6]
│ │ │ [7]
│ │ │ [7] : [7]
│ │ [6, 6, 7] : [6, 6, 7]
│ [5, 6, 2, 6, 7, 0, 4] : [0, 2, 4, 5, 6, 6, 7]
│ []
│ [] : []
[39, 5, 6, 2, 6, 7, 0, 4] : [0, 2, 4, 5, 6, 6, 7, 39]
[0, 2, 4, 5, 6, 6, 7, 39]
看起来就是自动画了递归树。具体解释请看此方法原作者github[递归函数的Debug技巧]
侵删~