小白一个,有错误欢迎指正,谢谢
递归算法
def QuickSort(arr,start,end):
if start < end:
i,j = start,end
temp = arr[i]
while i < j:
while (i<j) and arr[i] <= temp:
i += 1
arr[j] = arr[i]
while (i<j) and arr[j] > temp:
j -= 1
arr[i] = arr[j]
arr[i] = temp
QuickSort(arr,start,i-1)
QuickSort(arr,i+1,end)
return arr
QuickSort = lambda arr : arr if len(arr) <= 1 else QuickSort([item for item in arr[1:] if item < arr[0]]) + [arr[0]] + QuickSort([item for item in arr[1:] if item > arr[0]])
递归算法
def BinarySearch(arr,start,end,key):
if start > end:
return -1
mid = start + (end - start)//2
if key > arr[mid]:
return BinarySearch(arr,mid+1,end,key)
elif key < arr[mid]:
return BinarySearch(arr,start,mid-1,key)
else:
return mid
非递归算法
def BinarySearch(arr,key):
low = 0
high = len(arr)-1
while low <= high:
mid = low + (high-low)//2
if key > arr[mid]:
low = mid + 1
elif key < arr[mid]:
high = mid - 1
else:
return mid
return -1
def A_Outer(func):
print(2)
def A_Inner(*args,**kwargs):
print(3)
func(*args,**kwargs)
print(7)
return A_Inner
def B_Outer(func):
print(1)
def B_Inner(*args,**kwargs):
print(4)
func(*args,**kwargs)
print(6)
return B_Inner
@A_Outer
@B_Outer
def func(*args,**kwargs):
print("5:我是func")
#装饰器调用顺序:先调用B_Outer,再调用A_Inner
#打印顺序:
1
2
3
4
5:我是func
6
7
Python中的模块是天然的单例模式,模块在生成时会自动生成一个.pyc文件,下次再使用这个模块的时候,只需要加载.pyc文件即可,不会再次执行模块代码
调用时,只需 from mySingleton import Singleton,就可以使用里面的类Singleton
#这是一个文件名为mySingleton.py的py文件
class Singleton:
def func(self)
pass
singleton = Singleton()
def Singleton(func):
_instance = {}
def _Singleton(*args,**kwargs):
if func not in _instance:
_instance[func] = func(*args,**kwargs)
return _instance[func]
return _Singleton
@Singleton
class A:
def __init__(self,x=0):
self.x = x
a1 = A(1)
a2 = A(2)
print(a1 is a2) #结果为True,说明a1和a2的地址相同
class Singleton(object):
def __init__(self):
pass
@classmethod
def instance(cls,*args,**kwargs):
if not hasattr( Singleton,"_instance")
Singleton._instance = Singleton(*args,**kwargs)
return Singleton._instance
def Fib(num):
if num in (1,2):
return 1
return Fib(num-1)+(num-2)