单例
单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。
class Singleton(object):
def __new__(cls,*args,**kwargs):
if not hasattr(cls, '_instance'):
orig = super(Singleton,cls)
cls._instance = orig.__new__(cls, *args, **kwargs)
return cls._instance
斐波那契数列
# 方法一:
def func(n):
a, b = 0, 1
for x in range(n):
a, b = b , a+b
return b
# 方法二:
fib = lambda n: n if n <= 2 else fib(n - 1) + fib(n - 2)
二分查找法
二分查找,给出一个已经排好序的列表,注意是已经排好序的,查找指定元素在列表中的位置
def binary_search(list,item):
low = 0
high = len(list)-1
while low<=high:
mid = (low+high)//2
guess = list[mid]
if guess>item:
high = mid-1
elif guess<item:
low = mid+1
else:
return mid
return None
mylist = [1,3,5,7,9]
print binary_search(mylist,3) # 1
冒泡排序
def bubbleSort(array):
maxindex = len(array)-1
maxvalue = array[maxindex]
while maxindex:
for i in range(1,maxindex):
if array[i-1]>array[i]:
array[i],array[i-1] = array[i-1],array[i]
maxindex -=1
return array
array = [3, 0, 1, 832,23,45, 5, 5, 6, 9, 56, 897]
print(bubbleSort(array))
网友评论